MediaWiki:Inciskin/JS/Inciclopedia:Resumen de todos los tiempos.js

De Inciclopedia
Ir a la navegación Ir a la búsqueda

Nota: Después de publicar, quizás necesite actualizar la caché de su navegador para ver los cambios.

  • Firefox/Safari: Mantenga presionada la tecla Shift mientras pulsa el botón Actualizar, o presiona Ctrl+F5 o Ctrl+R (⌘+R en Mac)
  • Google Chrome: presione Ctrl+Shift+R (⌘+Shift+R en Mac)
  • Internet Explorer/Edge: mantenga presionada Ctrl mientras pulsa Actualizar, o presione Ctrl+F5
  • Opera: Presiona Ctrl+F5.
async function fetchContribs(user, contribs = [], cont = undefined, ucstart=undefined, ucend=undefined) {
    data = await $.getJSON({
        url: "https://inciclopedia.org/w/api.php?action=query&ucshow=!minor&list=usercontribs&uclimit=500&ucuser=" + encodeURIComponent(user) + "&ucdir=older" + (ucstart ? "&ucstart=" + encodeURIComponent(ucstart) : "") + (ucend ? "&ucend=" + encodeURIComponent(ucend) : "") + "&formatversion=2&format=json" + (cont ? "&uccontinue=" + encodeURIComponent(cont) : "")
    });
    if (data["query"] && data["query"]["usercontribs"]) {
        contribs.push(...data["query"]["usercontribs"]);
    }
    if (data["continue"] && data["continue"]["uccontinue"]) {
        return await fetchContribs(user, contribs, data["continue"]["uccontinue"], ucstart, ucend);
    }
    return contribs.filter((c) => !c["comment"].includes("trasladó") && !c["comment"].includes("redirigida"));
}

async function fetchFirstContrib(user) {
    data = await $.getJSON({
        url: "https://inciclopedia.org/w/api.php?action=query&ucshow=!minor&list=usercontribs&uclimit=1&ucuser=" + encodeURIComponent(user) + "&ucdir=newer&formatversion=2&format=json"
    });
    return data["query"] && data["query"]["usercontribs"] && data["query"]["usercontribs"].length > 0 ? data["query"]["usercontribs"][0]["timestamp"] : null;
}

async function fetchBlocks(user, lestart, leend, blocks=[], cont) {
    data = await $.getJSON({
        url: "https://inciclopedia.org/w/api.php?action=query&format=json&formatversion=2&list=logevents&letitle=User:" + encodeURIComponent(user) + "&leaction=block/block" + (lestart ? "&lestart=" + encodeURIComponent(lestart) : "") + (leend ? "&leend=" + encodeURIComponent(leend) : "")+ (cont ? "&lecontinue=" + encodeURIComponent(cont) : "")
    });
    if (data["query"] && data["query"]["logevents"]) {
        blocks.push(...data["query"]["logevents"]);
    }
    if (data["continue"] && data["continue"]["lecontinue"]) {
        return await fetchBlocks(user, lestart, leend, blocks, data["continue"]["lecontinue"])
    }
    return blocks;
}

function getEditDictAndSize(contribs) {
    const edits = {};
    let size = 0;
    for (const contrib of contribs) {
        if (contrib["comment"].includes("redirigida")) continue;
        size+=contrib["size"];
        if (contrib["title"] in edits) {
            edits[contrib["title"]]++;
        } else {
            edits[contrib["title"]] = 1;
        }
    }
    return {edits, size};
}

function getCategoryDict(categoryInstances) {
    const categories = {};
    for (const category of categoryInstances) {
        if (category in categories) {
            categories[category]++;
        } else {
            categories[category] = 1;
        }
    }
    return categories;
}

async function fetchCategories(titles, cont, result=[]) {
    const queryFor = titles.slice(0, 50).map((t) => encodeURIComponent(t));
    data = await $.getJSON({
        url: "https://inciclopedia.org/w/api.php?action=query&format=json&formatversion=2&generator=categories&titles=" + queryFor.join("|") + (cont ? "&gclcontinue=" + encodeURIComponent(cont) : "")
    });
    if (data["query"] && data["query"]["pages"]) {
        result.push(...data.query.pages.map((it) => it.title))
    }
    if (data["continue"] && data["continue"]["gclcontinue"]) {
        return await fetchCategories(titles, data["continue"]["gclcontinue"], result);
    }
    if (titles.length > 20) {
        return await fetchCategories(titles.slice(50), undefined, result);
    }
    return result;
}

async function fetchUserEditCount(user) {
    data = await $.getJSON({
        url: "https://inciclopedia.org/w/api.php?action=query&list=users&ususers=" + encodeURIComponent(user) + "&usprop=editcount&formatversion=2&format=json"
    });
    return data["query"] && data["query"]["users"] && data["query"]["users"].length > 0 ? data.query.users[0].editcount : 0;
}

async function fetchSummaryData(user = mw.config.values["wgUserName"], start="2024-12-01T00:00:00", end="2023-12-01T00:00:00") {
    const excludedNamespaces = ["Archivo", "Plantilla", "Categoría", "Archivo discusión", "MediaWiki discusión", "Plantilla discusión", "Categoría discusión", "MediaWiki", "Inciclopedia", "Inciclopedia discusión", "Foro", "Discusión", "Usuario", "Usuario discusión", "Incinoticias Discusión", "Incijuegos", "Incijuegos Discusión"];
    const contribs = await fetchContribs(user, [], undefined, start, end);
    const {edits, size} = getEditDictAndSize(contribs);
    const pagesEdited = contribs.filter((it) => !it["comment"].includes("redirigida") && (!it["title"].includes(":") || !excludedNamespaces.includes(it["title"].substring(0, it["title"].indexOf(":")))));
    const pagesCreated = contribs.filter((it) => it["new"] && !it["comment"].includes("redirigida") && (!it["title"].includes(":") || !excludedNamespaces.includes(it["title"].substring(0, it["title"].indexOf(":")))));

    const topPages = Array.from(new Set(pagesEdited.map((it) => it.title))).filter((key) => !key.includes(":") || !excludedNamespaces.includes(key.substring(0, key.indexOf(":")))).map((key) => [key, edits[key]]).sort((n1, n2) => n2[1] - n1[1]).map((n) => n[0]).slice(0,5);
    const categoryInstances = pagesEdited.length < 2000 ? await fetchCategories(pagesEdited.map((it) => it.title), undefined, []) : [];
    const categoryDict = getCategoryDict(categoryInstances);
    const topCategories = Object.keys(categoryDict).map((key) => [key, categoryDict[key]]).sort((n1, n2) => n2[1] - n1[1]).slice(0, 5);
    const firstEdit = await fetchFirstContrib(user);
    const blocks = await fetchBlocks(user, start, end, []);
    const userEditCount = await fetchUserEditCount(user);
    let character = "tio2";
    let characterAttribute = "";

    let mostEdited = "";
    let mostEditedPrincipal = "";
    let editNo = 0;
    let editNoPrincipal = 0;
    for (const key in edits) {
        if (edits[key] > editNo) {
            mostEdited = key;
            editNo = edits[key];
        }
        if (!key.includes(":") && edits[key] > editNoPrincipal) {
            mostEditedPrincipal = key;
            editNoPrincipal = edits[key];
        }
    }
    if (pagesEdited.length < 10) {
        character = "tio1";
    }
    if (editNoPrincipal > contribs.length * 0.2) {
        character = "billgates";
        characterAttribute = mostEditedPrincipal;
    }
    if (pagesEdited.length > 10 && size > 1000000) {
        character = "cervantes";
    }
    const incijuegos = contribs.filter((c) => c.new && !c.title.includes("discusión") && c.title.includes("Incijuegos"));
    if (incijuegos.length > 0) {
        character = "shigeru";
        characterAttribute = incijuegos[0].title.replace("Incijuegos", "").replace("/", "").replace(":", "");
    }
    const atunes = contribs.filter((c) => c.new && !c.title.includes("discusión") && c.title.includes("ATunes"));
    if (atunes.length > 0) {
        character = "taylor";
        characterAttribute = atunes[0].title.replace("ATunes/Canciones/", "");
    }
    const incinoticias = contribs.filter((c) => c.new && !c.title.includes("discusión") && c.title.includes("Incinoticias"));
    if (atunes.length > 0) {
        character = "matias";
        characterAttribute = incinoticias[0].title.replace("Incinoticias:", "");
    }
    if (blocks.length > 0) {
        character = "jimbo";
    }

    return {
        user,
        firstEdit,
        numberOfEdits: contribs.length,
        userEditCount,
        numberOfPagesEdited: new Set(contribs.map((it) => it["title"])).size,
        numberOfPagesCreated: pagesCreated.length,
        totalEditSize: size,
        topPages,
        topCategories: topCategories.map((n) => n[0].substring(n[0].indexOf(":") + 1)),
        top1CategoryEdits: topCategories.length > 0 ? topCategories[0][1] : null,
        character,
        characterAttribute,
        isAll: start===null
    }
}

function b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
        function toSolidBytes(match, p1) {
            return String.fromCharCode('0x' + p1);
    }));
}

async function generateToken(user, start, end) {
    const wrapped = await fetchSummaryData(user, start, end);
    return b64EncodeUnicode(JSON.stringify(wrapped));
}

async function magic(user, all) {
    $("#notDialog").hide();
    if (localStorage.getItem("token2-" + (all ? "all-" : "") + user)) {
        $("#viewDialog").show();
        $("#viewSummary").html('<a href="https://wrapped.inciclopedia.es/?token=' + localStorage.getItem("token2-" + (all ? "all-" : "") + user) + '" target="_blank">Ver mi resumen ' + (all ? 'de todos los tiempos' : 'del año') + '</a>');
    } else {
        $("#generateDialog").show();
        $("#confirmRequest").click(() => {
            $("#confirmRequest").hide();
            $("#wait").show();
            generateToken(user, all ? null : undefined, all ? null : undefined).then((token) => {
                localStorage.setItem("token2-" + (all ? "all-" : "") + user, token);
                $("#generateDialog").hide();
                $("#viewDialog").show();
                $("#viewSummary").html('<a href="https://wrapped.inciclopedia.es/?token=' + token + '" target="_blank">Ver mi resumen ' + (all ? 'de todos los tiempos' : 'del año') + '</a>');
            }).catch(() => {
                $("#error").show();
            })
        })
    }
}


if (mw.config.values["wgUserName"]) {
    magic(mw.config.values["wgUserName"], true);
}