Alive6ftUnder / Kirara News Translation Applier

// ==UserScript==
// @name         Kirara News Translation Applier
// @namespace    https://openuserjs.org/users/Alive6ftUnder
// @updateURL    https://openuserjs.org/meta/Alive6ftUnder/Kirara_News_Translation_Applier.meta.js
// @version      0.1
// @description  Fetches the translations of kirara news items
// @author       Some girl
// @copyright    2018, Alive6ftUnder (https://openuserjs.org/users/Alive6ftUnder)
// @license      MIT
// @match        https://krr-prd-web.star-api.com/news/*
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';

    const TL_MAP_URL = "https://pastebin.com/raw/GHqSQvgr";

    var xhttp;
    var tlURL;
    var tlButton;
    var title;

    if (/\d{4,}/.test(window.location.href)) {
        var style = document.createElement('style');
        style.innerHTML = "div.newsType { display: inline-block; }" +
                          "div.newsType.translate { float: right; }"+
                          "div.newsType.translate.check { background-image: url(https://i.imgur.com/9a1OVfI.png); }"+
                          "div.newsType.translate.fetch { background-image: url(https://i.imgur.com/uaOyqKp.png); }"+
                          "div.newsType.translate.fetch:hover { filter: brightness(1.05); }"+
                          "div.newsType.translate.get { background-image: url(https://i.imgur.com/veHKHMp.png); }"+
                          "div.newsType.translate.notl { background-image: url(https://i.imgur.com/dhAM6CE.png); }"+
                          "div.newsType.translate.done { background-image: url(https://i.imgur.com/7aJn98n.png); }";
        document.querySelector('head').appendChild(style);

        tlButton = document.createElement('div');
        tlButton.classList.add("newsType");
        tlButton.classList.add("translate");
        tlButton.classList.add("check");

        var nh = document.querySelector('.newsHeader');
        nh.insertBefore(tlButton, nh.children[1]);

        xhttp = new XMLHttpRequest();
        xhttp.addEventListener("load", translationCheck);
        xhttp.open("GET",TL_MAP_URL);
        xhttp.send();
    } else {
        var styleSheet = document.createElement('link');
        styleSheet.setAttribute('rel', 'stylesheet');
        styleSheet.setAttribute('id', 'star-news_detail-style-css');
        styleSheet.href = "https://krr-prd-web.star-api.com/wp-content/themes/star/assets/css/news_detail.css?ver=2017122705";
        styleSheet.setAttribute('type', 'text/css');
        styleSheet.setAttribute('media', 'all');
        document.querySelector('head').appendChild(styleSheet);

        var style = document.createElement('style');
        style.innerHTML = ".newsDetail .newsInner { margin: 40px auto 40px auto}"+
                          ".newsPost.translated { filter: brightness(1.1); }"+
                          ".page-numbers li { display: inline; }"+
                          ".page-numbers {"+
                              "width: fit-content;"+
                              "margin: 12px auto 0px auto;"+
                              "font-size: 30px;"+
                          "}"+
                          ".page-numbers li {"+
                              "margin: 0px 8px;"+
                          "}"+
                          ".page-numbers .prev { font-size: 0; }"+
                          ".page-numbers .prev::after {"+
                              "font-size: 30px;"+
                              "content: 'prev';"+
                          "}"+
                          ".page-numbers .next { font-size: 0; }"+
                          ".page-numbers .next::after {"+
                              "font-size: 30px;"+
                              "content: 'next';"+
                          "}";
        document.querySelector('head').appendChild(style);

        document.querySelector('.newsTop').classList.add('newsDetail');

        var range = new Range();
        range.selectNode(document.querySelector('.newsList'));

        var mod = document.createElement('div');
        mod.classList.add('newsInner');
        range.surroundContents(mod);

        var posts = document.querySelectorAll('.newsPost');
        for (var i = 0; i < posts.length; i++) {
            range.selectNodeContents(posts[i]);
            mod = document.createElement('div');
            mod.classList.add('newsTitle');
            range.surroundContents(mod);
        }

        xhttp = new XMLHttpRequest();
        xhttp.addEventListener("load", titleCheck);
        xhttp.open("GET",TL_MAP_URL);
        xhttp.send();
    }

    function translationCheck(e) {
        if (xhttp.status == 200) {
            var r = xhttp.responseText;
            var id = window.location.href.match(/\d+/)[0];

            //console.log(xhttp.responseText);
            //console.log(id);

            var n = r.indexOf(id);
            //console.log(n);
            if (n != -1) {
                var start = r.indexOf("url",n);
                var end = r.indexOf('\n',start);
                if (end == -1) { end = r.length; }
                tlURL = r.substring(start+4, end);
                //console.log(tlURL);

                start = r.indexOf("title",n);
                end = r.indexOf('\n',start);
                if (end == -1) { end = r.length; }
                title = r.substring(start+6, end);

                tlButton.onclick = translationFetch;
                tlButton.classList.remove("check");
                tlButton.classList.add("fetch");
            } else {
                tlButton.classList.remove("check");
                tlButton.classList.add("notl");
            }
        } else {
            console.log("Error fetching tl map");
            tlButton.classList.remove("check");
            tlButton.classList.add("notl");
        }
    }

    function translationFetch() {
        tlButton.onclick = null;
        tlButton.classList.remove("fetch");
        tlButton.classList.add("get");

        xhttp = new XMLHttpRequest();
        xhttp.addEventListener("load", translationApply);
        xhttp.open("GET",tlURL);
        xhttp.send();
    }

    function translationApply(e) {
        if (xhttp.status == 200) {
            var parser = new DOMParser();
            var html = parser.parseFromString(xhttp.responseText, "text/html");
            //console.log(html);

            var divs = document.querySelectorAll('.newsText > div');
            for (var i = 0; i < divs.length; i++) {
                var phDiv = html.getElementById(divs[i].getAttribute("data-post-id"));
                //console.log(phDiv);

                divs[i].querySelector('.charNameMain').innerHTML = phDiv.querySelector("#name").innerHTML;
                divs[i].querySelector('.charNameSub').innerHTML = phDiv.querySelector("#nameSub").innerHTML;
                divs[i].querySelector('.charSkillSp > .fontStand').innerHTML = "Totteoki";

                var skillsText = divs[i].querySelectorAll('.charSkill dd');
                skillsText[0].innerHTML = phDiv.querySelector("#ttk").innerHTML;
                skillsText[1].innerHTML = phDiv.querySelector("#skill1").innerHTML;
                skillsText[2].innerHTML = phDiv.querySelector("#skill2").innerHTML;

                phDiv.parentElement.insertBefore(divs[i], phDiv);
                phDiv.parentElement.removeChild(phDiv);
            }

            document.querySelector('.newsTitle dd').innerHTML = title;
            document.querySelector('.newsText').innerHTML = html.querySelector('body').innerHTML;

            tlButton.classList.remove("get");
            tlButton.classList.add("done");
            console.log("Working as intended!");
        } else {
            console.log("Error fetching tl");
            tlButton.classList.remove("get");
            tlButton.classList.add("notl");
        }
    }

    function titleCheck(e) {
        if (xhttp.status == 200) {
            var r = xhttp.responseText;

            var links = document.querySelectorAll('.newsPost a');
            for (var i = 0; i < links.length; i++) {
                var id = links[i].href.match(/\d+/)[0];
                var n = r.indexOf(id);

                if (n != -1) {
                    var start = r.indexOf("title",n);
                    var end = r.indexOf('\n',start);
                    if (end == -1) { end = r.length; }
                    links[i].querySelector('dd').innerHTML = r.substring(start+6, end);
                    links[i].parentElement.parentElement.classList.add('translated');
                }
            }
        } else {
            console.log("Error fetching tl map");
        }
    }

})();