Last active
December 17, 2015 15:09
-
-
Save britto/5629340 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name Campfire Alerts | |
// @description Issues sound alerts for messages addressed to the user | |
// @match https://*.campfirenow.com/room/* | |
// @author João Britto | |
// @grant none | |
// ==/UserScript== | |
function init(chat, Campfire, Class, escapeRegExp) { | |
Campfire.PersonalMessageHandler = Class.create({ | |
initialize: function(chat) { | |
this.chat = chat; | |
this.initPattern(); | |
}, | |
initPattern: function() { | |
var tokens = this.chat.username.split(/\s+/), | |
names = [], | |
initials = ''; | |
for (var i = 0; i < tokens.length; i++) { | |
var initial = tokens[i].match(/^[A-Z]/); | |
if (initial) { | |
names.push(escapeRegExp(tokens[i])); | |
initials += initial; | |
} | |
} | |
this.pattern = new RegExp('\\b(?:' + names.join('|') + '|' + initials + ')\\b', 'i'); | |
}, | |
onMessagesInserted: function(messages) { | |
for (var i = 0; i < messages.length; i++) { | |
this.proccessMesage(messages[i]); | |
} | |
}, | |
proccessMesage: function(message) { | |
if (message.kind === 'text') { | |
var messageBody = message.bodyElement().textContent; | |
if (this.pattern.test(messageBody)) { | |
message.authorCell.style.backgroundColor = '#D9FAD9'; | |
message.bodyCell.style.backgroundColor = '#D9FAD9'; | |
this.chat.soundmanager.play('incoming', true); | |
notify(message.author(), { body: messageBody }); | |
} | |
} | |
} | |
}); | |
chat.personalmessagehandler = new Campfire.PersonalMessageHandler(chat); | |
chat.listeners.push(chat.personalmessagehandler); | |
// Cache for the 'messagesInserted' event must be cleared to enable the new listener | |
chat.events.messagesInserted = undefined; | |
} | |
function notify(title, options) { | |
// Ensure user granted permissions for Notification | |
if (Notification.permission !== 'granted') { | |
Notification.requestPermission(function (permission) { | |
if (Notification.permission !== permission) | |
Notification.permission = permission; | |
}); | |
} | |
if (Notification.permission === 'granted') | |
var n = new Notification(title, options); | |
} | |
init(window.chat, window.Campfire, window.Class, window.RegExp.escape); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment