Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ==UserScript==
- // @name RPH Tools
- // @namespace https://openuserjs.org/scripts/shuffyiosys/RPH_Tools
- // @version 3.1.1
- // @description Adds extended settings to RPH
- // @match http://chat.rphaven.com
- // @copyright (c)2014 shuffyiosys@github
- // @grant none
- // @license MIT license (https://en.wikipedia.org/wiki/MIT_License)
- // ==/UserScript==
- /*jshint multistr: true */
- /*jshint bitwise: false*/
- /*global $:false */
- /* Template for Modules
- var = (function(){
- html = '';
- return {
- init : function(){
- },
- getHtml : function(){
- return html;
- },
- toString : function(){
- return ' Module';
- },
- };
- }());
- */
- var VERSION_STRING = 'RPH Tools 3.1.1';
- var settingsDialog = {};
- var GetInput = function(settingId) {
- return $('#' + settingId).val();
- };
- var GetCheckBox = function(settingId) {
- return $('#' + settingId).is(':checked');
- };
- var DialogToggle = function(event) {
- var dialog = event.data.dialog;
- if (dialog.state === false) {
- if (event.data.onOpen !== undefined) {
- event.data.onOpen();
- }
- dialog.form.show();
- dialog.state = true;
- } else {
- if (event.data.onClose !== undefined) {
- event.data.onClose();
- }
- dialog.form.hide();
- dialog.state = false;
- }
- };
- var CreateDialog = function(element, form) {
- return {
- button: $(element),
- form: $(form),
- state: false
- };
- };
- var MarkProblem = function(element, mark) {
- if (mark === true) {
- $("#" + element).css('background', '#FF7F7F');
- } else {
- $("#" + element).css('background', '#FFF');
- }
- };
- var ValidateSetting = function(settingId, setting) {
- var validInput = false;
- var input = $('#' + settingId).val();
- switch (setting) {
- case "url":
- validInput = ValidateUrl(input);
- break;
- case "color":
- validInput = ValidateColor(input);
- break;
- }
- MarkProblem(settingId, !validInput);
- return validInput;
- };
- var ValidateColor = function(color) {
- var pattern = new RegExp(/(^#[0-9A-Fa-f]{6}$)|(^#[0-9A-Fa-f]{3}$)/i);
- return pattern.test(color);
- };
- var ValidateUrl = function(url) {
- var match = false;
- var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
- var pingExt = url.slice((url.length - 4), (url.length));
- if (url === '') {
- match = true;
- } else if (regexp.test(url) === true) {
- if (pingExt == ".wav" || pingExt == ".ogg" || pingExt == ".mp3") {
- match = true;
- }
- }
- return match;
- };
- /****************************************************************************
- * @brief: Tests the color range of the color to ensure its valid
- * @param: TextColor - String representation of the color.
- *
- * @return: True if the color is within range, false otherwise.
- ****************************************************************************/
- var ValidateColorRange = function(TextColor) {
- var rawHex = TextColor.substring(1, TextColor.length);
- var red = 255;
- var green = 255;
- var blue = 255;
- /* If the color text is 3 characters, limit it to #DDD */
- if (rawHex.length == 3) {
- red = parseInt(rawHex.substring(0, 1), 16);
- green = parseInt(rawHex.substring(1, 2), 16);
- blue = parseInt(rawHex.substring(2, 3), 16);
- if ((red <= 13) && (green <= 13) && (blue <= 13)) {
- return true;
- }
- }
- /* If the color text is 6 characters, limit it to #D2D2D2 */
- else if (rawHex.length == 6) {
- red = parseInt(rawHex.substring(0, 2), 16);
- green = parseInt(rawHex.substring(2, 4), 16);
- blue = parseInt(rawHex.substring(4, 6), 16);
- if ((red <= 210) && (green <= 210) && (blue <= 210)) {
- return true;
- }
- }
- console.log('RPH Tools[ValidateColorRange]: Color check failed', rawHex, red, green, blue);
- return false;
- };
- /****************************************************************************
- * @brief Adds usernames to droplists.
- * @param user_id - ID of username
- ****************************************************************************/
- var AddUserToDroplist = function(user_id, droplist) {
- getUserById(user_id, function(User) {
- $('#' + droplist).append('<option value="' + user_id + '">' +
- User.props.name + '</option>');
- });
- };
- /****************************************************************************
- * @brief Clears droplists.
- ****************************************************************************/
- var ClearUsersDropLists = function(droplist) {
- $('#' + droplist).empty();
- };
- /****************************************************************************
- * @brief In an array of object, return the first instance where a key
- * matches a value.
- *
- * @param objArray - Array of objects
- * @param key - Key to look for
- * @param value - Value of the key to match
- * @return Index of the first instance where the key matches the value, -1
- * otherwise.
- ****************************************************************************/
- var ArrayObjectIndexOf = function(objArray, key, value) {
- for (var i = 0; i < objArray.length; i++) {
- if (objArray[i][key] === value) {
- return i;
- }
- }
- return -1;
- };
- /****************************************************************************
- * @brief: Checks if a search term is in an <a href=...> tag.
- * @param: searchTerm - String to look for
- * @param: msg - msg being searched.
- *
- * @return: True or false if there's a match.
- ****************************************************************************/
- var IsInLink = function(searchTerm, msg) {
- var regexp = new RegExp('href=".*?' + searchTerm + '.*?"', '');
- return regexp.test(msg);
- };
- /****************************************************************************
- * @brief Generates a hash value for a string
- *
- * @note This was modified from https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery
- ****************************************************************************/
- String.prototype.hashCode = function() {
- var hash = 0,
- i, chr, len;
- if (this.length === 0) return hash;
- for (i = 0, len = this.length; i < len; i++) {
- chr = this.charCodeAt(i);
- hash = ((hash << 31) - hash) + chr;
- hash |= 0; // Convert to 32bit integer
- }
- return hash;
- };
- /****************************************************************************
- * @brief: Checks if the current account is a mod of the room.
- *
- * @param: roomName: Name of the room.
- ****************************************************************************/
- var IsModOfRoom = function(room){
- for(var idx = 0; idx < account.users.length; idx++){
- if (room.props.mods.indexOf(account.users[idx]) > -1 ||
- room.props.owners.indexOf(account.users[idx]) > -1 ){
- return true;
- }
- }
- return false;
- };
- /****************************************************************************
- * @brief: Module for handling the chat functions of the script.
- ****************************************************************************/
- var ChatModule = (function() {
- var pingSettings = {
- 'triggers': [],
- 'audioUrl': 'http://chat.rphaven.com/sounds/boop.mp3',
- 'color': '#000',
- 'highlight': '#FFA',
- 'bold': false,
- 'italics': false,
- 'exact': false,
- 'case': false,
- };
- var chatSettings = {
- 'showNames': true,
- 'noIcons': false,
- 'strictUrl': false,
- 'canCancel': false,
- 'autoJoin': false,
- 'session': false,
- 'roomSession': [],
- 'favRooms': [],
- };
- var localStorageName = "rpht_ChatModule";
- var pingSound = null;
- var autoJoinTimer = null;
- var updateSessionTimer = null;
- var waitForDialog = true;
- var html =
- '<h3 class="rpht_headers" id="chatSettingsHeader">Chat room</h3>' +
- '<div id="chatSettingsForm" style="display:none;">' +
- '<p style="border-bottom: 2px solid #EEE;">' +
- '<span style="background: #333; position: relative; top: 0.7em;"><strong>User text color</strong> </span>' +
- '</p>' +
- '<div class="rpht-block"><label>Username:</label><select style="width: 300px;" id="userColorDroplist"></select></div>' +
- '<div class="rpht-block"><label>Text color:</label><input style="width: 300px;" type="text" id="userNameTextColor" name="userNameTextColor" value="#111"></div>' +
- '<div class="rpht-block"><button type="button" id="userNameTextColorButton">Set color</button></div>' +
- '<p style="border-bottom: 2px solid #EEE;">' +
- '<span style="background: #333; position: relative; top: 0.7em;"><strong>Pings</strong> </span>' +
- '</p><br />' +
- '<p>Names to be pinged (comma separated)</p>' +
- '<textarea id="pingNames" class="rpht_textarea" name="pingNames"> </textarea>' +
- '<br /><br />' +
- '<div class="rpht-block"><label>Ping URL: </label><input style="width: 370px;" type="text" id="pingURL" name="pingURL"></div>' +
- '<div class="rpht-block"><label>Text Color: </label><input style="width: 370px;" type="text" id="pingTextColor" name="pingTextColor" value="#000"></div>' +
- '<div class="rpht-block"><label>Highlight: </label><input style="width: 370px;" type="text" id="pingHighlightColor" name="pingHighlightColor" value="#FFA"></div>' +
- '<br>' +
- '<p>Matching options</p> <br/>' +
- '<input style="width: 40px;" type="checkbox" id="pingBoldEnable" name="pingBoldEnable"><strong>Bold</strong>' +
- '<input style="width: 40px;" type="checkbox" id="pingItalicsEnable" name="pingItalicsEnable"><em>Italics</em>' +
- '<input style="width: 40px;" type="checkbox" id="pingExactMatch" name="pingExactMatch">Exact match' +
- '<input style="width: 40px;" type="checkbox" id="pingCaseSense" name="pingCaseSense">Case sensitive' +
- '<br /><br />' +
- '<p style="border-bottom: 2px solid #EEE;">' +
- '<span style="background: #333; position: relative; top: 0.7em;"><strong>Auto Joining</strong> </span>' +
- '</p>' +
- '<div class="rpht-block"><label>Can Cancel: </label><input type="checkbox" id="canCancelJoining" name="canCancelJoining" checked></div>' +
- '<div class="rpht-block"><label>Room Sessioning: </label><input type="checkbox" id="roomSessioning" name="roomSessioning"></div>' +
- '<div class="rpht-block"><label>Join favorites: </label><input type="checkbox" id="favEnable" name="favEnable"></div>' +
- '<div class="rpht-block"><label>Username: </label><select style="width: 300px;" id="favUserList"></select></div>' +
- '<div class="rpht-block"><label>Room: </label><input style="width: 370px;" type="text" id="favRoom" name="favRoom"></div>' +
- '<div class="rpht-block"><label>Password: </label><input style="width: 370px;" type="text" id="favRoomPw" name="favRoomPw"></div>' +
- '<div class="rpht-block"><button type="button" id="favAdd">Add</button></div>' +
- '<p>Favorite rooms</p>' +
- '<select style="width: 403px;" id="favRoomsList" size="5"></select><br><br>' +
- '<div class="rpht-block"><button type="button" id="favRemove">Remove</button></div>' +
- '<br>' +
- '<p style="border-bottom: 2px solid #EEE;">' +
- '<span style="background: #333; position: relative; top: 0.7em;"><strong>Other Settings</strong> </span>' +
- '</p><br />' +
- '<div class="rpht-block"><label>Chat history: </label><input style="width: 300px;" type="number" id="chatHistory" name="chatHistory" max="65535" min="10" value="300"><br /><br /></div>' +
- '<div class="rpht-block"><label>No image icons in chat</label><input style="margin-right: 10px;" type="checkbox" id="imgIconDisable" name="imgIconDisable"></div>' +
- '<div class="rpht-block"><label>Show username in tabs & textbox (requires rejoin)</label><input style="margin-right: 10px;" type="checkbox" id="showUsername" name="showUsername"></div>' +
- '<div class="rpht-block"><label>Strict URL parser</label><input style="margin-right: 10px;" type="checkbox" id="strictUrl" name="strictUrl"></div>' +
- '</div>' +
- '<br />';
- /**************************************************************************
- * @brief: When user joins a room, do the following:
- * - Set up the .onMessage function for pinging
- * - Add the user's name to the chat tab and textarea
- * - Create a room-pair name for the Modding section
- * @param: room - Room that the user has joined
- **************************************************************************/
- var roomSetup = function(room) {
- var thisRoom = getRoom(room.room);
- var userId = GetIdFromChatTab(thisRoom);
- var moddingModule = RphToolsModule.GetModule('Modding Module');
- thisRoom.onMessage = function(data) {
- var thisRoom = this;
- if (account.ignores.indexOf(data.userid) !== -1) {
- return;
- }
- postMessage(thisRoom, data);
- };
- if (chatSettings.showNames) {
- AddNameToUI(thisRoom, userId);
- }
- if (moddingModule !== null) {
- getUserById(room.userid, function(User) {
- var classes = GetClasses(User, thisRoom);
- moddingModule.AddModFeatures(thisRoom, userId, classes);
- });
- }
- ResizeChatTabs();
- if (jQuery._data(window, "events").resize === undefined) {
- $(window).resize(ResizeChatTabs);
- }
- if (chatSettings.session === true) {
- if (ArrayObjectIndexOf(chatSettings.roomSession, 'roomname', room.room) === -1 ||
- ArrayObjectIndexOf(chatSettings.roomSession, 'user', room.userid) === -1) {
- var tempData = {
- 'roomname': room.room,
- 'user': room.userid
- };
- chatSettings.roomSession.push(tempData);
- }
- }
- };
- /****************************************************************************
- * @brief: Takes a message received in the chat and modifies it if it has
- * a match for pinging
- * @param: thisRoom - The room that the message is for.
- * @param: data - The message for the room
- ****************************************************************************/
- var postMessage = function(thisRoom, data) {
- getUserById(data.userid, function(User) {
- var timestamp = makeTimestamp(data.time);
- var msg = parseMsg_rpht(data.msg);
- var classes = '';
- var $el = '';
- var msgHtml = '';
- if (User.blocked) {
- return;
- }
- classes = GetClasses(User, thisRoom);
- /* Check if this is a valid RNG */
- if (msg[msg.length - 1] === '\u200b') {
- msg += ' <span style="background:#4A4; color: #000;">☑</span>';
- }
- /* Add pinging higlights */
- try {
- var testRegex = null;
- testRegex = MatchPing(msg, pingSettings.triggers, pingSettings.case,
- pingSettings.exact);
- if (testRegex !== null) {
- msg = HighlightPing(msg, testRegex, pingSettings.color,
- pingSettings.highlight, pingSettings.bold,
- pingSettings.italics);
- HighlightRoom(thisRoom, pingSettings.color, pingSettings.highlight);
- if (pingSound !== null) {
- pingSound.play();
- }
- }
- if (ModdingModule !== null && IsModOfRoom(thisRoom) === true){
- var modSettings = ModdingModule.GetSettings();
- testRegex = MatchPing(msg, modSettings.alertWords, false, true);
- if (testRegex !== null) {
- msg = HighlightPing(msg, testRegex, "#EEE", "#E00", true, false);
- HighlightRoom(thisRoom, "#EEE", "#E00");
- if (pingSound !== null) {
- ModdingModule.PlayAlert();
- }
- ModdingModule.AutoKick(thisRoom, data.userid, msg);
- }
- }
- } catch (err) {
- console.log('RPH Tools[postMessage]: I tried pinging D:', err);
- msg = parseMsg_rpht(data.msg);
- }
- if (msg.charAt(0) === '/' && msg.slice(1, 3) === 'me') {
- classes += 'action ';
- msg = msg.slice(3);
- msgHtml = '<span class="first">[' + timestamp +
- ']</span>\n<span style="color:#' + User.props.color +
- '"><a class="name" title="[' + timestamp +
- ']" style="color:#' + User.props.color +
- '">' + User.props.name + '</a>' + msg + '</span>';
- } else {
- msgHtml = '<span class="first">[' + timestamp + ']<a class="name" title="[' +
- timestamp + ']" style="color:#' + User.props.color + '">' +
- User.props.name +
- '<span class="colon">:</span></a></span>\n<span style="color:#' +
- User.props.color + '">' + msg + '</span>';
- }
- if (chatSettings.noIcons) {
- $el = AppendMessageTextOnly(msgHtml, thisRoom).addClass(classes);
- } else {
- $el = thisRoom.appendMessage(msgHtml).addClass(classes);
- }
- $el.find('br:gt(7)').remove();
- });
- };
- /****************************************************************************
- * @brief: Gets the user name's classes that are applicable to it
- * @param: User - User of the message
- * @param: thisRoom - Room that the message is being sent to
- ****************************************************************************/
- var GetClasses = function(User, thisRoom) {
- var classes = '';
- if (User.friendOf) {
- classes += 'friend ';
- }
- if (isOwnUser(User)) {
- classes += 'self ';
- }
- if (isOwnerOf(thisRoom, User)) {
- classes += 'owner ';
- } else if (isModOf(thisRoom, User)) {
- classes += 'mod ';
- }
- if (isInGroup(thisRoom, User)) {
- classes += 'group-member ';
- }
- return classes;
- };
- /****************************************************************************
- * @brief: Checks if the message has any ping terms
- * @param: msg - The message for the chat as a string.
- *
- * @return: Returns the match or null
- ****************************************************************************/
- var MatchPing = function(msg, triggers, caseSensitive, exactMatch) {
- var testRegex = null;
- var pingNames = triggers.split(',');
- var regexParam = (caseSensitive ? "m" : 'im');
- if (triggers.length === 0) {
- return testRegex;
- }
- for (i = 0; i < pingNames.length; i++) {
- if (pingNames[i] !== "") {
- var regexPattern = pingNames[i].trim();
- if (exactMatch === true) {
- regexPattern = "\\b" + pingNames[i].trim() + "\\b";
- }
- /* Check if search term is not in a link. */
- if (IsInLink(pingNames[i], msg) === false) {
- testRegex = new RegExp(regexPattern, regexParam);
- if (msg.match(testRegex)) {
- return testRegex;
- }
- }
- }
- }
- return null;
- };
- /****************************************************************************
- * @brief: Adds highlights to the ping term
- * @param: msg - Message to be sent to the chat.
- * @param: testRegex - Regular expression to use to match the term.
- *
- * @param: Modified msg.
- ****************************************************************************/
- var HighlightPing = function(msg, testRegex, color, highlight, bold, italicize) {
- var boldEnabled = "";
- var italicsEnabled = "";
- if (bold === true) {
- boldEnabled = "font-weight: bold; ";
- }
- if (italicize === true) {
- italicsEnabled = "font-style:italic; ";
- }
- msg = msg.replace(testRegex, '<span style="color: ' + color +
- '; background: ' + highlight + '; ' + boldEnabled +
- italicsEnabled + '">' + msg.match(testRegex) + '</span>');
- return msg;
- };
- /****************************************************************************
- * @brief: Adds a highlight to the room's tab
- * @param: thisRoom - Room where the ping happened.
- ****************************************************************************/
- var HighlightRoom = function(thisRoom, color, highlight) {
- //Don't highlight chat tab if the chat is marked as active.
- var testRegex = new RegExp('active', 'im');
- var className = thisRoom.$tabs[0][0].className;
- if (className.search(testRegex) == -1) {
- thisRoom.$tabs[0].css('background-color', highlight);
- thisRoom.$tabs[0].css('color', color);
- thisRoom.$tabs[0].click(function() {
- thisRoom.$tabs[0].css('background-color', '#333');
- thisRoom.$tabs[0].css('color', '#6F9FB9');
- thisRoom.$tabs[0].hover(function() {
- thisRoom.$tabs[0].css('background-color', '#6F9FB9');
- thisRoom.$tabs[0].css('color', '#333');
- }, function() {
- thisRoom.$tabs[0].css('background-color', '#333');
- thisRoom.$tabs[0].css('color', '#6F9FB9');
- });
- });
- }
- };
- /****************************************************************************
- * @brief: Adds user name to chat tab and chat textarea
- * @param: thisRoom - Room that was entered
- * @param: userId - ID of the user that entered
- ****************************************************************************/
- var AddNameToUI = function(thisRoom, userId) {
- getUserById(userId, function(User) {
- var tabsLen = thisRoom.$tabs.length;
- var idRoomName = thisRoom.$tabs[tabsLen - 1][0].className.split(' ')[2];
- var newTabHtml = '<span>' + thisRoom.props.name + '</span><p style="font-size: x-small; position: absolute; top: 12px;">' + User.props.name + '</p>';
- thisRoom.$tabs[tabsLen - 1].html(newTabHtml);
- $('<a class="close ui-corner-all">x</a>').on('click', function(ev) {
- ev.stopPropagation();
- chatSocket.emit('leave', {
- userid: User.props.id,
- name: thisRoom.props.name
- });
- }).appendTo(thisRoom.$tabs[tabsLen - 1]);
- $('textarea.' + idRoomName).prop('placeholder', 'Post as ' + User.props.name);
- $('textarea.' + idRoomName).css('color', "#" + User.props.color);
- });
- };
- /****************************************************************************
- * @brief: Gets the user's ID from the chat tab (it's in the class)
- * @param: thisRoom - Room to get the ID from
- ****************************************************************************/
- var GetIdFromChatTab = function(thisRoom) {
- var tabsLen = thisRoom.$tabs.length;
- var className = thisRoom.$tabs[tabsLen - 1][0].className;
- var charID = className.match(new RegExp(' [0-9]+', ''))[0];
- charID = charID.substring(1, charID.length);
- return parseInt(charID);
- };
- /****************************************************************************
- * @brief Appends message to a room without adding an image icon
- * @param html - HTML to add to the room.
- * @param thisRoom - Object to the room receiving the message.
- *
- * @note This was modified from RPH's original code, which is not covered
- * by this license.
- ****************************************************************************/
- var AppendMessageTextOnly = function(html, thisRoom) {
- var $el = $('<div>\n' + html + '\n</div>').appendTo(thisRoom.$el);
- var extra = 5; //add more if near the bottom
- if (thisRoom.$el[0].scrollHeight - thisRoom.$el.scrollTop() < 50) {
- extra = 60;
- }
- thisRoom.$el.animate({
- scrollTop: '+=' + ($el.outerHeight() + extra)
- }, 180);
- if (thisRoom.$el.children('div').length > account.settings.maxHistory) {
- thisRoom.$el.children('div:not(.sys):lt(3)').remove();
- }
- return $el;
- };
- /****************************************************************************
- * @brief: Resizes chat tabs accordingly
- ****************************************************************************/
- var ResizeChatTabs = function() {
- $('#chat-tabs').addClass('rpht_chat_tab');
- if ($('#chat-tabs')[0].clientWidth < $('#chat-tabs')[0].scrollWidth ||
- $('#chat-tabs')[0].clientWidth + 200 > $('#chat-bottom')[0].clientWidth) {
- $('#chat-top .inner').css('height', 'calc(100% - 20px)');
- $('#chat-bottom').css({
- 'margin-top': '-160px',
- 'height': '120px'
- });
- $('#chat-tabs').addClass('rpht_chat_tab_scroll');
- $('#chat-tabs').css('width', $('#chat-bottom')[0].clientWidth - 200);
- } else {
- $('#chat-top .inner').removeAttr('style');
- $('#chat-bottom').css({
- 'margin-top': '-140px'
- });
- $('#chat-tabs').removeClass('rpht_chat_tab_scroll');
- $('#chat-tabs').css('width', 'auto');
- }
- };
- var parseMsg_rpht = function(msg) {
- var regex_html_loose = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?|^([a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+.*)$)/gi;
- var regex_html_strict = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
- var regex_in_use = (chatSettings.strictUrl ? regex_html_strict : regex_html_loose);
- msg = msg.replace(/</g, '<');
- msg = msg.replace(/>/g, '>');
- msg = msg.replace(/\n/g, '<br />');
- msg = msg.replace(/="/g, '');
- msg = msg.replace(/(\[b\]|\*\*)(.*?)(\[\/b\]|\*\*)/g, '<strong>$2</strong>');
- msg = msg.replace(/(\-\-\-)/g, '—');
- msg = msg.replace(/(\[s\]|\-\-)(.*?)(\[\/s\]|\-\-)/g, '<strike>$2</strike>');
- msg = msg.replace(/(?:\[i\]|\/\/)([^\/].*?)(?:\[\/i\]|\/\/)/g, function(str, p1, offset, s) {
- if (s.charAt(offset - 1) == ":") {
- return str;
- } else {
- return "<em>" + $('<div>' + p1 + '</div>').text() + "</em>";
- }
- });
- msg = msg.replace(regex_in_use,
- function(url) {
- var full_url = url;
- if (!full_url.match('^https?:\/\/')) {
- full_url = 'http://' + full_url;
- }
- return '<a href="' + $('<div>' + full_url + '</div>').text() + '" target="_blank">' + $('<div>' + url + '</div>').text() + '</a>';
- });
- return msg;
- };
- var autoJoiningHandler = function() {
- if (roomnames.length > 0) {
- if (waitForDialog === true) {
- $('<div id="rpht-autojoin" class="inner">' +
- '<p>Autojoining or restoring session.</p>' +
- '<p>Press "Cancel" to stop autojoin or session restore.</p>' +
- '</div>').dialog({
- open: function(event, ui) {
- setTimeout(function() {
- $('#rpht-autojoin').dialog('close');
- }, 10 * 1000);
- },
- buttons: {
- Cancel: function() {
- clearTimeout(autoJoinTimer);
- $(this).dialog("close");
- }
- },
- }).dialog('open');
- waitForDialog = false;
- clearTimeout(autoJoinTimer);
- autoJoinTimer = setTimeout(autoJoiningHandler, 10 * 1000);
- } else {
- if (chatSettings.autoJoin === true) {
- JoinFavoriteRooms();
- }
- if (chatSettings.session) {
- for (var i = 0; i < chatSettings.roomSession.length; i++) {
- var room = chatSettings.roomSession[i];
- var roomInFavs = ArrayObjectIndexOf(chatSettings.favRooms, 'room', room.roomname) > -1;
- var userInFavs = ArrayObjectIndexOf(chatSettings.favRooms, 'userId', room.user) > -1;
- var canJoin = (roomInFavs != userInFavs) || chatSettings.autoJoin;
- /* Restore session if:
- User xor room are not in favorites
- Autojoin is not enabled.
- */
- if (canJoin) {
- chatSocket.emit('join', {
- name: room.roomname,
- userid: room.user
- });
- }
- }
- }
- chatSettings.roomSession = [];
- clearTimeout(autoJoinTimer);
- }
- }
- };
- var JoinFavoriteRooms = function() {
- console.log('Joining favorite rooms');
- for (var i = 0; i < chatSettings.favRooms.length; i++) {
- var favRoom = chatSettings.favRooms[i];
- console.log('Joining favorite room', favRoom);
- chatSocket.emit('join', {
- name: favRoom.room,
- userid: favRoom.userId,
- pw: favRoom.roomPw
- });
- }
- };
- var updateSession = function() {
- var tempSession = [];
- for (var i = 0; i < rph.roomsJoined.length; i++) {
- var roomname = rph.roomsJoined[i].roomname;
- if (ArrayObjectIndexOf(chatSettings.roomSession, 'roomname', roomname) !== -1) {
- tempSession.push(rph.roomsJoined[i]);
- }
- }
- chatSettings.roomSession = tempSession;
- SaveSettings();
- };
- var AddFavoriteRoom = function() {
- var room = getRoom($('#favRoom').val());
- if (room === undefined) {
- MarkProblem('favRoom', true);
- return;
- }
- if (chatSettings.favRooms.length < 10) {
- var favExists = false;
- var hashStr = $('#favRoom').val() + $('#favUserList option:selected').html();
- var favRoomObj = {
- _id: hashStr.hashCode(),
- user: $('#favUserList option:selected').html(),
- userId: parseInt($('#favUserList option:selected').val()),
- room: $('#favRoom').val(),
- roomPw: $('#favRoomPw').val()
- };
- MarkProblem('favRoom', false);
- if (ArrayObjectIndexOf(chatSettings.favRooms, "_id", favRoomObj._id) === -1) {
- $('#favRoomsList').append(
- '<option value="' + favRoomObj._id + '">' +
- favRoomObj.user + ": " + favRoomObj.room + '</option>'
- );
- chatSettings.favRooms.push(favRoomObj);
- console.log('RPH Tools[AddFavoriteRoom]: Added favorite room', favRoomObj);
- }
- if (chatSettings.favRooms.length >= 10) {
- $('#favAdd').text("Favorites Full");
- $('#favAdd')[0].disabled = true;
- }
- }
- };
- var RemoveFavoriteRoom = function() {
- var favItem = document.getElementById("favRoomsList");
- var favItemId = $('#favRoomsList option:selected').val();
- favItem.remove(favItem.selectedIndex);
- for (var favs_i = 0; favs_i < chatSettings.favRooms.length; favs_i++) {
- if (chatSettings.favRooms[favs_i]._id == favItemId) {
- chatSettings.favRooms.splice(favs_i, 1);
- break;
- }
- }
- if (chatSettings.favRooms.length < 10) {
- $('#favAdd').text("Add");
- $('#favAdd')[0].disabled = false;
- }
- };
- var ChangeTextColor = function() {
- var text_color = $('input#userNameTextColor').val();
- if (ValidateColor(text_color) === false ||
- ValidateColorRange(text_color) === false) {
- MarkProblem('userNameTextColor', true);
- } else {
- var userId = $('#userColorDroplist option:selected').val();
- text_color = text_color.substring(1, text_color.length);
- getUserById(userId, function(User) {
- MarkProblem('userNameTextColor', false);
- sendToSocket('modify', {
- userid: User.props.id,
- color: text_color
- });
- });
- }
- };
- var SaveSettings = function() {
- localStorage.setItem(localStorageName, JSON.stringify(GetSettings()));
- };
- var LoadSettings = function(storedSettings) {
- if (storedSettings !== null) {
- chatSettings = storedSettings.chatSettings;
- pingSettings = storedSettings.pingSettings;
- }
- PopulateSettings();
- };
- var LoadOldSettings = function() {
- var oldSettings = JSON.parse(localStorage.getItem("chatSettings"));
- if (oldSettings !== null) {
- pingSettings.triggers = oldSettings.pings;
- pingSettings.audioUrl = oldSettings.ping_url;
- pingSettings.color = oldSettings.color;
- pingSettings.highlight = oldSettings.highlight;
- pingSettings.bold = ((oldSettings.flags & 2) > 0);
- pingSettings.italics = ((oldSettings.flags & 4) > 0);
- pingSettings.exact = ((oldSettings.flags & 8) > 0);
- pingSettings.case = ((oldSettings.flags & 16) > 0);
- chatSettings.showNames = ((oldSettings.flags & 64) > 0);
- chatSettings.noIcons = ((oldSettings.flags & 128) > 0);
- chatSettings.session = oldSettings.session;
- chatSettings.strictUrl = oldSettings.strictUrl;
- chatSettings.canCancel = !oldSettings.alwaysJoin;
- chatSettings.favRooms = oldSettings.favRooms;
- chatSettings.autoJoin = oldSettings.autoJoin;
- }
- oldSettings = JSON.parse(localStorage.getItem("lastSession"));
- if (oldSettings !== null) {
- chatSettings.roomSession = oldSettings;
- }
- SaveSettings();
- PopulateSettings();
- };
- var DeleteSettings = function() {
- localStorage.removeItem(localStorageName);
- pingSettings = {
- 'triggers': [],
- 'audioUrl': 'http://chat.rphaven.com/sounds/boop.mp3',
- 'color': '#000',
- 'highlight': '#FFA',
- 'bold': false,
- 'italics': false,
- 'exact': false,
- 'case': false,
- };
- chatSettings = {
- 'showNames': true,
- 'noIcons': false,
- 'strictUrl': false,
- 'canCancel': false,
- 'autoJoin': false,
- 'session': false,
- 'favRooms': [],
- 'RoomSession': [],
- };
- PopulateSettings();
- };
- var PopulateSettings = function() {
- ClearUsersDropLists('favUserList');
- $('#pingNames').val(pingSettings.triggers);
- $('#pingURL').val(pingSettings.audioUrl);
- $('#pingTextColor').val(pingSettings.color);
- $('#pingHighlightColor').val(pingSettings.highlight);
- $('input#pingBoldEnable').prop("checked", pingSettings.bold);
- $('input#pingItalicsEnable').prop("checked", pingSettings.italics);
- $('input#pingExactMatch').prop("checked", pingSettings.exact);
- $('input#pingCaseSense').prop("checked", pingSettings.case);
- $('input#favEnable').prop("checked", chatSettings.autoJoin);
- $('input#showUsername').prop("checked", chatSettings.showNames);
- $('inputimgIconDisable').prop("checked", chatSettings.noIcons);
- $('#roomSessioning').prop("checked", chatSettings.session);
- $('#canCancelJoining').prop("checked", chatSettings.canCancel);
- $('#strictUrl').prop("checked", chatSettings.strictUrl);
- for (var i = 0; i < chatSettings.favRooms.length; i++) {
- var favRoomObj = chatSettings.favRooms[i];
- $('#favRoomsList').append(
- '<option value="' + favRoomObj._id + '">' +
- favRoomObj.user + ": " + favRoomObj.room + '</option>'
- );
- }
- if (chatSettings.favRooms.length >= 10) {
- $('#favAdd').text("Favorites Full");
- $('#favAdd')[0].disabled = true;
- }
- pingSound = new Audio(pingSettings.audioUrl);
- if (chatSettings.session) {
- updateSessionTimer = setInterval(updateSession, 30 * 1000);
- }
- };
- /**************************************************************************
- * @brief Processes account events.
- *
- * @param account - Data blob countaining the user's account.
- **************************************************************************/
- var ProcessAccountEvt = function(account) {
- var users = account.users;
- ClearUsersDropLists('userColorDroplist');
- for (i = 0; i < users.length; i++) {
- AddUserToDroplist(users[i], 'userColorDroplist');
- AddUserToDroplist(users[i], 'favUserList');
- }
- };
- var GetSettings = function() {
- return {
- 'chatSettings': chatSettings,
- 'pingSettings': pingSettings
- };
- };
- return {
- init: function() {
- var autoJoining = false;
- var hasRooms = false;
- settingsDialog.chat = CreateDialog('#chatSettingsHeader', '#chatSettingsForm');
- settingsDialog.chat.button.click({
- dialog: settingsDialog.chat
- }, DialogToggle);
- $('#pingNames').blur(function() {
- var triggers = $('#pingNames').val().replace('\n', '').replace('\r', '');
- pingSettings.triggers = triggers;
- SaveSettings();
- });
- $('#pingURL').blur(function() {
- if (ValidateSetting('pingURL', 'url')) {
- pingSettings.audioUrl = GetInput('pingURL');
- SaveSettings();
- }
- });
- $('#pingTextColor').blur(function() {
- if (ValidateSetting('pingTextColor', 'color')) {
- pingSettings.color = GetInput('pingTextColor');
- SaveSettings();
- }
- });
- $('#pingHighlightColor').blur(function() {
- if (ValidateSetting('pingHighlightColor', 'color')) {
- pingSettings.highlight = GetInput('pingHighlightColor');
- SaveSettings();
- }
- });
- $('#pingBoldEnable').change(function() {
- pingSettings.bold = GetCheckBox('pingBoldEnable');
- SaveSettings();
- });
- $('#pingItalicsEnable').change(function() {
- pingSettings.italics = GetCheckBox('pingItalicsEnable');
- SaveSettings();
- });
- $('#pingExactMatch').change(function() {
- pingSettings.exact = GetCheckBox('pingExactMatch');
- SaveSettings();
- });
- $('#pingCaseSense').change(function() {
- pingSettings.case = GetCheckBox('pingCaseSense');
- SaveSettings();
- });
- $('#showUsername').change(function() {
- chatSettings.showNames = GetCheckBox('showUsername');
- SaveSettings();
- });
- $('#imgIconDisable').change(function() {
- chatSettings.noIcons = GetCheckBox('imgIconDisable');
- SaveSettings();
- });
- $('#favEnable').click(function() {
- chatSettings.autoJoin = GetCheckBox('favEnable');
- SaveSettings();
- });
- $('#roomSessioning').click(function() {
- chatSettings.session = GetCheckBox('roomSessioning');
- if (chatSettings.session) {
- updateSessionTimer = setInterval(updateSession, 30 * 1000);
- } else {
- clearTimeout(updateSessionTimer);
- }
- SaveSettings();
- });
- $('#canCancelJoining').click(function() {
- chatSettings.canCancel = GetCheckBox('canCancelJoining');
- SaveSettings();
- });
- $('#strictUrl').click(function() {
- chatSettings.strictUrl = GetCheckBox('strictUrl');
- SaveSettings();
- });
- $('#favAdd').click(function() {
- AddFavoriteRoom();
- SaveSettings();
- });
- $('#favRemove').click(function() {
- RemoveFavoriteRoom();
- SaveSettings();
- });
- $('#userNameTextColorButton').click(function() {
- ChangeTextColor();
- });
- $('#chatHistory').change(function() {
- rph.setSetting('maxHistory', parseInt($(this).val()));
- });
- if (JSON.parse(localStorage.getItem(localStorageName))) {
- LoadSettings(JSON.parse(localStorage.getItem(localStorageName)));
- } else {
- LoadOldSettings();
- }
- chatSocket.on('confirm-room-join', function(data) {
- roomSetup(data);
- });
- chatSocket.on('user-kicked', function(data) {
- for (var i = 0; i < account.users.length; i++) {
- if (data.targetid == account.users[i]) {
- $('<div class="inner"><p>You were kicked from ' +
- data.room + '.<br />' + ' Reason: ' + data.msg +
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement