跳转到内容

User:Hyijun/MoveTool.js

维基百科,自由的百科全书
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google ChromeFirefoxMicrosoft EdgeSafari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
'use strict';
// Create portlet link
const portletLinkOnline = mw.util.addPortletLink(
    'p-tb',
    'javascript:prepare()',
    '高级移动',
    't-movetool',
    '移动页面时修正内链',
    '',
    '#pt-userpage'
);

// $(portletLinkOnline).on('click', function (e) {
//     console.log('rinnnnnnnnnn');
//     e.preventDefault();
// });

var old_title;
var new_title;
var reason;
var links = [];
var do_keep_now = true;

async function prepare() {
    const ot = prompt('请输入旧标题,若此页面即为旧标题所在页则可以留空:');
    if (ot !== '') {
        old_title = ot;
    } else {
        old_title = mw.config.get('wgTitle');
    }

    console.log(old_title);
    new_title = prompt('请输入新标题:');
    reason = '使用工具替换内链:' + prompt('请输入移动理由:');
    const pagesLinks = await get_pages_linkin(old_title);
    console.log(pagesLinks);
    for (const link of pagesLinks) {
        console.log(link);
        if (link.ns === 0 || link.ns === 10) {
            const l = link.title;
        } else {
            continue;
        }
        const wt = await get_page_wikitext(l);
        const pr = '暂未能加载预览,请检查源代码,确认后可发布'
        // var pr = await get_preview(replace_pages_link(wt, title,new_title,do_keep_now));
        links.push([l, replace_pages_link(wt, old_title, new_title, do_keep_now), pr]);
    }
    console.log(links);
    start();
}


function start() {
    document.getElementById('content').innerHTML = `
    <h1>移动工具 v1.0</h1>
    <h2>即将对该条目进行移动<!--,请填写并确认以下信息--></h2>
    <fieldset>
        <legend>操作</legend>
        <label for="new_title">新标题:</label>
        <input id="new_title" class="mw-searchInput" name="new_title" size="40">
        <label for="move_reason">移动理由:</label>
        <input id="move_reason" class="mw-searchInput" name="move_reason" size="40">
        <label for="edit_reason">修改内链摘要:</label>
        <input id="edit_reason" class="mw-searchInput" name="edit_reason" size="40" value="通过工具自动修复内链">
        <input name="loadpreview" type="submit" value="加载预览">
        <input name="postedit" onclick=end() type="submit" value="一键发布编辑">
    </fieldset>
    <hr/>
    <p>以下是链入该页面的页面,移动后将自动修复内链</p>
    <ul>
    `;
    for (const [i, link] of Object.entries(links)) {
        document.getElementById('content').innerHTML += `
        <li>
            <a href="${get_link(link[0])}">
            ${link[0]}
            </a>
        </li>
        <details>
            <summary>展开预览</summary>
            <fieldset>
                <legend>预览</legend>
                <div id="preview${i}">
                    ${link[2]}
                    <!--预览内容-->
                </div>
            </fieldset>
            <fieldset style="height:300px">
                <legend>wikitext</legend>
                <textarea style="height:100%; width: 100%">
                    ${link[1]}
                </textarea>
            </fieldset>
            <button id="target" onclick="reload_preview(${i}, links[${i}][0])">发布更改</button>
        </details>
        `;
    }
}

async function end() {
    if (confirm('确定吗?')) {
        if (!is_redirect()) {
            const token = await get_token();
            await move_pages(old_title, new_title, reason, false, token);
        }
        for (const link of links) {
            replace_pages_text(link[0], reason);
        }
        alert('成功');
    } else {
        alert('用户取消操作');
    }
}

function get_link(title) {
    return mw.util.getUrl(title);
}

function reload_preview(number, title) {
    console.log(number);
    document.getElementById(`preview${number}`).innerHTML = get_preview(title);
}


async function get_pages_linkin(title) {
    const data = await new mw.Api().get({
        format: 'json',
        action: 'query',
        prop: 'linkshere',
        titles: old_title,
        formatversion: '2',
    })
    return data[1].pages[0].linkshere;
}

function replace_pages_text(title, summary) {
    return new mw.Api().edit(title, revision => ({
        text: replace_pages_link(revision.content, old_title, new_title, true),
        summary: summary
    }));
}


async function get_token() {
    const data = await new mw.Api().get({
        action: 'query',
        meta: 'tokens',
        type: 'csrf',
        formatversion: '2',
        format: 'json'
    });
    return data.query.tokens.csrftoken;
}

async function is_redirect() {
    const data = await new mw.Api().get({
        action: 'query',
        prop: 'info',
        titles: old_title,
        formatversion: '2',
        format: 'json'
    });
    return data.query.pages[0].redirect;
}

async function get_preview(text) {
    console.log(text);
    const data = await new mw.Api().get({
        action: 'parse',
        prop: 'text',
        page: text,
        contentmodel: 'wikitext',
        format: 'json',
        async: false,
        formatversion: '2',
    });
    return data.parse.text;
}

async function move_pages(old_title, new_title, reason, do_not_direct, token) {
    const data = await new mw.Api().get({
        action: 'move',
        form: old_title,
        to: new_title,
        reason: reason,
        movetalk: true,
        movesubpages: true,
        noredirect: do_not_direct,
        token: token,
        format: 'json',
        formatversion: '2',
    });
    return data;
}

async function get_page_wikitext(title) {
    const data = await new mw.Api().get({
        action: 'query',
        prop: 'revisions',
        titles: title,
        async: false,
        rvprop: 'content',
        rvslots: 'main',
        formatversion: '2',
        format: 'json'
    });
    return data.query.pages[0].revisions[0].slots.main.content;
}

function replace_pages_link(item, old_link, new_link, do_keep_now) {
    const reg1 = new RegExp(`\[\[(${old_link})\]\]`);
    // var reg2 = new RegExp('\\[\\[([^\\[\\[]*?)\\|(' + old_link + ')\\]\\]', 'g');
    const reg2 = new RegExp(`\[\[(${old_link})\|([^\[\[]*?)\]\]`);
    while (reg1.test(item)) {
        item = item.replace(reg1, `[[${new_link}]]`);
    }
    if (do_keep_now) {
        while (reg2.test(item)) {
            item = item.replace(reg2, `[[${reg2.exec(item)[1]}${new_link}|${old_link}]]`);
        }
    } else {
        while (reg2.test(item)) {
            item = item.replace(reg2, `[[${new_link}]]`);
        }
    }
    return item;
}