Немає опису редагування
Немає опису редагування
Мітка: Ручний відкіт
 
(Не показано 38 проміжних версій цього користувача)
Рядок 1: Рядок 1:
local p = {}
local p = {}


-- [[25.10.2024]] для розрахунку днів
-- ================================================
local TARGET_TIMESTAMP = os.time({year=2024, month=10, day=25, hour=0, min=0, sec=0})
-- КЕШУВАННЯ
-- ================================================


--- Функція для виведення помилки на сторінку
local page_cache = {}
local function error_output(context, error_details)
    -- !!! УВАГА: ЦЕ ВІДОБРАЖАЄТЬСЯ НА СТОРІНЦІ !!!
    return string.format("<span style='color:red; font-weight:bold;'>[FD2 Error: %s. Player: %s]</span>", context, error_details)
end
 
 
----------------------------------------------------------------------
-- ГОЛОВНИЙ ПОШУК (Використовується для Гравці, Призовий фонд, Фундація, Фіналіст)
-- Індексація: 1=№, 2=Ім'я, 3=Значення, 4=Додатково
----------------------------------------------------------------------
 
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", "N/A")
    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 escaped = mw.ustring.gsub(player_name, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
    local player_pattern = "%[%[" .. escaped .. "%]%]"
 
    -- 1. Вилучаємо вміст таблиці wikitable
    local table_content = mw.ustring.match(content, "{|.-([|].-.-[|]})")
    if not table_content then
        return error_output("Table Missing", page_title)
    end
 
    -- 2. Знаходимо весь блок даних гравця (4 комірки: №, Ім'я, Значення, Додатково)
    local full_row_pattern = "([|]%s*.-%s*[|]%s*" .. player_pattern .. "%s*[|]%s*.-%s*[|]%s*.-%s*)"
    local full_row_match = mw.ustring.match(table_content, full_row_pattern)
   
    if not full_row_match then
        -- Повертаємо nil, щоб функції-обгортки (recruiter, date_added) могли встановити значення за замовчуванням
        return nil
    end


    -- 3. Розділяємо захоплений блок на комірки
local function get_page_content(page_name)
    local cells = {}
     if page_cache[page_name] then
      
         return page_cache[page_name]
    for cell in mw.ustring.gmatch(full_row_match, "[|](.-)") do
        local trimmed_cell = mw.text.trim(cell)
        if trimmed_cell ~= "" then
            table.insert(cells, trimmed_cell)
         end
     end
     end
      
      
     local result = cells[column_index]
     local title = mw.title.new(page_name)
     if not result then  
     if not title or not title.exists then
         -- Якщо рядок знайдено, але колонка відсутня (наприклад, 4-та), повертаємо nil.
         page_cache[page_name] = nil
         return nil
         return nil
     end
     end
    -- 4. Прибираємо вікі-посилання [[link|text]] і [[link]]
    result = mw.ustring.gsub(result, "%[%[([^%]|]+)|([^%]]+)%]%]", "%2")
    result = mw.ustring.gsub(result, "%[%[([^%]]+)%]%]", "%1")
    return mw.text.trim(result)
end
----------------------------------------------------------------------
-- Рахує різницю в днях між датою та 25.10.2024
----------------------------------------------------------------------
local function date_with_days(dateString)
    if not dateString or mw.ustring.find(dateString, "Error") then return "Невідомо" end
    local d, m, y = dateString:match("(%d%d)%.(%d%d)%.(%d%d%d%d)")
    if not d then return dateString end
    local start = os.time({day = tonumber(d), month = tonumber(m), year = tonumber(y), hour = 0, min = 0, sec = 0})
    local finish = TARGET_TIMESTAMP
      
      
     local diff = math.floor((finish - start) / 86400)
     local content = title:getContent()
    if diff < 0 then diff = 0 end
     page_cache[page_name] = content
 
     return content
    return string.format("%s (%d д)", dateString, diff)
end
 
 
----------------------------------------------------------------------
-- ФУНКЦІЇ ДЛЯ {{MCC Player New}}
----------------------------------------------------------------------
 
-- 1. Провідник (Колонка 4)
function p.recruiter(frame)
     local name = frame.args.player
    local raw = fetch_from_table("Гравці", name, 4)
 
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
   
    if raw == "Відсутній" then return "Не вказано" end
    return raw or "Не вказано"
end
 
-- 2. Дата приєднання (Колонка 3)
function p.date_added(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Гравці", name, 3)
   
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
 
    return raw and date_with_days(raw) or "Невідомо"
end
 
-- 3. Призовий фонд (Колонка 3)
function p.prize_pool(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Призовий_фонд", name, 3)
 
    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
 
    if raw then
        raw = mw.ustring.gsub(raw, "[^%d%s]", "")
        raw = mw.text.trim(raw)
    end
     return (raw or "0") .. " ₴"
end
end


-- 4. Фундація (Колонка 3)
-- ================================================
function p.foundation(frame)
-- АВТОМАТИЧНЕ МЕНЮ СЕКЦІЙ
    local name = frame.args.player
-- ================================================
    local raw = fetch_from_table("Фундація", name, 3)


    if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
function p.section_menu(frame)
    local page_name = frame.args.page or mw.title.getCurrentTitle().text
    local content = get_page_content(page_name)
      
      
     if raw then  
     if not content then
         raw = mw.ustring.gsub(raw, "[^%d%s]", "")
         return ""
        raw = mw.text.trim(raw)
     end
     end
    return (raw or "0") .. " ₴"
end
-- 5. Фіналіст (Колонка 3)
function p.final(frame)
    local name = frame.args.player
    local raw = fetch_from_table("Фіналіст", name, 3)
      
      
     if type(raw) == "string" and mw.ustring.find(raw, "Error") then return raw end
     local sections = {}
      
      
     local count = raw and mw.ustring.match(raw, "(%d+)")
     for line in mw.ustring.gmatch(content, "[^\n]+") do
        -- ТІЛЬКИ заголовки рівня 2: == Назва ==
        if mw.ustring.match(line, "^==[^=]") and mw.ustring.match(line, "[^=]==$") then
            local section_name = mw.ustring.match(line, "^==%s*(.-)%s*==$")
           
            if section_name and section_name ~= "" then
                -- Виконуємо шаблони щоб отримати реальний текст
                local processed = frame:preprocess(section_name)
                processed = mw.text.trim(processed)
               
                -- Anchor
                local anchor = mw.ustring.gsub(processed, " ", "_")
               
                if processed ~= "" then
                    table.insert(sections, {
                        display = processed,
                        anchor = anchor
                    })
                end
            end
        end
    end
      
      
     if count then
     if #sections == 0 then
        return count .. "/9"
         return ""
    else
         return "0/9"
     end
     end
end
-- 6. Результат сезону (Додано функціонал season_result)
function p.season_result(frame)
    local season = frame.args.season
    local player = frame.args.player
    if not player or player == "" then return error_output("No Player Name", "Season") end
      
      
     local season_titles = {
    -- Будуємо HTML
        "Перший_сезон", "Другий_сезон", "Третій_сезон",
     local html_parts = {}
        "Четвертий_сезон", "П'ятий_сезон", "Шостий_сезон",
        "Сьомий_сезон", "Восьмий_сезон", "Дев'ятий_сезон"
    }
      
      
     local season_title = season_titles[tonumber(season)]
     table.insert(html_parts, '<div class="l-box" style="position:fixed; top:20px; left:20px; z-index:100; border-radius:16px; background-color:#23232c; width:220px; box-sizing:border-box; overflow:hidden;">')
 
    if not season_title then return error_output("Invalid Season Index", season) end
      
      
     local title = mw.title.new(season_title)
     table.insert(html_parts, '<div style="padding:15px 20px; font-weight:bold; font-size:15px; color:#fff; border-bottom:1px solid rgba(255,255,255,0.1);">Зміст</div>')
    if not title or not title.exists then return error_output("Season Page Missing", season_title) end
      
      
     local content = title:getContent()
     for i, section in ipairs(sections) do
    if not content then return error_output("Season Content Read Fail", season_title) end
        local border = ""
 
        if i < #sections then
    -- Шукаємо секцію "Рейтинг" та таблицю
            border = "border-bottom:1px solid rgba(255,255,255,0.05);"
    local rating_section = mw.ustring.match(content, "==%s*Рейтинг%s*==.-{|%s*class%s*=%s*\"wikitable sortable\"(.-)|}")
        end
    if not rating_section then
       
        return error_output("Rating Section Missing", season_title)  
        table.insert(html_parts, string.format(
            '<div class="l-box-item" style="padding:12px 20px; %s">[[#%s|%s]]</div>',
            border, section.anchor, section.display
        ))
     end
     end
    -- Патерн для пошуку позиції (перша колонка) гравця (друга колонка)
    -- | <№> | [[Гравець]]
    local escaped_player = mw.ustring.gsub(player, "([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1")
    local pattern = "[|]%s*(%d+)%s*[|]%s*%[%[" .. escaped_player .. "%]%]"
      
      
     local rank = mw.ustring.match(rating_section, pattern)
     table.insert(html_parts, '</div>')
      
      
     if not rank then
     return table.concat(html_parts, '\n')
        return "--"
    end
 
    return rank
end
end


return p
return p

Поточна версія на 10:24, 8 грудня 2025

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

local p = {}

-- ================================================
-- КЕШУВАННЯ
-- ================================================

local page_cache = {}

local function get_page_content(page_name)
    if page_cache[page_name] then
        return page_cache[page_name]
    end
    
    local title = mw.title.new(page_name)
    if not title or not title.exists then
        page_cache[page_name] = nil
        return nil
    end
    
    local content = title:getContent()
    page_cache[page_name] = content
    return content
end

-- ================================================
-- АВТОМАТИЧНЕ МЕНЮ СЕКЦІЙ
-- ================================================

function p.section_menu(frame)
    local page_name = frame.args.page or mw.title.getCurrentTitle().text
    local content = get_page_content(page_name)
    
    if not content then
        return ""
    end
    
    local sections = {}
    
    for line in mw.ustring.gmatch(content, "[^\n]+") do
        -- ТІЛЬКИ заголовки рівня 2: == Назва ==
        if mw.ustring.match(line, "^==[^=]") and mw.ustring.match(line, "[^=]==$") then
            local section_name = mw.ustring.match(line, "^==%s*(.-)%s*==$")
            
            if section_name and section_name ~= "" then
                -- Виконуємо шаблони щоб отримати реальний текст
                local processed = frame:preprocess(section_name)
                processed = mw.text.trim(processed)
                
                -- Anchor
                local anchor = mw.ustring.gsub(processed, " ", "_")
                
                if processed ~= "" then
                    table.insert(sections, {
                        display = processed,
                        anchor = anchor
                    })
                end
            end
        end
    end
    
    if #sections == 0 then
        return ""
    end
    
    -- Будуємо HTML
    local html_parts = {}
    
    table.insert(html_parts, '<div class="l-box" style="position:fixed; top:20px; left:20px; z-index:100; border-radius:16px; background-color:#23232c; width:220px; box-sizing:border-box; overflow:hidden;">')
    
    table.insert(html_parts, '<div style="padding:15px 20px; font-weight:bold; font-size:15px; color:#fff; border-bottom:1px solid rgba(255,255,255,0.1);">Зміст</div>')
    
    for i, section in ipairs(sections) do
        local border = ""
        if i < #sections then
            border = "border-bottom:1px solid rgba(255,255,255,0.05);"
        end
        
        table.insert(html_parts, string.format(
            '<div class="l-box-item" style="padding:12px 20px; %s">[[#%s|%s]]</div>',
            border, section.anchor, section.display
        ))
    end
    
    table.insert(html_parts, '</div>')
    
    return table.concat(html_parts, '\n')
end

return p