User:Vanished user 1929210/js/sandbox/importer.js
外观
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google Chrome、Firefox、Microsoft Edge及Safari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
/* jshint esversion: 6 */
/* globals $:false */
/* globals mw:false */
(_ => {
'use strict';
let pages = [];
let summary = '從中文維基百科匯入[[$1]]';
let source = 'zh.wikipedia.org';
let prefix = 'zh';
let success = 0;
let finished = 0;
let failed = [];
const ajax = async (...params) => new Promise((success, failure) => {
$.ajax(...params).done((...data) => success(...data)).fail((...x) => failure(...x));
});
const readPage = async (url, pageName) => {
let data = await ajax({
url: url,
data: {
action: 'query',
prop: 'revisions',
rvprop: 'content',
titles: pageName, // 多个页面用“|”分隔
redirects: true, // 解析重定向
converttitles: true, // 自动处理简繁转换。仅限中文维基。
format: 'json'
},
dataType: 'jsonp',
type: 'POST',
});
if (data.query) {
let pages = data.query.pages;
for (let pageid in pages) {
let page = pages[pageid];
if ('missing' in page) {
throw new Error('Empty');
} else {
return page.revisions[0]['*'];
}
}
}
};
const writePage = async (pageName, text, summary) => {
let data = await ajax({
url: mw.util.wikiScript('api'),
data: {
format: 'json',
action: 'edit',
title: pageName, // 页面名称
summary: summary, // 编辑摘要
text: text, // 页面内容
token: mw.user.tokens.get('editToken')
},
dataType: 'json',
type: 'POST',
});
if (data && data.edit && data.edit.result === 'Success') {
return true;
} else {
console.log(data);
throw new Error(data);
}
};
const finish = (page, ok) => {
finished++;
if (ok) {
success++;
} else {
failed.push(page);
}
if (finished === pages.length) {
alert(`匯入完成,已匯入${success}/${pages.length}個頁面。匯入以下頁面時出現錯誤:\n${failed.join('\n')}`);
}
};
for (let page of pages) {
readPage(`https://${source}/w/api.php`, page)
.then(content => {
writePage(page, content, summary.replace(/\$1/g, `${prefix}:${page}`))
.then(_ => finish(page, true))
.catch(_ => finish(page, false));
})
.catch(_ => finish(page, false));
}
})();