User:Lady Furude/chat.js

/* console.log("Wanna form a contract with me?"); * * FucodeLogger.js is an advanced script for logging the chat and private messages. * Contains several features, such as copying the logs or downloafing them with a * special chosen filename. In other words, whatever you could wish for. * Author: Lady Furude, KockaAdmiralac * * Thanks to Speedit for help with making a button and creating an object~ * Thanks to KockaAdmiralac for help with finding appropriate functions, 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. * * If you've got a wish you'd like to pay for with your soul, contact Lady Furude! * * Don't forget to form a contract with Kyuubey and become a Magical Girl! ~ $(function {   "use strict";    // This array is going to contain all the messages    var loggedMsg = [];    // Function for outputting time parameters    function getTime(c) {        var time = c;        var year = c.getFullYear;        var month = c.getMonth + 1;        var day = c.getDate;        var hour = c.getHours;        var minute = c.getMinutes;        var second = c.getSeconds;        // Formatting the time's data        month = month.toString.padStart(2, 0);        day = day.toString.padStart(2, 0);        hour = hour.toString.padStart(2, 0);        minute = minute.toString.padStart(2, 0);        second = second.toString.padStart(2, 0);        // Returning the part with timestamp of a message        return "[" + year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second + "] ";    }    // Log everything by event    (function { // Describing actions that need to be logged var actions = ["chat:add", "join", "logout", "kick", "ban"]; // Defining the appearance of system messages var FucodeLoggerActionsLook = FucodeLoggerActionsLook ? FucodeLoggerActionsLook : ["has joined the chat", "has left the chat", "has been kicked by", "has been banned by"]; actions.forEach(function(t) {           mainRoom.socket.bind(t, function(a) { var loggedTime = getTime(new Date); // Getting the content data var data = JSON.parse(a.data); var nickname = data.attrs.name; var text = data.attrs.text; // For kicks and bans var modName = data.attrs.moderatorName; var kickedName = data.attrs.kickedUserName; // Future messages var logged; var msgLogged; // This one is                var joinLogged = loggedTime + nickname + " " + FucodeLoggerActionsLook[0]; var partLogged = loggedTime + nickname + " " + FucodeLoggerActionsLook[1]; var kickLogged = loggedTime + kickedName + " " + FucodeLoggerActionsLook[2] + " " + modName; var banLogged = loggedTime + kickedName + " " + FucodeLoggerActionsLook[3] + " " + modName; // Choosing the format depending on the event type if (t == "join") logged = joinLogged; else if (t == "chat:add") { // Splitting the text if it has a new line if (text.indexOf("\n") !== -1) { text.split("\n").forEach(function(line) {                           msgLogged = loggedTime + "<" + nickname + "> " + line;                            logged = msgLogged;                            loggedMsg.push(logged);                        }); } else { // Simply format the message if it has one single line msgLogged = loggedTime + "<" + nickname + "> " + text; logged = msgLogged; loggedMsg.push(logged); }               }                else if (t == "logout") logged = partLogged; else if (t == "kick") logged = kickLogged; else if (t == "ban") logged = banLogged; // Putting the event message into the array if (t !== "chat:add") loggedMsg.push(logged); });       }, this); return loggedMsg; });   var FucodeLogger = {        // This array contains the logged messages        logged: [],        // Formatting the private logs        formatPM: function(messages, messagesObj) {            messages.forEach(function(a) { var nickname = messagesObj[a]._previousAttributes.name; var content = messagesObj[a]._previousAttributes.text; // Declaring the format of logs var loggedTime = getTime(new Date(messagesObj[a]._previousAttributes.timeStamp)); var privateMsg = loggedTime + "<" + nickname + "> " + content; this.logged.push(privateMsg); }, this);       },        // Logging the currently opened room        clickLog: function {            // This variable contains the number of iteration when the main chat gets logged            var amount = 0;            if (mainRoom.activeRoom == "main" || mainRoom.activeRoom === null) {                loggedMsg.forEach(function(a) { this.logged.push(loggedMsg[amount]); amount++; }, this);           } else {                var messagesObj = window.mainRoom.chats.privates[mainRoom.activeRoom].model.chats._byCid;                var messages = Object.keys(messagesObj);                this.formatPM(messages, messagesObj);            }        },        // Creating paragraphs for a future modal        createText: function {            var preContent = "";            for (var c = 0; c < this.logged.length; c++) {                preContent += this.logged[c] + '\n';            }            var textDiv = $(" ", { id: "FucodeLoggerContent", text: preContent, });           return textDiv;        },        // A modal window that contains the logged stuff        modal: function {            var modalContent = [this.createText,                $(" ", { id: "FucodeLoggerCopy", text: "Copy" }),               $(" ", {                    id: "FucodeLoggerDl", text: "Download" })           ];            $.showCustomModal("The result of logging the chat", $(" ").append(modalContent).html, {               id: "FucodeLoggerResult", }).css({ width: "750px", overflow: "auto", height: "550px", "margin-left": "-388px" });           // Copy button feature: copy the logs with one single click! (Or two of them :P)            var FucodeLoggerCopy = document.querySelector("#FucodeLoggerCopy");            FucodeLoggerCopy.addEventListener("click", function(event) { // Double-click: the copy feature works at the second click, for some reason. $("#FucodeLoggerCopy").click; var content = document.querySelector("#FucodeLoggerContent"); var range = document.createRange; range.selectNode(content); window.getSelection.addRange(range); try { var successful = document.execCommand("copy"); // Shows that logs are copied 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"); }               window.getSelection.removeAllRanges; });           // Download feature: choose the filename and keep the logs on your side easily!            var blob = new Blob([$("#FucodeLoggerContent").text], {type: 'octet/stream'});            // Things that execute when you choose download option            $("#FucodeLoggerDl").click(function { if (!document.getElementById("FucodeLoggerSetDownload")) { $(".modalContent").append($(" ", { id: "FucodeLoggerSetDownload" }));                   var setDlContent = [$(" ", {                        id: "FucodeLoggerFilenameNotif",                        text: "Type the filename:"                    }), $(" ", {                        id: "FucodeLoggerSetFilename",                        type: "text"                    }), $(" ", {                        id: "FucodeLoggerExecuteDl",                        name: "setFilename",                        text: "Set the filename"                    })]; $("#FucodeLoggerSetDownload").append(setDlContent); // Function for defining the filename var filename; function setFilename { filename = $("#FucodeLoggerSetFilename").val + ".txt"; }                   $("#FucodeLoggerExecuteDl").click(function {                        setFilename;                        if (!document.getElementById("FucodeLoggerLinkDl")) {                            $("#FucodeLoggerExecuteDl").text("");                            // The link that starts downloading the logs                            $("#FucodeLoggerExecuteDl").append($("", {                                id: "FucodeLoggerLinkDl",                                download: filename,                                href: URL.createObjectURL(blob),                                text: "Download logs"                            }).css({                                color: "#FFF",                                "text-decoration": "none"                            }));                        }                    }); // Allows an user to press Enter instead of clicking the button $("#FucodeLoggerSetFilename").keyup(function(event) {                       if (event.keyCode === 13) {                            $("#FucodeLoggerExecuteDl").click;                        }                    }); }           });        }    };    // 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.clickLog;                    FucodeLogger.modal;                }            }        }); });   // Thanks to Speedy-kun for this incredible library C:    importArticle({ type: "script", article: "u:dev:Chat-js.js" }); });