Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ==UserScript==
- // @name RuMinePP
- // @namespace https://ru-minecraft.ru/
- // @version 1.3.0
- // @description suka
- // @author (You)
- // @match https://ru-minecraft.ru/*
- // @grant none
- // ==/UserScript==
- window.RMPPVersion = "v1.3.0-beta";
- (function() {
- const code = main.toString().slice(17, -1);
- let script = document.createElement("script");
- script.appendChild(document.createTextNode(code));
- document.body.appendChild(script);
- Modules.load();
- })();
- function main() {
- let DB = {
- _queue: [],
- init: function(cb) {
- DB._open = indexedDB.open("RuMinePP_DB", 1);
- DB._open.onsuccess = function() {
- DB.db = DB._open.result;
- }
- DB._open.onupgradeneeded = function() {
- DB.db = DB._open.result;
- let store = DB.db.createObjectStore("MessageHistory", { keyPath: "id", autoIncrement: true });
- store.createIndex("messageId", "messageId", { unique: false });
- store.createIndex("content", "content", { unique: false });
- }
- },
- processQueue: function() {
- let tx = DB.db.transaction("MessageHistory", "readwrite");
- let store = tx.objectStore("MessageHistory");
- let el = null;
- while (el = DB._queue.shift()) {
- store.put({
- messageId: el[0],
- content: el[1]
- });
- }
- },
- getMessageHistory: function(id, cb) {
- let result = [];
- DB.db
- .transaction("MessageHistory", "readonly")
- .objectStore("MessageHistory")
- .openCursor().onsuccess = function(event) {
- let cursor = event.target.result;
- if (cursor) {
- if (cursor.value.messageId === id)
- result.push(cursor.value.content);
- cursor.continue();
- } else {
- cb(result);
- }
- }
- },
- pushQueue(id, content) {
- DB._queue.push([id, content]);
- }
- };
- let HTML = {
- _pages: {},
- register: function(name, content) {
- HTML._pages[name] = encodeURIComponent(content);
- },
- get: function(name) {
- return decodeURIComponent(HTML._pages[name]);
- }
- };
- const Injector = {
- before: function(fn, inj) {
- let self = this;
- return function() {
- inj.apply(self, arguments);
- return fn.apply(self, arguments);
- }
- },
- after: function(fn, inj) {
- let self = this;
- return function() {
- const res = fn.apply(self, arguments);
- inj.apply(self, arguments);
- return res;
- }
- }
- };
- const Modules = {
- _modules: [],
- registerModule: function(name, fn) {
- Modules._modules.push({ name: name, fn: fn });
- },
- load: function() {
- if (window.location.href === "https://ru-minecraft.ru/index.php?action=logout") return;
- if (localStorage.getItem("_logout") === "do") {
- document.write("Вхожу в аккаунт...");
- localStorage.setItem("_logout", "refresh");
- return setTimeout(() => window.location.href = "https://ru-minecraft.ru/", 1000);
- }
- if (localStorage.getItem("_logout") === "refresh") {
- localStorage.setItem("_logout", "1");
- Modules._modules.find(e => e.name === "MultiAccount").fn();
- return window.loginMultiaccount();
- }
- if (!$(".loginset")[1]) return;
- if (window.location.href.startsWith("https://ru-minecraft.ru/out?")) return;
- try {
- Notification.requestPermission();
- Modules._modules.forEach(function(m) {
- console.log(m.name + " enabled? " + (localStorage.getItem(m.name + "_enabled") !== "0"));
- if (localStorage.getItem(m.name + "_enabled") !== "0") m.fn();
- });
- } catch (e) {
- document.write("<pre><center><h1>Невозможно инициализировать RuMine++</h1></center><br><br>");
- document.write(e.stack + "");
- document.write("<br><br><i>" + navigator.userAgent + "</i></pre>");
- }
- }
- };
- const PageAPI = {
- getForumMessages: function(content) {
- return Array.from($("li.msg", content ? $(content) : undefined)).slice(0, -1);
- },
- getForumPage: function(content) {
- try {
- return ~~$(".txt_info_pages", content ? $(content) : undefined)[1].innerHTML.split(" ").pop();
- } catch(e) {
- return 1;
- }
- },
- appendForumMessage: function(el) {
- $(".contentBoxTopicMessageList")[0].insertBefore(el, document.getElementById("addNewMsg"));
- },
- appendHistoryBtn: function(msg) {
- let el = document.createElement("a");
- el.href = "#";
- el.onclick = function() {
- editHistory(PageAPI.getMessageId(msg));
- return false;
- }
- el.innerHTML = "История редактирования";
- let msgEl = $(".msgIControl", $(msg))[0];
- if (!msgEl) return;
- msgEl.appendChild(el);
- },
- isForumTopic: function() {
- return window.location.href.startsWith("https://ru-minecraft.ru/forum/showtopic-");
- },
- getMessageInfo: function(msg) {
- const username = $(".autorInfo > p > a", $(msg))[0].innerHTML;
- const avatar = $(".avatar > a > img", $(msg))[0].src;
- const text = $("div[id^='MsgTextBox-']", $(msg))[0].innerText;
- return {
- username: username,
- avatar: avatar,
- text: text
- }
- },
- getMessageId: function(msg) {
- let topic = window.location.href.slice("https://ru-minecraft.ru/forum/showtopic-".length);
- topic = topic.slice(0, topic.indexOf("/"));
- const msgId = $(".getMessageLinck", $(msg)).text().slice(1);
- return topic + "_" + msgId;
- },
- getMessageHTML: function(msg) {
- let html = $("div[id^='MsgTextBox-']", $(msg)).html().trim();
- return html.slice(0, html.indexOf('<div class="likeBox-'));
- },
- insertCustomEmoticon: function(url) {
- doInsert("[img]" + url + "[/img]\n\n", "", false);
- $("#bullet_energy_emos").dialog("close");
- window.ie_range_cache = null;
- },
- getOnline: function(content) {
- return Array.from(
- $("span",
- $(
- $(".userClin", content ? $(content) : undefined)[0]
- )
- ).not("[style='color:#9CA1A5']")
- ).map(e => e.innerText);
- },
- getUserInfo: function(username, cb) {
- // TODO: implement other
- $.ajax({
- url: "https://ru-minecraft.ru/engine/ajax/profile.php?name=" + username + "&skin=ru-minecraft",
- success: function(content) {
- const e = $(content);
- const avatar = $("img", e)[0].src;
- cb({
- avatar: avatar
- });
- }
- });
- },
- login: function(login, password, cb) {
- $.ajax({
- method: "POST",
- url: "https://ru-minecraft.ru/",
- data: {
- login_name: login,
- login_password: password,
- login: "submit"
- },
- success: function(body, status, xhr) {
- cb(true);
- },
- error: function() {
- cb(false);
- }
- });
- },
- popup: function (title, body, buttons) {
- $("#dlepopup").remove();
- $("body").append("<div id='dlepopup' title='" + title + "' style='display:none'>" + body + "</div>");
- $('#dlepopup').dialog({
- autoOpen: true,
- width: 550,
- dialogClass: "modalfixed",
- buttons: buttons
- });
- },
- openWithPost: function(url, data) {
- $("#Form").remove();
- let form = document.createElement("form");
- let target = "w" + Math.random();
- form.setAttribute("id", "Form");
- form.setAttribute("method", "POST");
- form.setAttribute("action", url);
- form.setAttribute("target", target);
- Object.keys(data).forEach(function(key) {
- let input = document.createElement("input");
- input.setAttribute("type", "hidden");
- input.setAttribute("name", key);
- input.setAttribute("value", data[key]);
- form.appendChild(input);
- });
- document.body.appendChild(form);
- window.open("", target, 'height=900,width=1250,resizable=0,scrollbars=1');
- form.submit();
- }
- };
- Modules.registerModule("CustomEmoticons", function() {
- if (!PageAPI.isForumTopic()) return;
- if (!localStorage.getItem("emoticons_urls")) localStorage.setItem("emoticons_urls", "");
- const emoticons = localStorage.getItem("emoticons_urls").split("\n");
- window.ins_emo = Injector.after(window.ins_emo, function() {
- let container = $("#bullet_energy_emos > div > table > tbody")[0];
- let text = document.createElement("tr");
- text.innerHTML = "= Кастомные =";
- let textend = document.createElement("tr");
- textend.innerHTML = "= Основные =";
- container.insertBefore(text, container.firstChild);
- container.insertBefore(textend, container.children[1]);
- let current = null;
- emoticons.forEach(function(e, i) {
- if (i % 4 === 0) {
- current = document.createElement("tr");
- container.insertBefore(current, textend);
- }
- let el_a = document.createElement("a");
- let el = document.createElement("img");
- let el_td = document.createElement("td");
- el.setAttribute("class", "emoji");
- el.setAttribute("src", e);
- el.setAttribute("width", "64px");
- el_a.setAttribute("onclick", "PageAPI.insertCustomEmoticon('" + e + "'); return false;");
- el_a.setAttribute("href", "#");
- el_td.setAttribute("style", "padding:5px;");
- el_td.setAttribute("align", "center");
- el_a.appendChild(el);
- el_td.appendChild(el_a);
- current.appendChild(el_td);
- });
- });
- });
- Modules.registerModule("EditPreview", function() {
- window.ajax_prep_for_edit = Injector.after(window.ajax_prep_for_edit, function(id, mode) {
- if (mode !== "short") return;
- let button = document.createElement("button");
- let span = document.createElement("span");
- button.setAttribute("type", "button");
- button.setAttribute("class", "ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only");
- button.setAttribute("role", "button");
- button.setAttribute("aria-disabled", "false");
- span.setAttribute("class", "ui-button-text");
- span.innerHTML = "Превью";
- button.appendChild(span);
- button.onclick = function() {
- const title = $("input[id^='edit-title-']")[0].value;
- const shortStory = $("textarea[id^='dleeditnews']")[0].value;
- const fullStory = $("textarea[id^='dleeditfullnews']")[0].value;
- PageAPI.openWithPost("/engine/preview.php",
- {
- "catlist[]":"",
- "title": title,
- "xfield[name]": "",
- "short_story": shortStory,
- "full_story": fullStory,
- "mod": "preview",
- "approve": "1"
- }
- );
- }
- function tryAdd() {
- if (!$(".ui-dialog-buttonset")[0]) return setTimeout(() => tryAdd(), 500);
- $(".ui-dialog-buttonset")[0].appendChild(button)
- }
- tryAdd();
- });
- });
- Modules.registerModule("ForumMessageHistory", function() {
- if (!PageAPI.isForumTopic()) return;
- DB.init();
- // временный костыль
- window._pushHistory = function(msg) {
- if (!DB.db) return setTimeout(() => window._pushHistory(msg), 1000);
- const text = PageAPI.getMessageHTML(msg);
- const id = PageAPI.getMessageId(msg);
- DB.getMessageHistory(id, function(history) {
- if (history[history.length - 1] === text) return;
- DB.pushQueue(id, PageAPI.getMessageHTML(msg));
- });
- }
- PageAPI.appendForumMessage = Injector.before(PageAPI.appendForumMessage, function(msg) {
- window._pushHistory(msg);
- PageAPI.appendHistoryBtn(msg);
- });
- PageAPI.getForumMessages().forEach(function(msg) {
- window._pushHistory(msg);
- PageAPI.appendHistoryBtn(msg);
- });
- window.editHistory = function(id) {
- ShowLoading();
- DB.getMessageHistory(id, function(history) {
- HideLoading();
- history.unshift("");
- PageAPI.popup(
- "История редактирования",
- "<div style='overflow-y: scroll; height:400px;'>" + history.join("<hr>") + "</div>",
- {
- "Ясно": function() {
- $("#dlepopup").remove();
- }
- }
- );
- });
- }
- function tryQueue() {
- if (DB.db) DB.processQueue();
- setTimeout(() => tryQueue(), 1000);
- }
- tryQueue();
- });
- Modules.registerModule("ForumMessagesUpdater", function() {
- if (!PageAPI.isForumTopic()) return;
- Notification.requestPermission();
- let currentPage = null;
- let editing = null;
- function getNewMessages(cb) {
- $.ajax({
- success: function(content) {
- cb({
- messages: PageAPI.getForumMessages(content),
- page: PageAPI.getForumPage(content)
- });
- }
- });
- }
- function tick() {
- const current = PageAPI.getForumMessages();
- getNewMessages(function(actual) {
- if (current.length !== actual.messages.length) {
- actual.messages.slice(current.length).forEach(function(msg) {
- PageAPI.appendForumMessage(msg);
- const info = PageAPI.getMessageInfo(msg);
- let notification = new Notification(info.username, {
- body: info.text,
- icon: info.avatar
- });
- setTimeout(() => notification.close(), 3000);
- });
- }
- current.forEach(function(c, i) {
- if (c.getAttribute("id").endsWith(editing)) return;
- if ($(".EditMsgView", $(c)).text() !== $(".EditMsgView", $(actual.messages[i])).text()) {
- if (window._pushHistory) {
- window._pushHistory(actual.messages[i]);
- PageAPI.appendHistoryBtn(actual.messages[i]);
- }
- $("#" + c.getAttribute("id")).html(actual.messages[i].innerHTML);
- }
- });
- if (currentPage !== null && currentPage !== actual.page) {
- currentPage = actual.page;
- PageAPI.popup("Опа!", "Появилась новая страница!", {
- "Перейти": function() {
- window.location.href = window.location.href.replace("page-" + (actual.page - 1), "page-" + actual.page);
- }
- });
- new Notification("Новая страница!", {
- body: "На форуме появилась новая страница"
- });
- }
- if (currentPage === null) currentPage = actual.page;
- });
- }
- setInterval(() => tick(), 2000);
- // Inject
- window.MsgEdit = Injector.before(window.MsgEdit, (id) => editing = id);
- window.MsgEditSave = Injector.before(window.MsgEditSave, () => editing = null);
- window.MsgEditCancel = Injector.before(window.MsgEditCancel, () => editing = null);
- // Redefine default functions
- window.doAddMessage = function() {
- var a = document.getElementById("message_add_form");
- if (a.text_msg.value == "") {
- Alert_popup(lang[0][29][6], lang[0][23][0]);
- return false
- }
- if (a.recaptcha_response_field) {
- var b = Recaptcha.get_response();
- var c = Recaptcha.get_challenge()
- } else if (a.question) {
- var b = a.question.value;
- var c = a.question_sec.value
- } else {
- var b = "";
- var c = ""
- }
- Ajax_Loading("");
- var d = new Array;
- $("#message_add_form input[class='marker_file_ajax']").each(function(a, b) {
- d.push($(b).val())
- });
- if (forum_cpu) {
- var e = dle_root + forum_path + "/add/" + a.topict_id.value + "/post"
- } else {
- var e = dle_root + "index.php?do=" + forum_path + "&action=newpost&id=" + a.topict_id.value + "¶m=post"
- }
- $.post(e, {
- text_msg: a.text_msg.value,
- topic_id: a.topict_id.value,
- recaptcha_response_field: b,
- recaptcha_challenge_field: c,
- id_file: d
- }, function(b) {
- Ajax_close("");
- if (b.param == 0) {
- Alert_popup(b.data, lang[0][23][0]);
- return false
- }
- setElementForum()
- $("#text_msg").val("");
- }, "json");
- }
- });
- Modules.registerModule("MultiAccount", function() {
- $(".loginname").append(" <a href='#' style='color: #eee; font-size: 12px;' title='Мультиаккаунт' onclick='multiaccount(); return false;'>[+]</a>")
- if (!localStorage.getItem("accounts")) localStorage.setItem("accounts", "[]");
- function getAccounts() {
- return JSON.parse(localStorage.getItem("accounts"));
- }
- function addAccount(login, password) {
- let accounts = getAccounts();
- accounts.push({ login: login, password: password });
- localStorage.setItem("accounts", JSON.stringify(accounts));
- }
- function removeAccount(login) {
- let accounts = getAccounts();
- accounts = accounts.filter(e => e.login !== login);
- localStorage.setItem("accounts", JSON.stringify(accounts));
- }
- window.loginMultiaccount = function(login) {
- if (localStorage.getItem("_logout") !== "1") {
- localStorage.setItem("_logout", "do");
- localStorage.setItem("_queue_login", login);
- return window.location.href = "https://ru-minecraft.ru/index.php?action=logout";
- }
- localStorage.removeItem("_logout");
- document.write("Вхожу в аккаунт (2)...");
- const qlogin = localStorage.getItem("_queue_login");
- const password = getAccounts().find(e => e.login === qlogin).password;
- PageAPI.login(qlogin, password, function(success) {
- if (success) return setTimeout(() => window.location.reload(), 1000);
- PageAPI.popup("Ошибка", "Неверный логин или пароль");
- });
- }
- window.deleteMultiaccount = function(login) {
- removeAccount(login);
- window.requestAnimationFrame(() => window.multiaccount());
- }
- window.addMultiaccount = function() {
- let page = "<div style='display: block; vertical-align: middle; border-bottom: solid #ddd 2px;'>";
- page += "<img style='vertical-align: middle;' src='https://ru-minecraft.ru/templates/ru-minecraft/images/alert.png' />";
- page += "<span style='vertical-align: middle;'>Пароли хранятся локально без какого либо шифрования</span><br>";
- page += "</div><br>";
- // TODO move to html
- page += "<input style='width: 520px; border: none; outline: none; font-size: 16px;' type='text' id='ma-login' placeholder='Логин'><br><br>";
- page += "<input style='width: 520px; border: none; outline: none; font-size: 16px;' type='password' id='ma-password' placeholder='Пароль'>";
- PageAPI.popup("Добавить мультиаккаунт", page, {
- "Отмена": function() {
- window.requestAnimationFrame(() => window.multiaccount());
- },
- "Добавить": function() {
- const login = $("#ma-login").val();
- const password = $("#ma-password").val();
- addAccount(login, password);
- window.requestAnimationFrame(() => window.multiaccount());
- }
- });
- }
- window.multiaccount = function() {
- let page = "<button onclick='addMultiaccount();'>Добавить</button><hr>";
- getAccounts().forEach(function(account, i) {
- page += "<b>" + account.login + "</b> | ";
- page += "<button onclick=\"loginMultiaccount('" + account.login + "');\">Войти</button> |";
- page += "<button onclick=\"deleteMultiaccount('" + account.login + "');\">Удалить</button>";
- page += "<br>";
- });
- PageAPI.popup("Мультиаккаунт", page, {
- "Закрыть": function() {
- $("#dlepopup").remove();
- }
- });
- }
- });
- Modules.registerModule("OnlineNotification", function() {
- if (!window.location.href.startsWith("https://ru-minecraft.ru/forum/")) return;
- $.getScript("https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js");
- Notification.requestPermission();
- let current = PageAPI.getOnline();
- function tick() {
- $.ajax({
- success: function(body) {
- const actual = PageAPI.getOnline(body);
- const joined = _.difference(actual, current);
- joined.forEach(function(username) {
- PageAPI.getUserInfo(username, function(info) {
- let notification = new Notification(username + " онлайн", {
- icon: info.avatar
- });
- setTimeout(() => notification.close(), 2000);
- });
- });
- current = actual;
- }
- });
- }
- setInterval(() => tick(), 4000);
- });
- Modules.registerModule("ReleaseChecker", function() {
- if (localStorage.getItem("lastChecked") === null || localStorage.getItem("lastChecked") + 600000 < Date.now()) {
- $.ajax({
- url: "https://api.github.com/repos/yioyo3/ruminepp/releases",
- success: function(result) {
- if (result[0].tag_name === RMPPVersion || result[0].tag_name === localStorage.getItem("lastVersion"))
- return;
- localStorage.setItem("lastVersion", result[0].tag_name);
- localStorage.setItem("lastChecked", Date.now());
- PageAPI.popup("Новая версия RuMine++", "Появилась новая версия RuMine++ <b>" + result[0].tag_name + "</b>", {
- "Подробнее": function() {
- window.location.href = "https://github.com/yioyo3/ruminepp/releases";
- }
- });
- }
- });
- }
- });
- Modules.registerModule("RuMinePP", function() {
- const container = $(".loginset")[1];
- let rmppSettings = document.createElement("a");
- rmppSettings.href = "#";
- rmppSettings.onclick = function() {
- PageAPI.popup("Настройки RuMine++", HTML.get("settings.html"), {
- "Применить": function() {
- Array.from($(".rmppSetting")).forEach(e => localStorage.setItem(e.getAttribute("id") + "_enabled", e.checked ? "1" : "0"));
- localStorage.setItem("emoticons_urls", $("#CustomEmoticons_urls").val());
- window.location.reload();
- }
- });
- $("#CustomEmoticons_urls").val(localStorage.getItem("emoticons_urls") || "");
- $("#CustomEmoticons_urls").prop("disabled", localStorage.getItem("CustomEmoticons_enabled") === "0");
- Array.from($(".rmppSetting")).forEach(e => e.checked = localStorage.getItem(e.getAttribute("id") + "_enabled") !== "0");
- return false;
- }
- rmppSettings.innerHTML = "Настройки RuMine++";
- container.appendChild(rmppSettings);
- });
- HTML.register("settings.html", `<style>.ruminepp_logo{width:30%;position:relative;display:block;margin:0 auto;top:5px;opacity:.5}#checkboxes{width:100%;padding:0 30px}hr{border:2px dashed #82c3f3}input{opacity:0;z-index:-999}label{position:relative;display:inline-block;text-align:left;cursor:pointer;font-weight:500;padding:0 0 0 30px;height:20px;width:300px;float:left}.true_checkbox{width:15px;height:15px;position:relative;border:3px solid #71a9d2;border-radius:5px;margin:-21px 0;transition:border ease .4s;overflow:hidden;cursor:pointer}.fill{display:block;position:absolute;width:35px;height:35px;background:#9bd4ff;margin:15px 0 0 -30px;transform:rotate(45deg);transition:margin ease .5s}input:not(checked)+.true_checkbox{border:1.5px solid rgba(113,169,210,.3)}input:checked+.true_checkbox{border:3px solid #71a9d2}input:not(checked)+.true_checkbox>.fill{margin:15px 0 0 -30px}input:checked+.true_checkbox>.fill{margin:-7px}.more{text-decoration:none;color:#71a9d2;font-size:10px;transition:color ease .2s,visibility .5s,opacity .5s ease}.more:hover{text-decoration:none;color:#71a9d2}#spoiler{display:none;opacity:1;font-family:Consolas,'Droid Sans',Monaco,Lucida,sans-serif;transition:display ease .5s,opacity ease .5s}#spoiler textarea{border:1px dashed #71a9d2}.CustomEmoticons{width:155px}#CustomEmoticons_urls{outline:0}</style><img class=ruminepp_logo src=https://i.imgur.com/F9dywXu.png><br><hr style="border:.5px solid #91cdcf;width:100%"><span style="display:block;font-family:'Segoe UI',Arial,sans-serif;font-size:14px;user-select:none;background:url(https://i.imgur.com/ddIqSYY.png) repeat fixed center center"><div id=checkboxes><br><input class=rmppSetting id=RuMinePP type=checkbox><div class=true_checkbox><span class=fill></span></div><label for=RuMinePP>Включить RuMine++ (не убирать)</label><br><br><input class=rmppSetting id=ReleaseChecker type=checkbox><div class=true_checkbox><span class=fill></span></div><label for=ReleaseChecker>Проверять наличие новых релизов</label><br><br><input class=rmppSetting id=ForumMessagesUpdater type=checkbox><div class=true_checkbox><span class=fill></span></div><label for=ForumMessagesUpdater>Автообновление сообщений на форуме</label><br><br><input class=rmppSetting id=ForumMessageHistory type=checkbox><div class=true_checkbox><span class=fill></span></div><label for=ForumMessageHistory style=width:330px;font-size:13px>Сохранять историю редактирования сообщений</label><br><br><input class=rmppSetting id=CustomEmoticons type=checkbox><div class=true_checkbox><span class=fill></span></div><label for=CustomEmoticons class=CustomEmoticons>Кастомные эмотиконы</label><a class=more href="javascript:ShowOrHide('spoiler')">▼</a><div id=spoiler><br><textarea id=CustomEmoticons_urls placeholder="Ссылки на картинки для эмотиконов (с новой строки)"style=height:30px;width:450px;resize:none></textarea></div></div><br></span><script>$("#CustomEmoticons").click(function(){$(this).is(":checked")?($(".more").css({opacity:"1",visibility:"visible"}),$("#spoiler").css({opacity:"1",display:"none"})):($(".more").css({opacity:"0",visibility:"hidden"}),$("#spoiler").css({opacity:"1",display:"none"}))})</script>`)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement