User:Lady Furude/chat.js

/* FucodeLogger.js is an advanced script for logging the chat and private messages. * Contains several features, such as copying the logs or downloading them with a * special chosen filename. In other words, whatever you could wish for. * Authors: Lady Furude, KockaAdmiralac * * Thanks to KockaAdmiralac for help with finding appropriate methods, giving the * object that solved the difficulty of logging the messages, for testing the code with * me in his personal wiki, allowing to keep it there and suggesting Download feature. * Thanks to Speedit for help with making a button and creating an object~ * * If you've got a suggestion or found a bug, contact Lady Furude! */

$(function {   "use strict";    // This array is going to contain the messages of the main chat    var loggedMsg = [];    function getTime(c) {        var year = c.getFullYear;        var month = String(c.getMonth + 1).padStart(2, 0);        var day = c.getDate.toString.padStart(2, 0);        var hour = c.getHours.toString.padStart(2, 0);        var minute = c.getMinutes.toString.padStart(2, 0);        var second = c.getSeconds.toString.padStart(2, 0);        return "[" + year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second + "] ";    }    // Logging the main chat    // Warning: Doesn't include messages sent before user's arrival.    ["chat:add", "join", "part", "logout", "kick", "ban"].forEach(function(e) { mainRoom.socket.bind(e, function(a) {           var loggedTime = getTime(new Date);            var data = JSON.parse(a.data);            var joinLogged = loggedTime + data.attrs.name + " " + "has joined the chat";            var partLogged = loggedTime + data.attrs.name + " " + "has left the chat";            var logoutLogged = loggedTime + data.attrs.name + " " + "has closed the chat window";            var kickLogged = loggedTime + data.attrs.kickedUserName + " " + "has been kicked by" + " " + data.attrs.moderatorName;            var banLogged = loggedTime + data.attrs.kickedUserName + " " + "has been banned by" + " " + data.attrs.moderatorName;            if (e == "chat:add") {                data.attrs.text.split("\n").forEach(function(line) { loggedMsg.push(loggedTime + "<" + data.attrs.name + "> " + line); });           }            var logged = (function { switch(e) { case "join": return joinLogged; case "part": return partLogged; case "logout": return logoutLogged; case "kick": return kickLogged; case "ban": return banLogged; }           });            if (e !== "chat:add") loggedMsg.push(logged);        }); });   var FucodeLogger = {        logged: [],        logActiveRoom: function {            if (mainRoom.activeRoom == "main" || mainRoom.activeRoom === null) {                // Pushing all that was logged by IIFE above                for (var e = 0; e < loggedMsg.length; e++) {                    this.logged.push(loggedMsg[e]);                }            } else {                // Otherwise, logging messages of a private room and format them                var msgObj = window.mainRoom.chats.privates[mainRoom.activeRoom].model.chats._byCid;                for (var i in msgObj) {                    msgObj[i]._previousAttributes.text.split("\n").forEach(function(line) { this.logged.push(getTime(new Date(msgObj[i]._previousAttributes.timeStamp)) + "<" + msgObj[i]._previousAttributes.name + "> " + line); }, this);               }            }        },        createText: function {            // Creating text for a future modal            var preContent = "";            for (var c = 0; c < this.logged.length; c++) {                // Placing the last message of logs                if (c + 1 == this.logged.length) preContent += this.logged[c];                else { preContent += this.logged[c] + "\n"; }            }            return $(" ", { id: "FucodeLoggerContent", text: preContent, });       },        copyLogs: function {            document.querySelector("#FucodeLoggerCopy").addEventListener("click", function { // Double-click: the copy feature works at the second click, for some reason. $("#FucodeLoggerCopy").click; var range = document.createRange; range.selectNode(document.querySelector("#FucodeLoggerContent")); window.getSelection.addRange(range); try { document.execCommand("copy"); if (!document.getElementById("FucodeLoggerCopied")) { $(".modalContent").append($(" ", { id: "FucodeLoggerCopied", text: "Text is copied!" }));                   }                } catch(err) { // If it's not copied, look into console console.log("Whoops, unable to copy.\nMaybe switch to a normal browser?.."); }               window.getSelection.removeAllRanges; });       },        clickToDownloadLogs: function {            $("#FucodeLoggerExecuteDl").click(function { if (!document.getElementById("FucodeLoggerLinkDl")) { $("#FucodeLoggerExecuteDl").text(""); $("#FucodeLoggerExecuteDl").append($("", { id: "FucodeLoggerLinkDl", download: (function {                           var filename = $("#FucodeLoggerSetFilename").val + ".txt";                            return filename;                        }), href: URL.createObjectURL(new Blob([$("#FucodeLoggerContent").text], {type: 'octet/stream'})), text: "Download logs" }).css({ color: "#FFF", "text-decoration": "none" }));               }            });        },        downloadLogs: function {            $("#FucodeLoggerDl").click($.proxy(function {                if (!document.getElementById("FucodeLoggerSetDownload")) {                    $(".modalContent").append($(" ", {                        id: "FucodeLoggerSetDownload"                    }));                    $("#FucodeLoggerSetDownload").append([$(" ", {                        id: "FucodeLoggerFilenameNotif",                        text: "Type the filename:"                    }), $(" ", {                        id: "FucodeLoggerSetFilename",                        type: "text"                    }), $(" ", {                        id: "FucodeLoggerExecuteDl",                        name: "setFilename",                        text: "Set the filename"                    })]);                    // Allowing an user to press Enter instead of clicking the button $("#FucodeLoggerSetFilename").keyup(function(event) {                       if (event.keyCode === 13) $("#FucodeLoggerExecuteDl").click;                    }); this.clickToDownloadLogs; }           }, this)); },       createModal: function { $.showCustomModal("The result of logging the chat", $(" ").append([this.createText, $(" ", {                   id: "FucodeLoggerCopy",                    text: "Copy"                }), $(" ", {                   id: "FucodeLoggerDl",                    text: "Download"                }) ]).html, {               id: "FucodeLoggerResult",            }).css({                width: "750px",                overflow: "auto",                height: "550px",                "margin-left": "-388px"            }); this.copyLogs; this.downloadLogs; },   };

// Creating a button mw.hook("dev.chat").add(function(chat) {       FucodeLogger.button = new chat.Button({ name: "ChatLog", attr: { text: "Log", click: function { FucodeLogger.logged = []; FucodeLogger.logActiveRoom; FucodeLogger.createModal; }           }        });    });

// An incredible library made by Speedit, thanks! importArticle({       type: "script",        article: "u:dev:Chat-js.js"    }); });

$(function {   var config = mw.config.get([ 'wgArticlePath', 'wgCanonicalSpecialPageName', 'wgUserLanguage' ]);   if (config.wgCanonicalSpecialPageName !== 'Chat' || $('#userpage').length > 0) {        return;    }    var i18n = {        en: 'User Page',        be: 'Прафайл',        de: 'Benutzerseite',        es: 'Página de usuario',        pl: 'Strona użytkownika',        pt: 'Página de utilizador',        'pt-br': 'Página de usuário',        ru: 'Профайл',        sr: 'Профил',        'sr-el': 'Profil',        uk: 'Профайл',        sv: 'Användarsida'    },    alias = $.fn.show;    $.fn.show = function {        alias.apply(this, arguments);        $('.contribs')            .clone            .addClass('userpage')            .removeClass('contribs')            .prependTo('.regular-actions');        $('.userpage a').attr({ id: 'userpage', target: '_blank', href: config.wgArticlePath .replace('$1', 'User:' + $('#UserStatsMenu .info ul .username')                   .text                    .replace(/ /g, '_')                ) });       if($('.userpage svg').exists) {            $('.userpage svg')[0].setAttribute('viewBox','0 0 24 24');            $('.userpage path').attr('d', 'M12 14c3.309 0 6-2.691 6-6V6c0-3.309-2.691-6-6-6S6 2.691 6 6v2c0 3.309 2.691 6 6 6zm5 2H7c-3.86 0-7 3.14-7 7a1 1 0 0 0 1 1h22a1 1 0 0 0 1-1c0-3.86-3.14-7-7-7z');            $('.userpage .label').text(i18n[config.wgUserLanguage] || i18n[config.wgUserLanguage.split('-')[0]] || i18n.en);        }    }; });