跳转到内容

User:Kurgenera/dash.js

维基百科,自由的百科全书
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google Chrome、Firefox、Microsoft Edge及Safari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
致来访者:

在您计划向本页面提交任何更改前,请知悉维基百科社群关于尊重他人专属空间的编辑指引。除非您当前正在执行符合社群广泛共识的头衔授予,或者在特定置顶区域完成必要的站务签名,否则请勿对本页面的主体内容做出任何形式的文本干扰。此外,本页面承载的全部原创文字均已基于知识共享署名-相同方式共享4.0国际协议进行公开授权,在后续任何形式的重用、分发或衍生过程中,均请严格注意并切实履行您的署名义务与授权原则。
另请注意User:MonoFinet不要搬运和使用本人的任何自动化工具,否则本人对原工具进行快速删除处理。

var _addText="{{工具警告}}";

(function() {
    'use strict';

    // 确保在条目及常规页面下、且MediaWiki核心库可用时才执行
    if (typeof mw === 'undefined') return;

    const style = document.createElement('style');
    style.textContent = 
        '#efficient-nuke-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 99999; }' +
        '#efficient-nuke-modal { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: #fff; padding: 25px; border: 1px solid #ccc; border-radius: 5px; z-index: 100000; width: 450px; max-width: 90%; box-shadow: 0 0 15px rgba(0,0,0,0.5); font-family: sans-serif; color: #333; }' +
        '#efficient-nuke-log { margin-top: 15px; border: 1px solid #eee; padding: 10px; max-height: 200px; overflow-y: auto; font-size: 12px; list-style: none; background: #fdfdfd; text-align: left; }' +
        '#efficient-nuke-log li { margin-bottom: 3px; border-bottom: 1px solid #f0f0f0; padding-bottom: 3px; }' +
        '#nuke-progress-wrapper { height: 10px; background: #eee; border-radius: 5px; margin: 15px 0 5px 0; overflow: hidden; }' +
        '#nuke-progress-bar { height: 100%; background: #007bff; width: 0%; transition: width 0.3s; }' +
        '#nuke-counter-bar { display: flex; justify-content: space-between; font-size: 12px; color: #555; margin-bottom: 10px; padding: 5px; background: #f9f9f9; border-radius: 3px; }' +
        '.nuke-counter-item { text-align: center; flex: 1; }' +
        '.nuke-counter-val { font-weight: bold; color: #007bff; display: block; font-size: 14px; }' +
        '#efficient-nuke-modal .nuke-buttons { display: flex; gap: 10px; margin-top: 10px; }' +
        '#efficient-nuke-modal button { flex: 1; padding: 10px 15px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; }' +
        '#efficient-nuke-modal button#nuke-pause-btn { background-color: #dc3545; display: none; }' +
        '#efficient-nuke-modal textarea { width: 95%; min-height: 100px; padding: 5px; border: 1px solid #ccc; font-size: 14px; }' +
        '#efficient-nuke-modal label { font-size: 14px; font-weight: bold; display: block; margin-top: 10px; text-align: left; }' +
        '#nuke-launch-link { font-weight: bold; color: #d33; cursor: pointer; }';
    document.head.appendChild(style);

    let pageList = [];
    let currentIndex = 0;
    let isPaused = false;
    let successCount = 0;
    let skipCount = 0;
    let failCount = 0;

    // 文本虚拟编辑器,模拟原有代码的代理行为
    class EditorProxy {
        constructor(text) {
            this.text = text;
            this.hasChanges = false;
        }
        get() {
            return this.text;
        }
        set(newText) {
            if (this.text !== newText) {
                this.text = newText;
                this.hasChanges = true;
            }
        }
        replace(regex, replaceValue) {
            const oldText = this.text;
            this.text = this.text.replace(regex, replaceValue);
            if (oldText !== this.text) {
                this.hasChanges = true;
            }
            return this;
        }
    }

    // 核心替换逻辑:将全角波浪号“~”批量替换为连接号“—”
    const runStableFixes = (editor) => {
        editor.replace(/~/g, '—');
    };

    function log(text) {
        const logList = document.getElementById('efficient-nuke-log');
        if (!logList) return;
        const li = document.createElement('li');
        li.textContent = text;
        logList.appendChild(li);
        logList.scrollTop = logList.scrollHeight;
    }

    function updateCounters() {
        document.getElementById('val-total').textContent = pageList.length;
        document.getElementById('val-success').textContent = successCount;
        document.getElementById('val-skip').textContent = skipCount;
        document.getElementById('val-fail').textContent = failCount;
        
        if (pageList.length > 0) {
            const percentage = (currentIndex / pageList.length) * 100;
            document.getElementById('nuke-progress-bar').style.width = percentage + '%';
        }
    }

    // 通过本地 MediaWiki API 获取目标用户主名字空间的贡献列表
    function fetchUserContributions(username, uccontinue = '') {
        const api = new mw.Api();
        const params = {
            action: 'query',
            list: 'usercontribs',
            ucuser: username,
            uclimit: '500',
            ucnamespace: '0', 
            format: 'json'
        };
        if (uccontinue) params.uccontinue = uccontinue;

        api.get(params).done((data) => {
            if (data.query && data.query.usercontribs) {
                const edits = data.query.usercontribs;
                edits.forEach(edit => {
                    if (!pageList.includes(edit.title)) {
                        pageList.push(edit.title);
                    }
                });
                
                updateCounters();

                if (data.continue && data.continue.uccontinue) {
                    fetchUserContributions(username, data.continue.uccontinue);
                } else {
                    log(`成功提取到 ${pageList.length} 个不重复的条目页面。准备启动自动化匹配...`);
                    processNextPage();
                }
            } else {
                log('未找到该用户的任何主名字空间编辑贡献。');
            }
        }).fail(() => {
            log('提取用户贡献时 API 返回错误。');
        });
    }

    // 核心遍历及网络写入队列
    function processNextPage() {
        if (isPaused) return;

        if (currentIndex >= pageList.length) {
            log('====================================');
            log(`批量操作执行完毕。共扫描了 ${pageList.length} 个页面。`);
            document.getElementById('nuke-pause-btn').style.display = 'none';
            return;
        }

        const title = pageList[currentIndex];
        updateCounters();

        const api = new mw.Api();
        
        api.get({
            action: 'query',
            prop: 'revisions',
            titles: title,
            rvprop: 'content|timestamp',
            rvslots: 'main',
            format: 'json'
        }).done((data) => {
            const pages = data.query.pages;
            const pageId = Object.keys(pages)[0];
            
            if (pageId === '-1') {
                log(`[不存在] 页面可能已被删除: ${title}`);
                failCount++;
                currentIndex++;
                setTimeout(processNextPage, 0);
                return;
            }

            const revision = pages[pageId].revisions[0];
            let originalText = revision.slots && revision.slots.main ? revision.slots.main['*'] : revision['*'];
            const basetimestamp = revision.timestamp;

            const editor = new EditorProxy(originalText);
            runStableFixes(editor);

            if (!editor.hasChanges) {
                log(`[无改动] 跳过页面: ${title}`);
                skipCount++;
                currentIndex++;
                setTimeout(processNextPage, 0); 
            } else {
                // 提交条目修改
                api.postWithToken('csrf', {
                    action: 'edit',
                    title: title,
                    text: editor.get(),
                    summary: '依据格式手册([[MOS:连接号]])批量将“~”替换为“—”,使用[[User:Kurgenera/dash.js]]',
                    minor: true,
                    basetimestamp: basetimestamp,
                    bot: false 
                }).done((editData) => {
                    if (editData.edit && editData.edit.result === 'Success') {
                        log(`[已替换] 成功转换并保存页面: ${title}`);
                        successCount++;
                    } else {
                        log(`[未保存] 写入页面未被接受: ${title}`);
                        failCount++;
                    }
                    currentIndex++;
                    setTimeout(processNextPage, 0);
                }).fail((code) => {
                    log(`[失败] 写入页面 ${title} 时遇到致命错误。错误代码: ${code}`);
                    failCount++;
                    currentIndex++;
                    setTimeout(processNextPage, 0);
                });
            }
        }).fail(() => {
            log(`[失败] 读取页面 ${title} 的源码失败。`);
            failCount++;
            currentIndex++;
            setTimeout(processNextPage, 1000);
        });
    }

    function createModal() {
        if (document.getElementById('efficient-nuke-overlay')) return;

        const overlay = document.createElement('div');
        overlay.id = 'efficient-nuke-overlay';

        overlay.innerHTML = `
            <div id="efficient-nuke-modal">
                <h3 style="margin-top:0; color:#202122; font-size:16px; border-bottom:1px solid #a2a9b1; padding-bottom:5px;">连接号批量替换(~ → —)</h3>
                
                <label for="nuke-target-user">目标用户名</label>
                <input type="text" id="nuke-target-user" value="" placeholder="请输入目标用户名" style="width:95%; padding:6px; font-size:14px; margin-top:5px; border:1px solid #a2a9b1;" />
                
                <div id="nuke-progress-wrapper">
                    <div id="nuke-progress-bar"></div>
                </div>
                
                <div id="nuke-counter-bar">
                    <div class="nuke-counter-item">页面总数<span class="nuke-counter-val" id="val-total">0</span></div>
                    <div class="nuke-counter-item">成功修改<span class="nuke-counter-val" id="val-success" style="color:#00af89;">0</span></div>
                    <div class="nuke-counter-item">无需修改<span class="nuke-counter-val" id="val-skip" style="color:#72777d;">0</span></div>
                    <div class="nuke-counter-item">失败<span class="nuke-counter-val" id="val-fail" style="color:#d33;">0</span></div>
                </div>

                <ul id="efficient-nuke-log">
                    <li>准备就绪。输入目标用户名后点击开始运行...</li>
                </ul>

                <div class="nuke-buttons">
                    <button id="nuke-start-btn">开始运行</button>
                    <button id="nuke-pause-btn">暂停</button>
                    <button id="nuke-close-btn" style="background-color:#72777d;">关闭</button>
                </div>
            </div>
        `;
        document.body.appendChild(overlay);

        document.getElementById('nuke-close-btn').addEventListener('click', () => overlay.remove());

        document.getElementById('nuke-start-btn').addEventListener('click', () => {
            const targetUser = document.getElementById('nuke-target-user').value.trim();
            if (!targetUser) {
                log('用户名不能为空!');
                return;
            }
            // 重置队列与计数状态
            pageList = [];
            currentIndex = 0;
            isPaused = false;
            successCount = 0;
            skipCount = 0;
            failCount = 0;
            updateCounters();

            document.getElementById('nuke-start-btn').style.display = 'none';
            document.getElementById('nuke-pause-btn').style.display = 'block';
            
            log(`开始抓取用户「${targetUser}」的贡献历史...`);
            fetchUserContributions(targetUser);
        });

        document.getElementById('nuke-pause-btn').addEventListener('click', () => {
            const btn = document.getElementById('nuke-pause-btn');
            if (!isPaused) {
                isPaused = true;
                btn.textContent = '继续';
                btn.style.backgroundColor = '#00af89';
                log('队列已暂停。');
            } else {
                isPaused = false;
                btn.textContent = '暂停';
                btn.style.backgroundColor = '#dc3545';
                log('继续执行队列...');
                processNextPage();
            }
        });
    }

    // 契合 MediaWiki 内置加载时机,在左侧“工具”栏生成快捷触发入口
    mw.loader.using(['mediawiki.api']).then(function() {
        $(function() {
            const portlet = document.getElementById('p-tb');
            if (!portlet) return;
            const ul = portlet.querySelector('ul');
            if (!ul) return;

            const li = document.createElement('li');
            li.id = 't-dash-batch-nuke';
            li.innerHTML = '<span id="nuke-launch-link">批量替换“~”为“—”</span>';
            ul.appendChild(li);

            li.addEventListener('click', createModal);
        });
    });
})();