User:Ahecht/Scripts/draft-sorter.js: Difference between revisions

Content deleted Content added
Use homegrown substitute for Special:RandomInCategory, because the special page isn't very random and keeps returning the same few pages.
var api = new mw.Api( { userAgent: 'draft-sorter/0.0.1' } );
 
(24 intermediate revisions by the same user not shown)
Line 1:
//jshint maxerr:256512
//jshint esnext:false
//jshint esversion:8
 
//Based on [[User:Enterprisey/draft-sorter.js]] <nowiki>
( 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 ) {
Line 14 ⟶ 18:
}
 
var portletLink = mw.util.addPortletLink("p-cactions", "#", "Sort draft (sandbox)", "pt-draftsort", "Manage WikiProject tags");
$( portletLink ).click( function ( e ) {
e.preventDefault();
Line 20 ⟶ 24:
// If it's already there, don't duplicate
if ( $( "#draft-sorter-wrapper" ).length ) { return; }
 
// 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";
// Define the form
var form = $( "<div>" )
Line 39 ⟶ 47:
);
// Add the form to the page
form.insertAfter( "#jump-to-navcontentSub" );
 
var select = $( "<select>" )
Line 50 ⟶ 58:
.on("click", function ( e ) { submit(); } );
var cancelButton = new OO.ui.ButtonWidget ()
.setLabel( "Cancel" )
.setFlags( ["destructive"] )
.on("click", function( e ) {
$( "#draft-sorter-wrapper" ).remove();
window.___location.replace( window.___location.href.replace("draftsorttrigger=y","") );
} );
 
var nextButton = new OO.ui.ButtonWidget ()
.setIcon( "next" )
Line 56 ⟶ 72:
 
// Determine what templates are already on the talk page
var api = new mw.Api();
var existingProjects = [];
var wikiprojects = {};
Line 77 ⟶ 92:
console.log( "Project templates found on talk page: ");
console.log( existingProjects );
fetchJSONList(templateCache).then( (cachedList) => {
getTemplates();
wikiprojects = cachedList;
constructForm();
} );
} ).fail (function() {
console.log("Retrieving project templates from talk page failed.");
fetchJSONList(templateCache).then( (cachedList) => {
getTemplates();
wikiprojects = cachedList;
constructForm();
} );
});
predicts = [];
async function nextDraftfetchJSONList(listName) {
var parsedList = {}, listData;
// Special:RandomInCategory isn't random, so this function is a
// better substitute.
draftListvar query = [];{
action:'parse',
console.log ("Fetching drafts from API");
prop:'wikitext',
if (nextButton) {
page: listName,
nextButton.setLabel( "Loading..." ).setDisabled( true );
formatversion: '2',
origin: '*'
};
try {
listData = await api.get( query );
} catch (jsonerror) {
console.warn("Unable to fetch contents of " + listName + ":");
console.log(jsonerror);
}
getDrafts();
if (listData && listData.parse && listData.parse.wikitext) {
function getDrafts(cont) { // Recursively call API
try {
var api = new mw.Api();
parsedList = JSON.parse(listData.parse.wikitext);
var query = {
} catch (jsonerror) {
action: "query",
console.warn("Error parsing JSON list " + listName + ":");
list: "categorymembers",
console.log(jsonerror);
cmtitle: "Category:Pending_AfC_submissions",
cmprop: "title",
cmnamespace: "118",
cmtype: "page",
cmlimit: "max"
};
if (cont) {
query = Object.assign(query, cont);
}
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.log("Error getting list of drafts: " + error);
window.___location.href = mw.config.get( "wgServer" )
+ "/wiki/Special:RandomInCategory/Pending_AfC_submissions?draftsorttrigger=y";
} );
return;
}
return parsedList;
}
function nextDraft() {
// Special:RandomInCategory isn't random, use toolforge instead
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");
}
function showPredicts() {
$( "#draft-sorter-status" ).append( "<li>Suggested categories from <a href=\"https://www.mediawiki.org/wiki/ORES#Curation_supportTopic_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(
Line 177 ⟶ 181:
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.log("Error finding predictions in ORES response:");
console.log(data);
}
} ).fail( function ( error ) {
console.log("Error retrieving ORES data: " + error);
} );
return;
}
 
function getTemplates(cont) { // Recursively call API
var api = new mw.Api();
var query = {
action: "query",
generator: "search",
gsrsearch: "hastemplate:\"Template:WPBannerMeta\" prefix:\"Template:WikiProject_\"",
gsrnamespace: "10",
gsrlimit: "max"
};
if (cont) {
query = Object.assign(query, cont);
}
api.get( query )
.done (function (data) {
if (data && data.query && data.query.pages) { //API query returned pages
Object.entries(data.query.pages).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) { //No subpages
wikiprojects[title[1]] = item[1].title.replace("Template:", "");
}
} else {
console.log("No valid title found in the following item:");
console.log(item);
}
} );
}
if (data && data.continue) { //More results are available
getTemplates(data.continue);
} else {
console.log("Done fetching templates!");
constructForm();
}
} ).fail (function(error) {
console.log("Error getting list of templates: " + error);
constructForm();
} );
return;
}
Line 279 ⟶ 269:
mw.loader.load( "oojs-ui.styles.icons-movement");
console.log( "WikiProjects: ");
console.log( wikiprojects );
console.log( "Arguments: ");
console.log( arguments );
Object.keys(wikiprojects).sort().forEach( function(name) {
select.append( $( "<option>" )
Line 300 ⟶ 286:
form.append( "&#32;&#32;" );
form.append( submitButton.$element );
form.append( new OO.uicancelButton.ButtonWidget$element ();
.setLabel( "Cancel" )
.setFlags( ["destructive"] )
.on("click", function( e ) {
$( "#draft-sorter-wrapper" ).remove();
} ).$element
);
form.append( nextButton.$element );
form.append ( $( "<ul>" )
Line 335 ⟶ 315:
// The submission function
function submit() {
$( "#draft-sorter-form" )
submitButton.setLabel( "Submitting..." ).setDisabled( true );
.attr("disabled", true)
.trigger("chosen:updated");
submitButton
.setLabel( "Submitting..." )
.setDisabled( true );
cancelButton
.setLabel ( "Close" );
var newTags = [];
 
Line 345 ⟶ 332:
} );
 
console.log( newTags.length + " new tag(s): " + newTags.join(", ") );
var statusList = $( "#draft-sorter-status" )
.html( "<li>Saving " + newTags.length + " new tags.</li>" );
Line 360 ⟶ 347:
function editTalk(text, prefix) {
var params = {
action: "edit", section: "0",
title: "Draft talk:" + mw.config.get( "wgTitle" ),
summary: "Tagging draftsdraft: +" + newTags.join(", +") +
" ([[User:Ahecht/Scripts/draft-sorter.js|draft-sorter.js]])",
};
params[prefix + "text"] = text;
Line 372 ⟶ 360:
.text( "reload" )
.attr( "href", "#" )
.click( function () { document.___location.reload( true ); } ) )
window.append___location.replace( ")" );
window.___location.href.replace("draftsorttrigger=y","")
);
} )
).append( ")" );
submitButton.setLabel( "Submitted" );
nextButton.setLabel( "Next draft" ).setFlags( [ 'progressive' ] );
} else {
showStatus( "Couldn't save due to error: " + JSON.stringify( data ) );
Line 401 ⟶ 393:
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) );
Line 414 ⟶ 406:
}
} ).fail (function (error) {
console.logwarn( "Couldn't retrieve talk page text due to error: " + JSON.stringify( error ) );
editTalk(newText,"prepend");
} );
Line 426 ⟶ 418:
}
} ).fail( function ( error ) {
console.logwarn( "Couldn't retrieve templates on talk page due to error: " + JSON.stringify( error ) );
editTalk(newText,"prepend");
} );