User:Mamue/chat.js

var PINGS = ['mamue','maamue','archive','pdf','epub','sao-scans'];

var discordBot = 'SAODiscordBridge'; var missedMsgCount = 0; var oldWindowTitle = document.title; var isInit = false; var isActive = true; var getFirstWord = function(text) { return text.substr(0, text.indexOf(' ')); }; var scrollToBottom = function { mainRoom.viewDiscussion.scrollToBottom; }; var shouldIgnore = function(name) { return name == wgUserName || document.hasFocus; }; var updateWindowTitle = function { var addOn = missedMsgCount ? '[' + missedMsgCount + '] ' : ''; document.title = addOn + oldWindowTitle; }; var parseMessage = function(attr) { var name = attr.name ? attr.name : getFirstWord(attr.text); var msg = attr.text; var isDiscord = name == discordBot; if (isDiscord) { var split = msg.indexOf(':'); name = msg.substr(0, split); msg = msg.substr(split + 2); // ": " } if (shouldIgnore(name)) return null; else return { name: name + (isDiscord ? ' [Discord]' : ''), msg: msg }; }; var buildInMessage = function(name) { return { title: '[IN] ' + name }; }; var buildOutMessage = function(name) { return { title: '[OUT] ' + name }; }; var buildChatMessage = function(name, msg) { var isMentioned = PINGS.some(function(p) {   return msg.toLowerCase.indexOf(p) !== -1;  }); if (isMentioned) { name = '[MENTION] ' + name; scrollToBottom; } missedMsgCount += 1; updateWindowTitle; return { title: name, body: msg }; }; var getMessage = function(attr) { var msg = parseMessage(attr); if (!msg) return; if (attr.name) return buildChatMessage(msg.name, msg.msg); else if (attr.text.endsWith('is now trapped with us!')) return buildInMessage(msg.name); else return buildOutMessage(msg.name); }; var alertPing = function(chat) { //console.log('start - alertPing'); if (!isActive) return; var msg = getMessage(chat.attributes); if (msg) var blackhole = 'body' in msg ? new Notification(msg.title, { body: msg.body }) : new Notification(msg.title); //console.log('end - alertPing'); }; var initNotifications = function { Notification.requestPermission; var usernameElement = document.querySelector('.username'); var username = usernameElement.textContent; var updateNotificationStatus = function { usernameElement.textContent = username + ' [' + (isActive ? 'On' : 'Off') + ']'; }; updateNotificationStatus; var toggle = function { isActive = !isActive; updateNotificationStatus; }; usernameElement.addEventListener('click', toggle); }; $(document).ready(function { PINGS = PINGS.map(function(t) { return t.toLowerCase; });  var init = function {    if (isInit) {      console.log('binded - alertPing');      initNotifications;      return;    }    isInit = !!(mainRoom.model.chats.bind('afteradd', $.proxy(alertPing, mainRoom.viewDiscussion)));    // keep trying    setTimeout(init, 5000);  };  // skip first few messages if any  setTimeout(init, 2000); }); $(window).on('focus', function { missedMsgCount = 0;  updateWindowTitle; });