( function ( $, mw ) { mw.loader.using( ["mediawiki.api", "jquery.chosen", "oojs-ui-core"], function () {
mw.loader.load( "mediawiki.ui.input", "text/css" );
var api = new mw.Api( { userAgent: 'draft-sorter/0.0.1' } );
if ( mw.config.get( "wgNamespaceNumber" ) !== 118 ) {
// Configure defaults
//var templateCache = mw.config.get("wgFormattedNamespaces")[2]+":"+mw.config.get("wgUserName")+"/Scripts/draft-sorter.json";
//var templateCache = "Wikipedia:WikiProject Articles for creation/WikiProject templates.json";
var templateIncludelistName = "Wikipedia:WikiProject Articles for creation/WikiProject templates.json/includelist.json";
var templateBlocklistName = "Wikipedia:WikiProject Articles for creation/WikiProject templates.json/blocklist.json";
var wikiProjectMainCategory = "Category:WikiProject banner wrapper templates";
var wikiProjectCategories = [ // other WikiProject categories not included in wikiProjectMainCategory
"Category:WikiProject banners with quality assessment",
"Category:WikiProject banners without quality assessment",
"Category:WikiProject banner templates not based on WPBannerMeta",
"Category:Inactive WikiProject banners",
"Category:WikiProject banner wrapper templates",
];
// Define the form
);
// Add the form to the page
form.insertAfter( "#jump-to-navcontentSub" );
var select = $( "<select>" )
var wikiprojects = {};
new mw.Api()api.get( {
action: "query",
titles: "Draft talk:" + mw.config.get( "wgTitle" ),
console.log( existingProjects );
fetchJSONList(templateCache).then( (cachedList) => {
checkTemplateCache(wikiprojects = cachedList);
constructForm();
} );
} ).fail (function() {
console.log("Retrieving project templates from talk page failed.");
fetchJSONList(templateCache).then( (cachedList) => {
checkTemplateCache(wikiprojects = cachedList);
constructForm();
} );
});
try {
listData = await new mw.Api()api.get( query );
} catch (jsonerror) {
console.warn("Unable to fetch contents of " + listName + ":");
return parsedList;
}
function checkTemplateCache(cachedList) {
console.log("Retrieved cache from "+templateCache+".");
if (cachedList._timestamp) {
var cacheTimestamp = new Date(cachedList._timestamp);
delete cachedList._timestamp;
//Check if cache timestamp is more than 24 hours old
if ( isFinite(cacheTimestamp) && (Date.now() - cacheTimestamp < 86400000) ) {
console.log("Cache timestamp \"" + cacheTimestamp + "\" OK.");
wikiprojects = cachedList;
constructForm();
} else {
console.warn("Cache timestamp \"" + cacheTimestamp + "\" too old. Rebuilding...");
getTemplateCategories();
}
} else {
console.warn(wikiprojects);
console.warn("Cannot find timestamp in cache. Rebuilding...");
getTemplateCategories();
}
}
function writeTemplateCache() {
wikiprojects = Object.keys(wikiprojects).sort().reduce(
(obj, key) => {
obj[key] = wikiprojects[key];
return obj;
},
{}
);
wikiprojects._timestamp = new Date().toJSON();
var params = { action: 'edit',
title: templateCache,
text: JSON.stringify(wikiprojects),
summary: "Update WikiProject cache ([[User:Ahecht/Scripts/draft-sorter|draft-sorter]])",
watchlist:"unwatch"
};
new mw.Api().postWithToken("csrf", params ).done( function(reslt) {
console.log(templateCache + " updated:");
console.log(reslt);
constructForm();
} ).fail( function(reslt) {
console.error("Error updating " + templateCache + ":");
console.error(reslt);
constructForm();
} );
}
function nextDraft() {
// Special:RandomInCategory isn't random, souse thistoolforge function is ainstead
// better substitute.
draftList = [];
console.log ("Fetching drafts from API");
if (nextButton) {
nextButton.setLabel( "Loading..." ).setDisabled( true );
}
window.___location.href = "https://randomincategory.toolforge.org/Pending_AfC_submissions?draftsorttrigger=y&cmnamespace=118&cmtype=page&returntype=subject&server=" + mw.config.get("wgServerName");
getDrafts();
function getDrafts(cont) { // Recursively call API
var query = {
action: "query",
list: "categorymembers",
cmtitle: "Category:Pending_AfC_submissions",
cmprop: "title",
cmnamespace: "118",
cmtype: "page",
cmlimit: "max"
};
if (cont) {
query = Object.assign(query, cont);
}
new mw.Api().get( query )
.done (function (data) {
if (data && data.query && data.query.categorymembers) { //API query returned pages
data.query.categorymembers.forEach(function(item) {
draftList.push( item.title );
} );
}
if (data && data.continue) { //More results are available
getDrafts(data.continue);
} else { // Redirect to random page
console.log("Done fetching drafts!");
window.___location.href = mw.config.get( "wgServer" )
+ "/wiki/"
+ draftList[Math.random() * draftList.length | 0]
+ "?draftsorttrigger=y";
}
} ).fail (function(error) { // Use Special:RandomInCategory
console.error("Error getting list of drafts:");
console.error(error);
window.___location.href = mw.config.get( "wgServer" )
+ "/wiki/Special:RandomInCategory/Pending_AfC_submissions?draftsorttrigger=y";
} );
return;
}
}
$( "#draft-sorter-status" ).append( "<li>Suggested categories from <a href=\"https://www.mediawiki.org/wiki/ORES#Topic_routing\">ORES</a>:<ul id=\"draft-sorter-suggest\"></ul></li>" );
predicts.forEach( function(item) {
function addWithLink(p) {
var addLink = $( "<a>" )
$( "#draft-sorter-suggest" ).append(
.text("add")
$( "<li>" ).clicktext( functionitem + " ()" {).append(
$( select"<a>" ).valtext("add").click(
function() {
$( select ).val().concat( [ "WikiProject " + item ] )
$( select ).val(
).trigger("chosen:updated");
$( select ).val().concat( [ "WikiProject " + p ] )
} );
).trigger("chosen:updated");
}
)
).append( ")" )
);
}
var singularItem = item.replace(/s$/, '');
if( !existingProjects.includes( "WikiProject " + item )
&& wikiprojects[item]
) { //Prediction matches a WikiProject and doesn't already exist
addWithLink(item);
$( "#draft-sorter-suggest" ).append( $( "<li>" )
.append( item + " (" )
.append( addLink )
.append( ")" )
);
} else if( singularItem != item
&& !existingProjects.includes( "WikiProject " + singularItem )
&& wikiprojects[singularItem]
) { //Singular form of prediction matches a WikiProject and doesn't exist
addWithLink(singularItem);
addLink.click( function() {
$( select ).val(
$( select ).val().concat( [ "WikiProject " + singularItem ] )
).trigger("chosen:updated");
} );
$( "#draft-sorter-suggest" ).append( $( "<li>" )
.append( singularItem + " (" )
.append( addLink )
.append( ")" )
);
} else { //Prediction doesn't match a WikiProject or already exists
$( "#draft-sorter-suggest" ).append(
function getPredicts() {
var dbNamelang = mw.config.get( "wgDBnamewgServerName").split(".wikipedia.org" );
if (lang.length == 1) return;
const liftWingExternalEndpoint = "https://api.wikimedia.org/service/lw/inference/v1/models/";
let headers = new Headers({
"Content-Type": "application/json",
"User-Agent": "draft-sorter (https://en.wikipedia.org/wiki/User:Ahecht/Scripts/draft-sorter.js)"
});
var revID = mw.config.get( "wgCurRevisionId" );
var model = (lang[0] == "en") ? "enwiki-drafttopic" : "outlink-topic-model";
var postBody = JSON.stringify({
$.getJSON( "//ores.wikimedia.org/v3/scores/" + dbName + "/" + revID + "/drafttopic" )
"rev_id": revID,
.done( function ( data ) {
"lang": lang[0],
if(data && data[dbName] && data[dbName].scores &&
"page_title": mw.config.get("wgPageName")
data[dbName].scores[revID] &&
});
data[dbName].scores[revID].drafttopic &&
data[dbName].scores[revID].drafttopic.score &&
fetch(liftWingExternalEndpoint + model + ":predict", {
data[dbName].scores[revID].drafttopic.score.prediction) {
method: "POST",
headers: new Headers({
"Content-Type": "application/json",
"User-Agent": "draft-sorter (https://en.wikipedia.org/wiki/User:Ahecht/Scripts/draft-sorter.js)"
}),
body: postBody
}).then(response => response.json()).then(data => {
var prediction = [];
var dbName = mw.config.get("wgDBname");
if(data && data[dbName] && data[dbName].scores &&
data[dbName].scores[revID] &&
data[dbName].scores[revID].drafttopic &&
data[dbName].scores[revID].drafttopic.score &&
data[dbName].scores[revID].drafttopic.score.prediction) {
prediction = data[dbName].scores[revID].drafttopic.score.prediction;
} else if (data && data.prediction && data.prediction.results) {
data.prediction.results.forEach( p => {
if (p && p.topic) prediction.push(p.topic);
} );
}
if (prediction.length) {
console.log("Got ORES response! Raw predictions:");
console.log(prediction);
prediction.forEach( function (item) {
var last = item.split(".")[item.split(".").length-1];
var penultimate = item.split(".")[item.split(".").length-2];
if ( last.substr(-1) == "*" ) {
// Filter out redundant starred predictions
if (prediction.find(element => (
element.split(".")[element.split(".").length-1] != last &&
element.split(".")[element.split(".").length-2] == penultimate
) ) ) {
console.log("Prediction \"" + last + "\" excluded.");
last = null;
} else {
last = penultimate;
}
}
if ( wikiprojects[last] ) {
var prediction = data[dbName].scores[revID].drafttopic.score.prediction;
// WikiProject found, no need to try splitting
console.log("Got ORES response! Raw predictions:");
console predicts.logpush(predictionlast);
} else if ( last ) {
// Can't find wikiProject, try splitting
prediction.forEach( function (item) {
var lastsplitLast = itemlast.split(".")[item.split/("." & | and )/).length-1];
var penultimatefor (i= item.split(".")[item.split(".")0;i<=splitLast.length-;i+=2];) {
if splitLast[i] (= lastsplitLast[i].substrcharAt(-10) == "*" .toUpperCase() {
+ splitLast[i].slice(1);
// Filter out redundant starred predictions
if (predictionpredicts.findpush(element =>splitLast[i] ();
element.split(".")[element.split(".").length-1] != last &&
element.split(".")[element.split(".").length-2] == penultimate
) ) ) {
console.log("Prediction \"" + last + "\" excluded.");
last = null;
} else {
last = penultimate;
}
}
}
if ( wikiprojects[last]} ) {;
console.log("Filtered predictions:");
// WikiProject found, no need to try splitting
predictsconsole.pushlog(lastpredicts);
} else if showPredicts( last ) {;
} else {
// Can't find wikiProject, try splitting
console.warn("Error finding predictions in ORES response:");
var splitLast = last.split(/( & | and )/);
console.warn(data);
for (i=0;i<=splitLast.length;i+=2) {
}
splitLast[i] = splitLast[i].charAt(0).toUpperCase()
} ).catch( e => console.warn("Error retrieving ORES data: " + e) );
+ splitLast[i].slice(1);
predicts.push( splitLast[i] );
}
}
} );
console.log("Filtered predictions:");
console.log(predicts);
showPredicts();
} else {
console.error("Error finding predictions in ORES response:");
console.error(data);
}
} ).fail( function ( error ) {
console.error("Error retrieving ORES data: " + error);
} );
return;
}
function getTemplateCategories(cont) { // Recursively call API
var query = {
action: "query",
list: "categorymembers",
cmtitle: wikiProjectMainCategory,
cmtype: "subcat",
cmlimit: "max"
};
if (cont) {
query = Object.assign(query, cont);
}
new mw.Api().get( query )
.done (function (data) {
if (data && data.query && data.query.categorymembers) { //API query returned members
Object.entries(data.query.categorymembers).forEach( function(item) {
wikiProjectCategories.push(item[1].title);
} );
}
if (data && data.continue) { //More results are available
getTemplateCategories(data.continue);
} else {
fetchJSONList(templateBlocklistName).then( (templateBlocklist) => {
console.log("Template blocklist:");
console.log(templateBlocklist);
getTemplatesFromCategories(templateBlocklist);
} );
}
} ).fail (function(error) {
console.error("Error getting list of categories:");
console.error(error);
} );
return;
}
function getTemplatesFromCategories(templateBlockList, catTitle, cont) { // Recursively call API
if (typeof catTitle === 'undefined') { // Grab next item in wikiProjectCategories
catTitle = wikiProjectCategories.pop();
}
if (typeof catTitle === 'undefined') { // No remaining entries in wikiProjectCategories
// Manually add Wikiprojects with /s in their title
fetchJSONList(templateIncludelistName).then( (templateIncludelist) => {
console.log("Template includelist:");
console.log(templateIncludelist);
jQuery.extend( wikiprojects, templateIncludelist );
writeTemplateCache();
} );
} else {
var query = {
action: "query",
list: "categorymembers",
cmtitle: catTitle,
cmtype: "page",
cmnamespace: "10",
cmlimit: "max"
};
if (cont) {
query = Object.assign(query, cont);
}
new mw.Api().get( query )
.done (function (data) {
if (data && data.query && data.query.categorymembers) { //API query returned members
Object.entries(data.query.categorymembers).forEach( function(item) {
var title = item[1].title.match(/^Template:WikiProject\s(.*)$/);
if (title && title[1] && title[1] !== "") { //Valid page name format
if (title[1].indexOf("/") == -1 || title[1].match(/ task ?force$/i) ) { //No subpages
title[1] = title[1].replace(/ task ?force$/i,"");
if( !(templateBlockList[ title[1] ]) ) { //Not on blocklist
wikiprojects[ title[1] ] = item[1].title.replace("Template:", "");
}
}
}
} );
}
if (data && data.continue) { //More results are available
getTemplatesFromCategories(templateBlockList, catTitle, data.continue);
} else {
getTemplatesFromCategories(templateBlockList);
}
} ).fail (function(error) {
console.error("Error getting list of templates:");
console.error(error);
constructForm();
} );
return;
}
}
function editTalk(text, prefix) {
var params = {
action: "edit", section: "0",
title: "Draft talk:" + mw.config.get( "wgTitle" ),
summary: "Tagging draft: +" + newTags.join(", +") +
" ([[User:Ahecht/Scripts/draft-sorter.js|draft-sorter.js]])",
};
params[prefix + "text"] = text;
new mw.Api()api.postWithEditToken( params ).done( function ( data ) {
if ( data && data.edit && data.edit.result && data.edit.result === "Success" ) {
showStatus( "Edit saved successfully! (" )
}
new mw.Api()api.get( {
action: "query",
titles: "Draft talk:" + mw.config.get( 'wgTitle' ),
var talkText = data.parse.wikitext["*"];
if (typeof(talkText) == "string") {
var pattern = /(\{\{\s*(?:Wiki[ _]?Project[ _]?banners?[ _]?shell(?:\/redirect)?|(?:(?:WP)?[ _]?Banner|(?:Wiki)?Project|Scope)[ _]?shell|Multiple[ _]wikiprojects|WikiProject[ _]?Banners?|WPBS?)\s*\|(?:\s*[a-z1]+\s*=[^\{\}]*)*\s*(?:\\n)*?)/im;
if (talkText.search(pattern) >= 0) {
newText = talkText.replace( pattern, ("$1" + newText) );
|