Minecraft Wiki
Advertisement
[создать | история | обновить]Документация
У этого скрипта нет документации. Если вы знаете, как использовать этот скрипт, пожалуйста, добавьте соответствующую информацию.

Замечание. Возможно, после сохранения вам придётся очистить кэш своего браузера, чтобы увидеть изменения.

  • Firefox / Safari: Удерживая клавишу Shift, нажмите на панели инструментов Обновить либо нажмите Ctrl-F5 или Ctrl-R (⌘-R на Mac)
  • Google Chrome: Нажмите Ctrl-Shift-R (⌘-Shift-R на Mac)
  • Internet Explorer: Удерживая Ctrl, нажмите Обновить либо нажмите Ctrl-F5
  • Opera: Выберите очистку кэша в меню Инструменты → Настройки
// <nowiki>
/* eslint strict: ["error", "global"] */
/* globals $, RLQ, mw */

"use strict";

const mod_registry = [];

const mod_aliases = {
    "BC-IC2 Crossover": "BuildCraft-IndustrialCraft 2 Crossover Mod",
    "GraviSuite": "Gravitation Suite",
    "IC2": "IndustrialCraft 2",
    "Mo’Creatures": "Mo'Creatures",
    "RedPower2": "RedPower 2",
    "The CaMping": "The Camping Mod",
    "The Electrical Age": "Electrical Age"
};

const mod_name_repls = [
    [/ThaumCraft/g, "Thaumcraft"]
];

function register_mod(mod_name) {
    let mod_name_norm = mod_name.replace(/_/g, " ").trim();
    mod_name_norm = mod_name_norm.replace(/\/$/, "");

    if (mod_name_norm.startsWith("(") && mod_name_norm.endsWith(")")) {
        mod_name_norm = mod_name_norm.substring(1, mod_name_norm.length - 1).trim();
    }
    for (const replace of mod_name_repls) {
        mod_name_norm = mod_name_norm.replace(replace[0], replace[1]);
    }
    if (mod_aliases[mod_name_norm] !== undefined) {
        mod_name_norm = mod_aliases[mod_name_norm];
    }
    if (mod_name_norm.match(/^\d+$/)) {
        return;
    }

    if (!mod_registry.includes(mod_name_norm)) {
        mod_registry.push(mod_name_norm);
    }
}
// -----------------------------------------------------------------------------
function next_unlicensed_file(api, file_name) {
    return api.get({
        "action": "query",
        "list": "categorymembers",
        "cmtitle": "Категория:Нелицензированные файлы",
        "cmprop": "title",
        "cmlimit": 2,
        "cmsort": "sortkey",
        "cmstartsortkeyprefix": file_name,
        "utf8": true,
        "formatversion": 2
    });
}

function get_next_file_name(data) {
    if (data.continue === undefined) {
        mw.notification.notify("No unlicensed files remaining.");
    } else {
        return data.query.categorymembers[1].title;
    }
}

function jump_to_file(file_title) {
    window.location = `https://minecraft-ru.gamepedia.com/${file_title}`;
}

function get_page_code(templates) {
    let code = "";

    for (const template of templates) {
        code += `{{${template}}}`;
    }

    return code;
}

function get_summary(templates) {
    const base_summary = "license.js: полуавтоматическая простановка ";

    if (templates.length === 1) {
        return `${base_summary}шаблона ${templates[0]}`;
    }

    let summary = `${base_summary}шаблонов `;

    for (let index = 0; index < templates.length; index++) {
        if (index === templates.length - 1) {
            summary += " и ";
        } else if (index > 0) {
            summary += ", ";
        }
        summary += templates[index];
    }

    return summary;
}

function relicense_on_activation(license_text, license_summary) {
    return function (event) {
        $(".licensejs-button").unbind("click.licensejs");
        const $this = $(this);

        $this.append("⌛️");
        const api = new mw.Api();

        next_unlicensed_file(api, mw.config.get("wgTitle"))
            .done((data) => {
                const next_file = get_next_file_name(data);

                api.edit(mw.config.get("wgPageName"), (revision) => {
                    let {content} = revision;

                    if (content.match(/{{\s*[Лл]ицензия/g)) {
                        content = content.replace(/{{\s*[Лл]ицензия\s*}}/, license_text);
                    } else {
                        content = `${content}\n\n== Лицензирование ==\n${license_text}`;
                        content = content.replace(/\n{3,}/g, "\n\n");
                    }

                    return {
                        "text": content,
                        "summary": license_summary,
                        "assert": "user",
                        "minor": true,
                        "bot": true
                    };
                }).done(() => {
                    $this.text($this.text().replace("⌛", "✅"));
                    if (event.shiftKey) {
                        jump_to_file(next_file);
                    } else {
                        window.location.reload();

                        return false;
                    }
                })
                    .fail((data) => {
                        $this.text($this.text().replace("⌛", "❌"));
                        mw.notification.notify(`Edit error: ${data}`);
                    });
            });
    };
}

function get_link(text, templates) {
    const handler = relicense_on_activation(get_page_code(templates), get_summary(templates));


    return $("<li>").append($("<a>").text(text)
        .click(handler));
}

function get_linked_titles() {
    const linked_on = $(".mw-imagepage-linkstoimage a");
    const linked_on_titles = [];

    for (const title_name of linked_on) {
        let title = $(title_name).attr("title");

        if (title.match(new RegExp("частни(к|ца|ка|цы):"))) {
            if (title.includes("/")) {
                title = title.substring(title.indexOf("/") + 1);
            } else {
                continue;
            }
        }
        const ns_match = title.match(/^[^:]+:(\S.+)$/);

        if (ns_match) {
            title = ns_match[1];
        }

        linked_on_titles.push(title);
    }

    return linked_on_titles;
}

function fill_page_title_names() {
    const page_title = mw.config.get("wgTitle");
    const title_matches = [...page_title.matchAll(/\(([^а-яА-Я\(\)]+)\)/g)];

    for (const title_match of title_matches) {
        for (const title_match_entry of title_match) {
            register_mod(title_match_entry);
        }
    }
}

function produce_mod_links() {
    const links = [];

    for (const mod of mod_registry) {
        const mod_title = `L/Mod:${mod}`;
        const mod_code = `{{Лицензия/Модификация|${mod}}}`;
        const mod_template = ["Лицензия/Модификация"];
        const moj_mod_title = "(+Mojang)";
        const moj_mod_code = `{{Лицензия/Mojang}}\n{{Лицензия/Модификация|${mod}}}`;
        const moj_mod_templates = ["Лицензия/Mojang", "Лицензия/Модификация"];

        const handler_mod = relicense_on_activation(mod_code, get_summary(mod_template));
        const handler_moj_mod = relicense_on_activation(moj_mod_code, get_summary(moj_mod_templates));

        links.push($("<li>")
            .append($("<a>")
                .addClass("licensejs-button")
                .text(mod_title)
                .on("click.licensejs", handler_mod)));
        links.push($("<li>")
            .append($("<a>")
                .addClass("licensejs-button")
                .text(moj_mod_title)
                .on("click.licensejs", handler_moj_mod)));
    }

    return links;
}

function get_other_links() {
    const linked_on_titles = get_linked_titles();

    fill_page_title_names();

    for (const title of linked_on_titles) {
        if (title.match(/^[^а-яА-Я\/]+$/)) {
            register_mod(title);
        }

        const new_mod_names = [...title.matchAll(/([^а-яА-Я\n/]+?)\//g)];

        for (const new_mod_name_match of new_mod_names) {
            for (const new_mod_name of new_mod_name_match) {
                register_mod(new_mod_name);
            }
        }

        const final_mod_name = title.match(/\/([^а-яА-Я\n/]+?)$/);

        if (final_mod_name) {
            register_mod(final_mod_name[1]);
        }
    }

    return produce_mod_links();
}

RLQ.push(() => {
    mw.loader.using(["mediawiki.api", "mediawiki.notification"], () => {
        if (mw.config.get("wgCanonicalNamespace") === "File") {
            $("#filetoc").append(get_link("L/Mojang", ["Лицензия/Mojang"]));
            $("#filetoc").append(get_link("L/C418", ["Лицензия/C418"]));
            $("#filetoc").append(get_link("L/©", ["Лицензия/Авторское право"]));
            $("#filetoc").append(get_link("L/SG", ["Лицензия/Простая геометрия"]));

            for (const other_link of get_other_links()) {
                $("#filetoc").append(other_link);
            }

            $("#filetoc").append($("<li>")
                .append($("<a>")
                    .text("След. >>")
                    .on("click.licensejs", () => {
                        next_unlicensed_file(new mw.Api(), mw.config.get("wgTitle"))
                            .done((data) => {
                                jump_to_file(get_next_file_name(data));
                            });
                    })));
        }
    });
});
// </nowiki>
Advertisement