« Module:ZoteroAPI » : différence entre les versions

De alcolois
Aller à la navigation Aller à la recherche
Aucun résumé des modifications
Aucun résumé des modifications
 
(12 versions intermédiaires par le même utilisateur non affichées)
Ligne 1 : Ligne 1 :
local p = {}
local p = {}
local cachedData = nil  -- 🔒 Cache unique pour la durée d'exécution de la page


-- Fonction utilitaire pour récupérer et décoder les données Zotero
-- Fonction de récupération de données Zotero par itemKey
function p._fetchZoteroData(itemKey)
function p._fetchZoteroData(frame)
if not itemKey or itemKey == '' then
    -- Utiliser le cache si disponible
return nil
    if cachedData then
end
        return cachedData
    end
   
    -- Obtenir l'itemKey depuis le paramètre
    local itemKey = frame and frame.args[1]
   
    -- Si aucun itemKey n'est fourni, retourner nil
    if not itemKey or itemKey == "" then
        return nil
    end
   
    -- Construire l'URL avec l'itemKey directement dans le chemin
    local url = 'https://api.zotero.org/groups/4893620/items/' .. itemKey
   
    -- Récupérer les données avec getExternalData en utilisant JSONPath
    local success, result = pcall(function()
        return mw.ext.externalData.getExternalData({
            url = url,
            format = 'json',
            use_jsonpath = true,
            data = {
                key = '$.key',
                caseName = '$.data.caseName',
                dateDecided = '$.data.dateDecided',
                court = '$.data.court',
                url = '$.data.url',
                history = '$.data.history',
                docketNumber = '$.data.docketNumber',
                firstName = '$.data.creators[0].firstName',
                lastName = '$.data.creators[0].lastName'
            }
        })
    end)
   
    if not success or not result then
        return nil
    end
   
    -- Créer un objet avec les données extraites
    local data = {}
   
    -- ExternalData retourne un tableau de valeurs pour chaque champ
    -- Nous prenons le premier élément de chaque tableau
    for field, values in pairs(result) do
        if type(values) == "table" and values[1] then
            data[field] = values[1]
        end
    end
   
    cachedData = data
    return cachedData
end


local url = 'https://api.zotero.org/groups/4893620/items/' .. itemKey .. '?include=data&format=json'
-- Fonction de débogage simple
function p.debugSimple(frame)
    local itemKey = frame and frame.args[1]
   
    if not itemKey or itemKey == "" then
        return "Aucun itemKey fourni"
    end
   
    local url = 'https://api.zotero.org/groups/4893620/items/' .. itemKey
   
    -- Essayons une approche simplifiée
    local output = {"Test de récupération des données:"}
   
    -- Test 1: Récupérer juste le titre sans JSONPath
    local success, result1 = pcall(function()
        return mw.ext.externalData.getExternalData({
            url = url,
            format = 'json'
        })
    end)
   
    table.insert(output, "\n1. Test sans JSONPath:")
    if not success then
        table.insert(output, "  Erreur: " .. tostring(result1))
    elseif not result1 then
        table.insert(output, "  Aucun résultat")
    else
        table.insert(output, "  Type de résultat: " .. type(result1))
        -- Afficher quelques détails si c'est une table
        if type(result1) == "table" then
            for k, v in pairs(result1) do
                if type(v) ~= "table" then
                    table.insert(output, "  " .. k .. ": " .. tostring(v))
                else
                    table.insert(output, "  " .. k .. ": [table]")
                end
            end
        else
            table.insert(output, "  Valeur: " .. tostring(result1))
        end
    end
   
    -- Test 2: Récupérer juste le titre avec JSONPath simple
    local success, result2 = pcall(function()
        return mw.ext.externalData.getExternalData({
            url = url,
            format = 'json',
            use_jsonpath = true,
            data = {
                title = '$.data.caseName'
            }
        })
    end)
   
    table.insert(output, "\n2. Test avec JSONPath simple:")
    if not success then
        table.insert(output, "  Erreur: " .. tostring(result2))
    elseif not result2 then
        table.insert(output, "  Aucun résultat")
    else
        table.insert(output, "  Type de résultat: " .. type(result2))
        -- Afficher quelques détails si c'est une table
        if type(result2) == "table" then
            for k, v in pairs(result2) do
                if type(v) ~= "table" then
                    table.insert(output, "  " .. k .. ": " .. tostring(v))
                else
                    table.insert(output, "  " .. k .. ": [table]")
                    if k == "title" and type(v) == "table" then
                        for i, val in ipairs(v) do
                            table.insert(output, "    " .. i .. ": " .. tostring(val))
                        end
                    end
                end
            end
        else
            table.insert(output, "  Valeur: " .. tostring(result2))
        end
    end
   
    -- Test 3: Essayer avec #get_web_data via preprocess
    local webDataCall = '{{#get_web_data:url=' .. url .. '|format=json|use jsonpath=true|data=title=$.data.caseName}}'
    local result3 = frame:preprocess(webDataCall)
   
    table.insert(output, "\n3. Test avec #get_web_data:")
    table.insert(output, "  Résultat: " .. result3)
   
    return table.concat(output, "\n")
end


local data = mw.ext.externalData.getExternalData({
-- Fonctions de débogage
url = url,
function p.debugResult(frame)
format = 'json'
    local d = p._fetchZoteroData(frame)
})
    if not d then return "Aucune donnée reçue" end
    local out = {}
    table.insert(out, "✔ Clé : " .. (d.key or ''))
    table.insert(out, "✔ Titre : " .. (d.caseName or ''))
    table.insert(out, "✔ Tribunal : " .. (d.court or ''))
    table.insert(out, "✔ Date : " .. (d.dateDecided or ''))
    table.insert(out, "✔ URL : " .. (d.url or ''))
    table.insert(out, "✔ Auteur : " .. (d.firstName or '') .. " " .. (d.lastName or ''))
    return table.concat(out, "\n")
end


local decoded
-- Fonctions accessibles
if type(data) == "string" then
function p.caseName(frame)
local ok, result = pcall(mw.text.jsonDecode, data)
    local d = p._fetchZoteroData(frame)
if not ok or type(result) ~= "table" then
    return d and d.caseName or ''
return nil
end
end
decoded = result
elseif type(data) == "table" then
decoded = data
else
return nil
end


if decoded.__json and type(decoded.__json) == "table" then
function p.dateDecided(frame)
return decoded.__json
    local d = p._fetchZoteroData(frame)
end
    return d and d.dateDecided or ''
end


return decoded
function p.docketNumber(frame)
    local d = p._fetchZoteroData(frame)
    return d and d.docketNumber or ''
end
end


-- Fonction pour afficher le JSON formaté
function p.history(frame)
function p.debugRawJson(frame)
    local d = p._fetchZoteroData(frame)
local itemKey = frame.args[1]
    return d and d.history or ''
if not itemKey or itemKey == '' then
end
return "❌ Aucun itemKey fourni."
end


local d = p._fetchZoteroData(itemKey)
function p.url(frame)
if not d then
    local d = p._fetchZoteroData(frame)
return "❌ Aucune donnée reçue ou erreur de décodage."
    return d and d.url or ''
end
end


-- Fonction d’indentation
function p.court(frame)
local function indentJson(json)
    local d = p._fetchZoteroData(frame)
local indent = 0
    return d and d.court or ''
local formatted = {}
end
local inString = false


for i = 1, #json do
function p.auteurPrenom(frame)
local c = json:sub(i, i)
    local d = p._fetchZoteroData(frame)
if c == '"' and json:sub(i - 1, i - 1) ~= '\\' then
    return d and d.firstName or ''
inString = not inString
end
end
if not inString then
if c == '{' or c == '[' then
table.insert(formatted, c .. '\n' .. string.rep('  ', indent + 1))
indent = indent + 1
elseif c == '}' or c == ']' then
indent = indent - 1
table.insert(formatted, '\n' .. string.rep('  ', indent) .. c)
elseif c == ',' then
table.insert(formatted, ',\n' .. string.rep(' ', indent))
else
table.insert(formatted, c)
end
else
table.insert(formatted, c)
end
end


return table.concat(formatted)
function p.auteurNom(frame)
end
    local d = p._fetchZoteroData(frame)
    return d and d.lastName or ''
end


local raw = mw.text.jsonEncode(d)
-- Affichage de l'URL utilisée (pour vérification)
return '<pre>' .. indentJson(raw) .. '</pre>'
function p.debugUrl(frame)
    local itemKey = frame and frame.args[1] or ""
    return 'https://api.zotero.org/groups/4893620/items/' .. itemKey
end
end


return p
return p

Dernière version du 12 juin 2025 à 16:40

La documentation pour ce module peut être créée à Module:ZoteroAPI/doc

local p = {}
local cachedData = nil  -- 🔒 Cache unique pour la durée d'exécution de la page

-- Fonction de récupération de données Zotero par itemKey
function p._fetchZoteroData(frame)
    -- Utiliser le cache si disponible
    if cachedData then
        return cachedData
    end
    
    -- Obtenir l'itemKey depuis le paramètre
    local itemKey = frame and frame.args[1]
    
    -- Si aucun itemKey n'est fourni, retourner nil
    if not itemKey or itemKey == "" then
        return nil
    end
    
    -- Construire l'URL avec l'itemKey directement dans le chemin
    local url = 'https://api.zotero.org/groups/4893620/items/' .. itemKey
    
    -- Récupérer les données avec getExternalData en utilisant JSONPath
    local success, result = pcall(function()
        return mw.ext.externalData.getExternalData({
            url = url,
            format = 'json',
            use_jsonpath = true,
            data = {
                key = '$.key',
                caseName = '$.data.caseName',
                dateDecided = '$.data.dateDecided',
                court = '$.data.court',
                url = '$.data.url',
                history = '$.data.history',
                docketNumber = '$.data.docketNumber',
                firstName = '$.data.creators[0].firstName',
                lastName = '$.data.creators[0].lastName'
            }
        })
    end)
    
    if not success or not result then
        return nil
    end
    
    -- Créer un objet avec les données extraites
    local data = {}
    
    -- ExternalData retourne un tableau de valeurs pour chaque champ
    -- Nous prenons le premier élément de chaque tableau
    for field, values in pairs(result) do
        if type(values) == "table" and values[1] then
            data[field] = values[1]
        end
    end
    
    cachedData = data
    return cachedData
end

-- Fonction de débogage simple
function p.debugSimple(frame)
    local itemKey = frame and frame.args[1]
    
    if not itemKey or itemKey == "" then
        return "Aucun itemKey fourni"
    end
    
    local url = 'https://api.zotero.org/groups/4893620/items/' .. itemKey
    
    -- Essayons une approche simplifiée
    local output = {"Test de récupération des données:"}
    
    -- Test 1: Récupérer juste le titre sans JSONPath
    local success, result1 = pcall(function()
        return mw.ext.externalData.getExternalData({
            url = url,
            format = 'json'
        })
    end)
    
    table.insert(output, "\n1. Test sans JSONPath:")
    if not success then
        table.insert(output, "  Erreur: " .. tostring(result1))
    elseif not result1 then
        table.insert(output, "  Aucun résultat")
    else
        table.insert(output, "  Type de résultat: " .. type(result1))
        -- Afficher quelques détails si c'est une table
        if type(result1) == "table" then
            for k, v in pairs(result1) do
                if type(v) ~= "table" then
                    table.insert(output, "  " .. k .. ": " .. tostring(v))
                else
                    table.insert(output, "  " .. k .. ": [table]")
                end
            end
        else
            table.insert(output, "  Valeur: " .. tostring(result1))
        end
    end
    
    -- Test 2: Récupérer juste le titre avec JSONPath simple
    local success, result2 = pcall(function()
        return mw.ext.externalData.getExternalData({
            url = url,
            format = 'json',
            use_jsonpath = true,
            data = {
                title = '$.data.caseName'
            }
        })
    end)
    
    table.insert(output, "\n2. Test avec JSONPath simple:")
    if not success then
        table.insert(output, "  Erreur: " .. tostring(result2))
    elseif not result2 then
        table.insert(output, "  Aucun résultat")
    else
        table.insert(output, "  Type de résultat: " .. type(result2))
        -- Afficher quelques détails si c'est une table
        if type(result2) == "table" then
            for k, v in pairs(result2) do
                if type(v) ~= "table" then
                    table.insert(output, "  " .. k .. ": " .. tostring(v))
                else
                    table.insert(output, "  " .. k .. ": [table]")
                    if k == "title" and type(v) == "table" then
                        for i, val in ipairs(v) do
                            table.insert(output, "    " .. i .. ": " .. tostring(val))
                        end
                    end
                end
            end
        else
            table.insert(output, "  Valeur: " .. tostring(result2))
        end
    end
    
    -- Test 3: Essayer avec #get_web_data via preprocess
    local webDataCall = '{{#get_web_data:url=' .. url .. '|format=json|use jsonpath=true|data=title=$.data.caseName}}'
    local result3 = frame:preprocess(webDataCall)
    
    table.insert(output, "\n3. Test avec #get_web_data:")
    table.insert(output, "  Résultat: " .. result3)
    
    return table.concat(output, "\n")
end

-- Fonctions de débogage
function p.debugResult(frame)
    local d = p._fetchZoteroData(frame)
    if not d then return "Aucune donnée reçue" end
    local out = {}
    table.insert(out, "✔ Clé : " .. (d.key or ''))
    table.insert(out, "✔ Titre : " .. (d.caseName or ''))
    table.insert(out, "✔ Tribunal : " .. (d.court or ''))
    table.insert(out, "✔ Date : " .. (d.dateDecided or ''))
    table.insert(out, "✔ URL : " .. (d.url or ''))
    table.insert(out, "✔ Auteur : " .. (d.firstName or '') .. " " .. (d.lastName or ''))
    return table.concat(out, "\n")
end

-- Fonctions accessibles
function p.caseName(frame)
    local d = p._fetchZoteroData(frame)
    return d and d.caseName or ''
end

function p.dateDecided(frame)
    local d = p._fetchZoteroData(frame)
    return d and d.dateDecided or ''
end

function p.docketNumber(frame)
    local d = p._fetchZoteroData(frame)
    return d and d.docketNumber or ''
end

function p.history(frame)
    local d = p._fetchZoteroData(frame)
    return d and d.history or ''
end

function p.url(frame)
    local d = p._fetchZoteroData(frame)
    return d and d.url or ''
end

function p.court(frame)
    local d = p._fetchZoteroData(frame)
    return d and d.court or ''
end

function p.auteurPrenom(frame)
    local d = p._fetchZoteroData(frame)
    return d and d.firstName or ''
end

function p.auteurNom(frame)
    local d = p._fetchZoteroData(frame)
    return d and d.lastName or ''
end

-- Affichage de l'URL utilisée (pour vérification)
function p.debugUrl(frame)
    local itemKey = frame and frame.args[1] or ""
    return 'https://api.zotero.org/groups/4893620/items/' .. itemKey
end

return p