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:
//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
$( 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( "#
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 existingProjects = [];
var wikiprojects = {};
Line 77 ⟶ 92:
console.log( "Project templates found on talk page: ");
console.log( existingProjects );
fetchJSONList(templateCache).then( (cachedList) => {
wikiprojects = cachedList;
constructForm();
} );
} ).fail (function() {
console.log("Retrieving project templates from talk page failed.");
fetchJSONList(templateCache).then( (cachedList) => {
wikiprojects = cachedList;
constructForm();
} );
});
predicts = [];
async function
var parsedList = {}, listData;
action:'parse',
prop:'wikitext',
page: listName,
formatversion: '2',
origin: '*'
};
try {
listData = await api.get( query );
} catch (jsonerror) {
console.warn("Unable to fetch contents of " + listName + ":");
console.log(jsonerror);
}
if (listData && listData.parse && listData.parse.wikitext) {
try {
parsedList = JSON.parse(listData.parse.wikitext);
} catch (jsonerror) {
console.warn("Error parsing JSON list " + listName + ":");
console.log(jsonerror);
}
}
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#
predicts.forEach( function(item) {
function addWithLink(p) {
$( "#draft-sorter-suggest" ).append(
$( "<li>" ).
$(
function() {
$( select ).val(
$( 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);
} else if( singularItem != item
&& !existingProjects.includes( "WikiProject " + singularItem )
&& wikiprojects[singularItem]
) { //Singular form of prediction matches a WikiProject and doesn't exist
addWithLink(singularItem);
} else { //Prediction doesn't match a WikiProject or already exists
$( "#draft-sorter-suggest" ).append(
Line 177 ⟶ 181:
function getPredicts() {
var
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({
"rev_id": revID,
"lang": lang[0],
"page_title": mw.config.get("wgPageName")
});
fetch(liftWingExternalEndpoint + model + ":predict", {
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] ) {
// WikiProject found, no need to try splitting
} else if ( last ) {
// Can't find wikiProject, try splitting
var
+ splitLast[i].slice(1);
}
console.log("Filtered predictions:");
} else {
console.warn("Error finding predictions in ORES response:");
console.warn(data);
}
} ).catch( e => console.warn("Error retrieving ORES data: " + e) );
return;
}
Line 279 ⟶ 269:
mw.loader.load( "oojs-ui.styles.icons-movement");
Object.keys(wikiprojects).sort().forEach( function(name) {
select.append( $( "<option>" )
Line 300 ⟶ 286:
form.append( "  " );
form.append( submitButton.$element );
form.append(
form.append( nextButton.$element );
form.append ( $( "<ul>" )
Line 335 ⟶ 315:
// The submission function
function submit() {
$( "#draft-sorter-form" )
.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
" ([[User:Ahecht/Scripts/draft-sorter };
params[prefix + "text"] = text;
Line 372 ⟶ 360:
.text( "reload" )
.attr( "href", "#" )
.click( function () {
window.
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.
editTalk(newText,"prepend");
} );
Line 426 ⟶ 418:
}
} ).fail( function ( error ) {
console.
editTalk(newText,"prepend");
} );
|