User:Suffusion of Yellow/autowatch.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
/*
 * 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>