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


----------------------------------------------------------------------
-- ================================================
-- ГОЛОВНИЙ ПОШУК
-- КЕШУВАННЯ
-- Шукає у таблиці рядок, де друга колонка = player_name
-- ================================================
-- Повертає значення з column_index того ж самого рядка
----------------------------------------------------------------------


local function fetch_from_table(page_title, player_name, column_index)
local page_cache = {}
    local title = mw.title.new(page_title)
    if not title then return nil end


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()
     local content = title:getContent()
     if not content then return nil end
     page_cache[page_name] = content
 
     return content
     -- Escape для імен з дужками/крапками
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 nil end
-- ================================================


     -- 2. Знаходимо початок блоку, що містить ім'я гравця.  
function p.section_menu(frame)
    -- Ми шукаємо | <№>\n| [[Гравець]]
     local page_name = frame.args.page or mw.title.getCurrentTitle().text
    -- Перша колонка: [|]%s*.-%s*
     local content = get_page_content(page_name)
     -- Друга колонка (ім'я): [|]%s* + player_pattern
      
      
     -- Шаблон, що захоплює весь блок даних гравця (4 комірки)
     if not content then
    -- [|]%s*.-%s*[|]%s*[[Гравець]].- - Це шукає | <будь-що> | [[Гравець]] <будь-що>
        return ""
     -- Ми шукаємо шаблон, який починається з |- і містить 4 комірки.
     end
      
      
     local search_pattern =  
     local sections = {}
        "[|]%s*.-%s*[%-]%s*[|]%s*(" .. player_pattern .. ".-)" -- Знаходимо |- , потім першу комірку, потім [[гравець]]
      
      
     -- Ми знаємо, що ім'я гравця знаходиться у 2-й комірці.
     for line in mw.ustring.gmatch(content, "[^\n]+") do
    -- Отже, шаблон повинен захопити 1-шу, 2-гу, 3-тю та 4-ту комірки, що йдуть підряд
        -- ТІЛЬКИ заголовки рівня 2: == Назва ==
    -- [|]%s*.-%s* - Комірка 1 ()
        if mw.ustring.match(line, "^==[^=]") and mw.ustring.match(line, "[^=]==$") then
    -- [|]%s*" .. player_pattern .. "%s* - Комірка 2 (Ім'я гравця)
            local section_name = mw.ustring.match(line, "^==%s*(.-)%s*==$")
    -- [|]%s*.-%s* - Комірка 3 (Дата/Сума)
           
    -- [|]%s*.-%s* - Комірка 4 (Провідник)
            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
      
      
     local full_row_pattern = "([|]%s*.-%s*[|]%s*" .. player_pattern .. "%s*[|]%s*.-%s*[|]%s*.-%s*)"
     if #sections == 0 then
     local full_row_match = mw.ustring.match(table_content, full_row_pattern)
        return ""
     end
      
      
     if not full_row_match then return nil end
     -- Будуємо HTML
 
    local html_parts = {}
     -- 3. Розділяємо захоплений блок на комірки (яких має бути 4)
   
     local cells = {}
     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
     for cell in mw.ustring.gmatch(full_row_match, "[|](.-)") do
         local border = ""
         local trimmed_cell = mw.text.trim(cell)
         if i < #sections then
         if trimmed_cell ~= "" then
            border = "border-bottom:1px solid rgba(255,255,255,0.05);"
            table.insert(cells, trimmed_cell)
         end
         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
     end
    -- Перевірка індексування:
    -- cells[1] = №, cells[2] = [[Гравець]], cells[3] = Дата/Сума, cells[4] = Провідник/Рахунок
      
      
     local result = cells[column_index]
     table.insert(html_parts, '</div>')
    if not result then return nil end
 
    -- 4. Прибираємо [[link|text]] і [[link]]
    result = mw.ustring.gsub(result, "%[%[([^%]|]+)|([^%]]+)%]%]", "%2") -- [[link|text]] -> text
    result = mw.ustring.gsub(result, "%[%[([^%]]+)%]%]", "%1")          -- [[link]] -> link
 
    return mw.text.trim(result)
end
 
 
----------------------------------------------------------------------
-- Рахує різницю в днях між датою та 25.10.2024
----------------------------------------------------------------------
 
local function date_with_days(dateString)
    if not dateString then return "" end
 
    local d, m, y = dateString:match("(%d%d)%.(%d%d)%.(%d%d%d%d)")
    if not d then return dateString end
 
    -- Оскільки os.time працює з числами, перетворюємо
    d = tonumber(d)
    m = tonumber(m)
    y = tonumber(y)
 
    local start = os.time({day = d, month = m, year = y, hour = 0, min = 0, sec = 0})
    local finish = os.time({day = 25, month = 10, year = 2024, hour = 0, min = 0, sec = 0})
      
      
    local diff = math.floor((finish - start) / 86400)
     return table.concat(html_parts, '\n')
    if diff < 0 then diff = 0 end -- Якщо дата в майбутньому
 
     return string.format("%s (%d д)", dateString, diff)
end
 
 
----------------------------------------------------------------------
-- ПОЛЯ
-- Всі функції беруть PAGENAME та шукають його в 2-й колонці таблиці
----------------------------------------------------------------------
 
-- Для Гравців: № (1), Ім'я (2), Дата (3), Провідник (4)
function p.recruiter(frame)
    local name = mw.title.getCurrentTitle().text
    local raw = fetch_from_table("Гравці", name, 4)
    -- Додаткова логіка для рекрутера: якщо "Відсутній", то "Не вказано"
    if raw == "Відсутній" then return "Не вказано" end
    return raw or "Не вказано"
end
 
function p.date_added(frame)
    local name = mw.title.getCurrentTitle().text
    local raw = fetch_from_table("Гравці", name, 3)
    return raw and date_with_days(raw) or "Невідомо"
end
 
-- Для Фундація, Призовий_фонд, Фіналіст:
-- № (1), Ім'я (2), Сума/Рахунок (3), [Можливо, Дата, 4]
-- Припускаємо, що потрібне значення знаходиться у колонці 3
-- Оновлюємо індекс на 3
function p.foundation(frame)
    local name = mw.title.getCurrentTitle().text
    local raw = fetch_from_table("Фундація", name, 3)
    -- Додаємо ₴
    return (raw or "0") .. " ₴"
end
 
function p.prize_pool(frame)
    local name = mw.title.getCurrentTitle().text
    local raw = fetch_from_table("Призовий_фонд", name, 3)
    -- Додаємо ₴
    return (raw or "0") .. " ₴"
end
 
function p.final(frame)
    local name = mw.title.getCurrentTitle().text
    local raw = fetch_from_table("Фіналіст", name, 3)
    -- Припускаємо, що тут потрібне число, яке має бути доповнене "/9"
    if raw and raw ~= "" then
        return raw .. "/9"
    else
        return "0/9"
    end
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