FancyIcarus / Skynet Monkey

/**
  The MIT License (MIT)

  Copyright (c) 2014 Jeppe Rune Mortensen

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**/
// ==UserScript==
// @id              SkynetMonkey
// @name            Skynet Monkey
// @namespace       http://skynet
// @version         1.0.1
// @author          fancy <fancyicarus@gmail.com>
// @description     有赞天网优化
// @match           http://skynet.*
// @match           https://skynet.*
// @grant           GM_getValue
// @grant           GM_setValue
// @grant           GM_xmlhttpRequest
// @grant           GM_log
// @grant           GM_registerMenuCommand
// @grant           unsafeWindow
// @license         MIT
// ==/UserScript==

(function () {
  'use strict';
  var style = document.createElement('style');
  style.innerHTML = `
.jstValue {
white-space: pre-wrap;
font-size: 14px;
font-weight: 400;
font-family: 'Lucida Console', Monaco, monospace;
}
.jstComma {
white-space: pre-wrap;
}
.jstProperty {
color: #666;
word-wrap: break-word;
}
.jstBracket {
white-space: pre-wrap;;
}
.jstBool {
color: #2525CC;
}
.jstNum {
color: #D036D0;
}
.jstNull {
color: gray;
}
.jstStr {
color: #2DB669;
}
.jsFold {
user-select: none;
}
.jstFold:after {
content: ' -';
cursor: pointer;
}
.jstExpand {
white-space: normal;
}
.jstExpand:after {
content: ' +';
cursor: pointer;
}
.jstFolded {
white-space: normal !important;
}
.jstHiddenBlock {
display: none;
}`;

  document.head.appendChild(style);

  var JSONTree = (function () {
    var that = {};
    var escapeMap = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&quot;",
      "'": "&#x27;",
      "/": "&#x2F;"
    };

    var defaultSettings = {
      indent: 2
    };

    var id = 0;
    var instances = 0;

    that.create = function (data, settings) {
      instances += 1;
      return _span(_jsVal(data, 0, false), {
        class: "jstValue"
      });
    };

    var _escape = function (text) {
      return text.replace(/[&<>'"]/g, function (c) {
        return escapeMap[c];
      });
    };

    var _id = function () {
      return instances + "_" + id++;
    };

    var _jsVal = function (value, depth, indent) {
      if (value !== null) {
        var type = typeof value;
        switch (type) {
          case "boolean":
            return _jsBool(value, indent ? depth : 0);
          case "number":
            return _jsNum(value, indent ? depth : 0);
          case "string":
            return _jsStr(value, indent ? depth : 0);
          default:
            if (value instanceof Array) {
              return _jsArr(value, depth, indent);
            }
            else {
              return _jsObj(value, depth, indent);
            }
        }
      }
      else {
        return _jsNull(indent ? depth : 0);
      }
    };

    var _jsObj = function (object, depth, indent) {
      var id = _id();
      var content = Object.keys(object)
        .map(function (property) {
          return _property(property, object[property], depth + 1, true);
        })
        .join(_comma());
      var body = [
        _openBracket("{", indent ? depth : 0, id),
        _span(content, {
          id: id
        }),
        _closeBracket("}", depth)
      ].join("\n");
      return _span(body, {});
    };

    var _jsArr = function (array, depth, indent) {
      var id = _id();
      var body = array
        .map(function (element) {
          return _jsVal(element, depth + 1, true);
        })
        .join(_comma());
      var arr = [
        _openBracket("[", indent ? depth : 0, id),
        _span(body, {
          id: id
        }),
        _closeBracket("]", depth)
      ].join("\n");
      return arr;
    };

    var _jsStr = function (value, depth) {
      var jsonString = _escape(JSON.stringify(value));
      return _span(_indent(jsonString, depth), {
        class: "jstStr"
      });
    };

    var _jsNum = function (value, depth) {
      return _span(_indent(value, depth), {
        class: "jstNum"
      });
    };

    var _jsBool = function (value, depth) {
      return _span(_indent(value, depth), {
        class: "jstBool"
      });
    };

    var _jsNull = function (depth) {
      return _span(_indent("null", depth), {
        class: "jstNull"
      });
    };

    var _property = function (name, value, depth) {
      var property = _indent(_escape(JSON.stringify(name)) + ": ", depth);
      var propertyValue = _span(_jsVal(value, depth, false), {});
      return _span(property + propertyValue, {
        class: "jstProperty"
      });
    };

    var _comma = function () {
      return _span(",\n", {
        class: "jstComma"
      });
    };

    var _span = function (value, attrs) {
      return _tag("span", attrs, value);
    };

    var _tag = function (tag, attrs, content) {
      return (
        "<" +
        tag +
        Object.keys(attrs)
        .map(function (attr) {
          return " " + attr + '="' + attrs[attr] + '"';
        })
        .join("") +
        ">" +
        content +
        "</" +
        tag +
        ">"
      );
    };

    var _openBracket = function (symbol, depth, id) {
      return (
        _span(_indent(symbol, depth), {
          class: "jstBracket"
        }) +
        _span("", {
          class: "jstFold",
          onclick: "JSONTree.toggle('" + id + "')"
        })
      );
    };

    that.toggle = function (id) {
      var element = document.getElementById(id);
      var parent = element.parentNode;
      var toggleButton = element.previousElementSibling;
      if (element.className === "") {
        element.className = "jstHiddenBlock";
        parent.className = "jstFolded";
        toggleButton.className = "jstExpand";
      }
      else {
        element.className = "";
        parent.className = "";
        toggleButton.className = "jstFold";
      }
    };

    var _closeBracket = function (symbol, depth) {
      return _span(_indent(symbol, depth), {});
    };

    var _indent = function (value, depth) {
      return Array(depth * 2 + 1).join(" ") + value;
    };

    return that;
  })();

  window.JSONTree = JSONTree;

  function parseUglyJson(text) {
    var json;
    try {
      json = JSON.parse(text);
      if (typeof json !== "object") {
        json = parseUglyJson(json);
      }
    }
    catch (e) {
      json = {};
    }
    return json;
  }

  function refresh() {
    setTimeout(function () {
      console.log('refresh triggered');
      const project = document.querySelector('.log-search-form').querySelector('.el-input__inner').value;
      if (project !== "front-zhifuyun") {
        return;
      }
      const jsons = detectUglyJson();
      jsons.forEach(function (element) {
        if (element.querySelector("div")) {
          return;
        }
        var json = parseUglyJson(element.innerText);
        element.innerText = "";
        var container = document.createElement("div");
        container.innerHTML = JSONTree.create(json);
        element.appendChild(container);
      });
    }, 300);
  }

  function detectUglyJson() {
    var logs = Array.prototype.slice.call(
      document.querySelectorAll(".log-item")
    );

    return logs.map(function (log) {
      return log.querySelectorAll("tr")[2].querySelector(".log-table-content");
    });
  }

  function eventBinder(query, eventName) {
    var classes = query.split(' ');
    try {
      var element = classes.reduce(function (ele, className) {
        return ele.querySelector(className);
      }, document);
      element.addEventListener(eventName, refresh);
    }
    catch (e) {
      return;
    }
  }

  eventBinder(".log-search-btns .hulk-button--primary", "click");
  eventBinder(".log-search-form .hulk-col-7 .el-radio-group", "click");
})();