« 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
Ligne 20 : Ligne 20 :
     local url = 'https://api.zotero.org/groups/4893620/items/' .. itemKey .. '?include=data&format=json'
     local url = 'https://api.zotero.org/groups/4893620/items/' .. itemKey .. '?include=data&format=json'
      
      
     -- Utiliser mw.uri.fetchContent au lieu de externalData
     -- Afficher l'URL pour déboguer
     local success, response = pcall(function()
    mw.log('Fetching URL: ' .. url)
         return mw.uri.fetchContent(url)
   
    -- Récupérer les données avec getExternalData
     local success, result
    success, result = pcall(function()
         return mw.ext.externalData.getWebData{url = url}
     end)
     end)
      
      
     if not success or not response then
     if not success then
        mw.log('Error fetching data: ' .. tostring(result))
         return nil
         return nil
     end
     end
      
      
     -- Décoder la réponse JSON
     if not result or type(result) ~= "table" then
    local success, data = pcall(mw.text.jsonDecode, response)
        mw.log('No data or unexpected type: ' .. type(result))
    if not success or not data then
         return nil
         return nil
     end
     end
      
      
     -- Extraire les données de la réponse
     -- Pour le débogage
     if data.data then
    mw.log('Response type: ' .. type(result))
         cachedData = data.data
   
    -- ExternalData peut retourner les données dans un format de table spécifique
    -- Tentons de trouver la donnée JSON dans cette table
    local jsonData
   
    -- Parcourir les résultats pour trouver le contenu JSON
    for k, v in pairs(result) do
        if type(v) == "string" and v:match("^%s*[{[]") then
            -- Cela semble être du JSON
            jsonData = v
            break
        end
     end
   
    if not jsonData then
        -- Si nous ne trouvons pas de JSON, essayons la première valeur
        if result[1] and type(result[1]) == "table" and result[1][1] then
            jsonData = result[1][1]
        end
    end
   
    if not jsonData then
        mw.log('No JSON data found in response')
        return nil
    end
   
    -- Décoder le JSON
    local decoded
    success, decoded = pcall(mw.text.jsonDecode, jsonData)
   
    if not success or not decoded then
        mw.log('Failed to decode JSON: ' .. tostring(decoded))
        return nil
    end
   
    -- Traiter les données décodées
    if decoded.data then
         cachedData = decoded.data
     else
     else
         cachedData = data
         cachedData = decoded
     end
     end
      
      
Ligne 45 : Ligne 86 :
end
end


-- Fonction pour déboguer la réponse brute
-- Fonction de débogage de base
function p.debugRawResponse(frame)
function p.debugBasic(frame)
     local itemKey = frame and frame.args[1]
     local itemKey = frame and frame.args[1]
      
      
Ligne 55 : Ligne 96 :
     local url = 'https://api.zotero.org/groups/4893620/items/' .. itemKey .. '?include=data&format=json'
     local url = 'https://api.zotero.org/groups/4893620/items/' .. itemKey .. '?include=data&format=json'
      
      
     -- Utiliser mw.uri.fetchContent
     -- Tester différentes méthodes
     local success, response = pcall(function()
    local outputs = {}
         return mw.uri.fetchContent(url)
   
    -- Méthode 1: getExternalData
     local success, result = pcall(function()
         return mw.ext.externalData.getExternalData{url = url, format = 'json'}
     end)
     end)
      
      
     if not success then
    table.insert(outputs, "Méthode 1 (getExternalData):")
         return "Erreur lors de la requête: " .. tostring(response)
     if success then
         table.insert(outputs, "  Type: " .. type(result))
        if type(result) == "table" then
            table.insert(outputs, "  Clés: " .. table.concat(mw.getKeysSortedByValue(result), ", "))
        else
            table.insert(outputs, "  Valeur: " .. tostring(result))
        end
    else
        table.insert(outputs, " Erreur: " .. tostring(result))
     end
     end
      
      
     if not response then
     -- Méthode 2: getWebData
         return "Aucune réponse reçue"
    success, result = pcall(function()
     end
         return mw.ext.externalData.getWebData{url = url}
     end)
      
      
     -- Limiter la taille de la réponse pour éviter de surcharger la page
     table.insert(outputs, "\nMéthode 2 (getWebData):")
     if #response > 1000 then
     if success then
         response = response:sub(1, 1000) .. "... (tronqué)"
         table.insert(outputs, "  Type: " .. type(result))
        if type(result) == "table" then
            table.insert(outputs, "  Clés: " .. table.concat(mw.getKeysSortedByValue(result), ", "))
        else
            table.insert(outputs, "  Valeur: " .. tostring(result))
        end
    else
        table.insert(outputs, "  Erreur: " .. tostring(result))
     end
     end
      
      
     return "Type: " .. type(response) .. "\n\nContenu: " .. response
     return table.concat(outputs, "\n")
end
end



Version du 12 juin 2025 à 16:16

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 spécifique
    local url = 'https://api.zotero.org/groups/4893620/items/' .. itemKey .. '?include=data&format=json'
    
    -- Afficher l'URL pour déboguer
    mw.log('Fetching URL: ' .. url)
    
    -- Récupérer les données avec getExternalData
    local success, result
    success, result = pcall(function()
        return mw.ext.externalData.getWebData{url = url}
    end)
    
    if not success then
        mw.log('Error fetching data: ' .. tostring(result))
        return nil
    end
    
    if not result or type(result) ~= "table" then
        mw.log('No data or unexpected type: ' .. type(result))
        return nil
    end
    
    -- Pour le débogage
    mw.log('Response type: ' .. type(result))
    
    -- ExternalData peut retourner les données dans un format de table spécifique
    -- Tentons de trouver la donnée JSON dans cette table
    local jsonData
    
    -- Parcourir les résultats pour trouver le contenu JSON
    for k, v in pairs(result) do
        if type(v) == "string" and v:match("^%s*[{[]") then
            -- Cela semble être du JSON
            jsonData = v
            break
        end
    end
    
    if not jsonData then
        -- Si nous ne trouvons pas de JSON, essayons la première valeur
        if result[1] and type(result[1]) == "table" and result[1][1] then
            jsonData = result[1][1]
        end
    end
    
    if not jsonData then
        mw.log('No JSON data found in response')
        return nil
    end
    
    -- Décoder le JSON
    local decoded
    success, decoded = pcall(mw.text.jsonDecode, jsonData)
    
    if not success or not decoded then
        mw.log('Failed to decode JSON: ' .. tostring(decoded))
        return nil
    end
    
    -- Traiter les données décodées
    if decoded.data then
        cachedData = decoded.data
    else
        cachedData = decoded
    end
    
    return cachedData
end

-- Fonction de débogage de base
function p.debugBasic(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 .. '?include=data&format=json'
    
    -- Tester différentes méthodes
    local outputs = {}
    
    -- Méthode 1: getExternalData
    local success, result = pcall(function()
        return mw.ext.externalData.getExternalData{url = url, format = 'json'}
    end)
    
    table.insert(outputs, "Méthode 1 (getExternalData):")
    if success then
        table.insert(outputs, "  Type: " .. type(result))
        if type(result) == "table" then
            table.insert(outputs, "  Clés: " .. table.concat(mw.getKeysSortedByValue(result), ", "))
        else
            table.insert(outputs, "  Valeur: " .. tostring(result))
        end
    else
        table.insert(outputs, "  Erreur: " .. tostring(result))
    end
    
    -- Méthode 2: getWebData
    success, result = pcall(function()
        return mw.ext.externalData.getWebData{url = url}
    end)
    
    table.insert(outputs, "\nMéthode 2 (getWebData):")
    if success then
        table.insert(outputs, "  Type: " .. type(result))
        if type(result) == "table" then
            table.insert(outputs, "  Clés: " .. table.concat(mw.getKeysSortedByValue(result), ", "))
        else
            table.insert(outputs, "  Valeur: " .. tostring(result))
        end
    else
        table.insert(outputs, "  Erreur: " .. tostring(result))
    end
    
    return table.concat(outputs, "\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

function p.debugRawJson(frame)
    local d = p._fetchZoteroData(frame)
    if not d then
        return "Aucune donnée reçue"
    end
    local function indentJson(json)
        local indent = 0
        local formatted = {}
        local inString = false
        for i = 1, #json do
            local c = json:sub(i, i)
            if c == '"' and json:sub(i - 1, i - 1) ~= '\\' then
                inString = not inString
            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)
    end
    local raw = mw.text.jsonEncode(d)
    local pretty = indentJson(raw)
    return '<pre>' .. pretty .. '</pre>'
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 .. '?include=data&format=json'
end

return p