User:TheresNoTime/toastEcho.js

/** /* global $, mw */ /*jshint esversion: 6 */
 * Background Echo notification checking
 * @version 1.0.0
 * @license https://opensource.org/licenses/MIT MIT
 * @license https://opensource.org/licenses/MIT MIT

// Configure let et_version = "1.0.0"; let disp = false;

// Init mw.loader.using(['mediawiki.util', 'mediawiki.api'], setup);

/** * Setup script */ async function setup { console.info(`[toastNotify] v${et_version} loaded`); let permission = await Notification.requestPermission; if(permission) { getEchos; } }

/** * Get the `disp` global variable value * * @returns {boolean} The value of `disp` */ function getDisp { return disp; }

/** * Set the `disp` global variable value * * @param {boolean} set Sets `disp` to this * @returns {boolean} The value of `disp */ function setDisp(set) { console.debug(`[toastNotify] Display: ${getDisp} -> ${set}`); disp = set; return disp; }

/** * Display a toast notification * * @param {int} count The number of new alerts */ function showGenericToast(count) { setDisp(true);

const notification = new Notification('New Wikimedia alert', {       body: `You have ${count} new alerts`,        vibrate: true    });

// close the notification after 120 seconds setTimeout( => {       notification.close;    }, 120 * 1000);

// navigate to a URL notification.addEventListener('click', => {        let host = window.location.hostname;        notification.close;        window.open(`https://${host}/wiki/Special:Notifications`, '_blank');    }); }

/** * Check the returned notification API call * * @param {*} data */ async function checkEchos(data) { let notifications = data.query.notifications; let newCount = notifications.list.length; if(newCount > 0) { console.log(`[toastNotify] ${newCount} new`); showGenericToast(newCount); } else { console.log('[toastNotify] 0 new'); } }

/** * Call the notification API */ function getEchos { if(getDisp == false) { var api = new mw.Api; api.get( {           action: 'query',            meta:'notifications',            format: 'json',            notfilter: '!read',            notunreadfirst: 1        } ).done( function ( data ) {            checkEchos(data);            setTimeout( => { getEchos; }, 60 * 1000);       } );    } else { setTimeout( => {           getEchos;        }, 30 * 1000); } }