Немає опису редагування
Немає опису редагування
Рядок 1: Рядок 1:
local p = {}
local p = {}


function p.season_result(frame)
--- Функція для виведення помилки на сторінку
     local season = frame.args.season
local function error_output(context, error_details)
     local player = frame.args.player
     local safe_details = error_details or "N/A"
     return string.format("<span style='color:red; font-weight:bold;'>[FD2 Error: %s. Page: %s]</span>", context or "Unknown Context", safe_details)
end


     -- Updated list of seasons with new entries
--- Видаляє вікі-посилання [[link|text]] і [[link]]
     local season_titles = {
local function clean_wikilinks(text)
        "Перший_сезон", "Другий_сезон", "Третій_сезон",
    if not text then return nil end
        "Четвертий_сезон", "П'ятий_сезон", "Шостий_сезон",
     -- [[link|text]] -> text
        "Сьомий_сезон", "Восьмий_сезон", "Дев'ятий_сезон"
     text = mw.ustring.gsub(text, "%[%[([^%]|]+)|([^%]]+)%]%]", "%2")
     }
    -- [[link]] -> link
    text = mw.ustring.gsub(text, "%[%[([^%]]+)%]%]", "%1")
     return mw.text.trim(text)
end


    mw.log("Season index: ", season)
----------------------------------------------------------------------
    mw.log("Player name: ", player)
-- ГОЛОВНИЙ ПАРСЕР ДЛЯ ГОРИЗОНТАЛЬНИХ ТАБЛИЦЬ (Сторінка "Гравці")
----------------------------------------------------------------------


    local season_title = season_titles[tonumber(season)]
local function fetch_from_table(page_title, player_name, column_index)
     mw.log("Season page title: ", season_title)
      
 
    if not player_name or player_name == "" then
     if not season_title then
        return error_output("No Player Name", page_title)  
         return "??"
    end
   
    local title = mw.title.new(page_title)
     if not title or not title.exists then  
         return error_output("Page Missing", page_title)
     end
     end


     local title = mw.title.new(season_title)
     local content = title:getContent()
     local content = title and title:getContent()
     if not content then return error_output("Content Read Fail", page_title) end


     if not content then
     -- Шукаємо вміст першої таблиці на сторінці
        mw.log("Error: Content not found for the season page.")
    local table_content = mw.ustring.match(content, "{|.-([|].-.-[|]})")
         return "??"
    if not table_content then
         return error_output("Table Missing", page_title)
     end
     end


     mw.log("Page content loaded, length: ", string.len(content))
     local escaped = mw.ustring.gsub(player_name, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
     mw.log("Page content preview: ", mw.ustring.sub(content, 1, 500))
    -- Патерн для пошуку гравця у вікі-посиланні ([[Гравець]])
    local player_pattern = "%[%[" .. escaped .. "%]%]"
    local result = nil
   
    -- Патерн, який надійно захоплює C1 та РЕШТУ РЯДКА, починаючи з C3, базуючись на C2 (Гравець)
    local pattern_parts = {
        "^%s*|%s*",            -- Початок рядка, роздільник C1
        "(.-)",                 -- 1. Захоплюємо вміст C1
        "%s*[|][|]%s*",         -- Роздільник C1-C2
        player_pattern,        -- 2. Ім'я гравця (у C2)
        "%s*[|][|]%s*",        -- Роздільник C2-C3
        "(.+)$",                -- 3. Захоплюємо РЕШТУ РЯДКА (від C3 до кінця)
    }
    local start_pattern = table.concat(pattern_parts)
 
    -- Ітерація по всіх рядках
     for row in mw.ustring.gmatch(table_content, "\n%s*|-[^%s]*\n(.-)") do
       
        -- Спробуємо зіставити рядок із шаблоном
        local c1, rest_of_cells = mw.ustring.match(row, start_pattern)
       
        if c1 then
            -- Рядок гравця знайдено!
            local cell_data = {}
            table.insert(cell_data, mw.text.trim(c1)) -- C1
            table.insert(cell_data, "[[" .. player_name .. "]]") -- C2 (Фіксовано)


    -- Attempt to extract the "Рейтинг" section
            -- Розділяємо решту комірок ('rest_of_cells') за '||'
    local rating_section = mw.ustring.match(content, "==%s*Рейтинг%s*==.-{|%s*class%s*=%s*\"wikitable sortable\"(.-)|}")
            local remaining_cells = mw.text.split(rest_of_cells or "", '||')
    if not rating_section then
            for _, cell in ipairs(remaining_cells) do
        mw.log("Error: Rating section not found within the page content.")
                table.insert(cell_data, mw.text.trim(cell))
        mw.log("Page content: ", mw.ustring.sub(content, 1, 1000)) -- Log more content for better debugging
            end
         return "Rating section not found"
           
            -- Перевірка, чи існує потрібна колонка
            if column_index <= #cell_data and cell_data[column_index] then
                result = clean_wikilinks(cell_data[column_index])
                break -- Знайшли, виходимо
            end
         end
     end
     end


     mw.log("Rating section extracted, length: ", string.len(rating_section))
     return result
    mw.log("Rating section preview: ", mw.ustring.sub(rating_section, 1, 500))
end


    -- Adjusted to fetch the player's position (column 1 "№") instead of points
----------------------------------------------------------------------
    local pattern = "|%s*(%d+)%s*|%s*%[%[" .. mw.ustring.gsub(player, "([%(%)%.%-%+%[%]])", "%%%1") .. "%]%]"
-- ФУНКЦІЇ, ЩО ВИКЛИКАЮТЬСЯ З ШАБЛОНУ
    local direct_pattern = "|%s*(%d+)%s*|%s*" .. mw.ustring.gsub(player, "([%(%)%.%-%+%[%]])", "%%%1") .. "%s*"
----------------------------------------------------------------------
    local rank = mw.ustring.match(rating_section, pattern) or mw.ustring.match(rating_section, direct_pattern)


    if not rank then
function p.recruiter(frame)
        mw.log("Error: Player not found in season rankings or regex failed.")
    local name = frame.args.player
        mw.log("Pattern used: ", pattern)
    local raw = fetch_from_table("Гравці", name, 4) -- Колонка 4
        mw.log("Direct pattern used: ", direct_pattern)
   
        return "--"
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
     end
   
    if raw == "Відсутній" or raw == "-" then return "Не вказано" end
     return raw or "Не вказано"
end


     mw.log("Player rank found: ", rank)
function p.date_added(frame)
     return rank
    local name = frame.args.player
    local raw = fetch_from_table("Гравці", name, 3) -- Колонка 3
   
     if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
   
     return raw or "Невідомо"
end
end


return p
return p

Версія за 00:58, 24 листопада 2025

Документацію для цього модуля можна створити у Модуль:FetchData2/документація

local p = {}

--- Функція для виведення помилки на сторінку
local function error_output(context, error_details)
    local safe_details = error_details or "N/A" 
    return string.format("<span style='color:red; font-weight:bold;'>[FD2 Error: %s. Page: %s]</span>", context or "Unknown Context", safe_details)
end

--- Видаляє вікі-посилання [[link|text]] і [[link]]
local function clean_wikilinks(text)
    if not text then return nil end
    -- [[link|text]] -> text
    text = mw.ustring.gsub(text, "%[%[([^%]|]+)|([^%]]+)%]%]", "%2")
    -- [[link]] -> link
    text = mw.ustring.gsub(text, "%[%[([^%]]+)%]%]", "%1")
    return mw.text.trim(text)
end

----------------------------------------------------------------------
-- ГОЛОВНИЙ ПАРСЕР ДЛЯ ГОРИЗОНТАЛЬНИХ ТАБЛИЦЬ (Сторінка "Гравці")
----------------------------------------------------------------------

local function fetch_from_table(page_title, player_name, column_index)
    
    if not player_name or player_name == "" then
        return error_output("No Player Name", page_title) 
    end
    
    local title = mw.title.new(page_title)
    if not title or not title.exists then 
        return error_output("Page Missing", page_title)
    end

    local content = title:getContent()
    if not content then return error_output("Content Read Fail", page_title) end

    -- Шукаємо вміст першої таблиці на сторінці
    local table_content = mw.ustring.match(content, "{|.-([|].-.-[|]})")
    if not table_content then 
        return error_output("Table Missing", page_title)
    end

    local escaped = mw.ustring.gsub(player_name, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
    -- Патерн для пошуку гравця у вікі-посиланні ([[Гравець]])
    local player_pattern = "%[%[" .. escaped .. "%]%]" 
    local result = nil
    
    -- Патерн, який надійно захоплює C1 та РЕШТУ РЯДКА, починаючи з C3, базуючись на C2 (Гравець)
    local pattern_parts = {
        "^%s*|%s*",             -- Початок рядка, роздільник C1
        "(.-)",                 -- 1. Захоплюємо вміст C1 
        "%s*[|][|]%s*",         -- Роздільник C1-C2
        player_pattern,         -- 2. Ім'я гравця (у C2)
        "%s*[|][|]%s*",         -- Роздільник C2-C3
        "(.+)$",                -- 3. Захоплюємо РЕШТУ РЯДКА (від C3 до кінця)
    }
    local start_pattern = table.concat(pattern_parts)

    -- Ітерація по всіх рядках
    for row in mw.ustring.gmatch(table_content, "\n%s*|-[^%s]*\n(.-)") do
        
        -- Спробуємо зіставити рядок із шаблоном
        local c1, rest_of_cells = mw.ustring.match(row, start_pattern)
        
        if c1 then
            -- Рядок гравця знайдено!
            local cell_data = {}
            table.insert(cell_data, mw.text.trim(c1)) -- C1
            table.insert(cell_data, "[[" .. player_name .. "]]") -- C2 (Фіксовано)

            -- Розділяємо решту комірок ('rest_of_cells') за '||'
            local remaining_cells = mw.text.split(rest_of_cells or "", '||')
            for _, cell in ipairs(remaining_cells) do
                 table.insert(cell_data, mw.text.trim(cell))
            end
            
            -- Перевірка, чи існує потрібна колонка
            if column_index <= #cell_data and cell_data[column_index] then
                result = clean_wikilinks(cell_data[column_index])
                break -- Знайшли, виходимо
            end
        end
    end

    return result
end

----------------------------------------------------------------------
-- ФУНКЦІЇ, ЩО ВИКЛИКАЮТЬСЯ З ШАБЛОНУ
----------------------------------------------------------------------

function p.recruiter(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Гравці", name, 4) -- Колонка 4
    
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
    
    if raw == "Відсутній" or raw == "-" then return "Не вказано" end
    return raw or "Не вказано"
end

function p.date_added(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Гравці", name, 3) -- Колонка 3
    
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
    
    return raw or "Невідомо"
end

return p