User:Suffusion of Yellow/autowatch.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
Documentation for this user script can be added at User:Suffusion of Yellow/autowatch. |
/*
* Temporarily add pages linked from the Main Page to your watchlist.
*/
//<nowiki>
//jshint esversion:8, esnext:false
(function() {
'use strict';
const storageKey = "AutoWatchLastChecked";
const pages = window.autoWatchPages || [
{ title: "Main Page",
expiryMin: 3600 * 24,
expiryMax: 3600 * 36,
checkInterval: 900,
namespaces : "0"
}
];
async function autoWatch(sourcePage) {
let response = await (new mw.Api()).get( {
action: "query",
titles: sourcePage.title,
generator: "links",
redirects: true,
gpllimit: "max",
gplnamespace: sourcePage.namespaces,
prop: "info",
inprop: "watched",
curtimestamp: true
});
// Use server time instead of Date.now() in case our clock is wrong
let now = Date.parse(response.curtimestamp);
let expiryMin = now + 1000 * sourcePage.expiryMin;
let expiryMax = now + 1000 * sourcePage.expiryMax;
let toWatch = [];
for (let pageid in response.query.pages) {
let page = response.query.pages[pageid];
// Ignore pages watched indefinitely
if (page.watched !== undefined &&
page.watchlistexpiry == undefined)
continue;
// Ignore pages watched for "long enough"
if (page.watched !== undefined &&
Date.parse(page.watchlistexpiry) >= expiryMin)
continue;
toWatch.push(page.title);
}
for (let i = 0; i < toWatch.length; i += 50) {
let response = await (new mw.Api()).postWithToken("watch", {
action : "watch",
titles : toWatch.slice(i, i + 50).join("|"),
expiry : (new Date(expiryMax).toISOString())
});
}
}
async function autoWatchAll() {
let lastChecked;
try {
lastChecked = JSON.parse(mw.storage.session.get(storageKey)) || { };
} catch(e) {
lastChecked = { };
}
let now = Date.now();
let updated = { };
for (let page of pages) {
if (!lastChecked[page.title] ||
lastChecked[page.title] < now + 1000 * page.checkInterval ||
mw.config.get('wgPageName').replace(/_/g, ' ') == page.title) {
await autoWatch(page);
updated[page.title] = now;
} else {
updated[page.title] = lastChecked[page.title];
}
}
mw.storage.session.set(storageKey, JSON.stringify(updated));
}
mw.loader.using(["mediawiki.storage", "mediawiki.api"]).then(autoWatchAll);
})();
//</nowiki>