User:Jdlrobson/Gadget-trending-edits.js

// // Get timely notifications about edit surges on the wiki ( function ( $ ) {	var TRENDING_KEY = 'trending-edits';	var LAST_NOTIFICATION_KEY = 'trending-edits-last';	var DAY = 60 * 60 * 24;	var MIN_TRENDINESS = 4;	var MIN_EDITORS = 6;	var MIN_EDITS = 20;	var TIMESPAN_HOURS = 1;	var NOTIFICATION_DELAY_SECONDS = 5000;

var seen, lastNotification;

function secondsPassed(dateStr) { return (new Date - new Date(dateStr)) / 1000; }

function load { lastNotification = mw.storage.get(LAST_NOTIFICATION_KEY); seen = mw.storage.get(TRENDING_KEY) || '{}'; seen = JSON.parse(seen) || {}; // cleanup old keys $.each( seen, function ( key ) {			if ( secondsPassed(seen[key]) > DAY ) {				delete seen[key];			}		} ); }

function save { mw.storage.set(TRENDING_KEY, JSON.stringify(seen)); mw.storage.set(LAST_NOTIFICATION_KEY, new Date); }

function hatnote { if ( seen[mw.config.get('wgPageName')] ) { $( ' ' ).text( 'This page is currently receiving a high amount of edit traffic.' ).prependTo( '.mw-parser-output' ); }	}

function timeSinceLast { return ( new Date - lastNotification ) }

if (("Notification" in window)) { load; hatnote; if ( !lastNotification || secondsPassed(lastNotification) > TIMESPAN_HOURS * 60 * 60 ) { setTimeout( function {				$.ajax( 'https://wikipedia-trending.wmflabs.org/api/trending/enwiki/' + TIMESPAN_HOURS, { withCredentials: true } ).then( function (data) { var pages = data.pages; if ( pages.length ) { var page = pages[0]; var thumb = page.thumbnail || { source: '/static/apple-touch/wikipedia.png' }; var title = page.title; if ( page.trendiness > MIN_TRENDINESS && page.editors > MIN_EDITORS && page.totalEdits > MIN_EDITS && !seen[page.title] ) { Notification.requestPermission.then(function(result) {								var msg = new Notification('Edit surge: ' + page.normalizedtitle, { body: page.extract, icon: thumb.source } );								seen[title] = new Date;								save;								msg.addEventListener( 'click', function { window.location = mw.util.getUrl( title, { _pushnotification: 'yes' } ); })							});						}					}				} );			}, NOTIFICATION_DELAY_SECONDS ); }	} } ( jQuery )) //