DKK Torn Utilities DEVELOPMENT

Commonly used functions in my Torn scripts.

当前为 2019-11-19 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/392610/751034/DKK%20Torn%20Utilities%20DEVELOPMENT.js

  1. // ==UserScript==
  2. // @name DKK Torn Utilities DEVELOPMENT
  3. // @description Commonly used functions in my Torn scripts.
  4. // @version 2.0.5
  5. // @exclude *
  6. // @namespace https://openuserjs.org/users/DeKleineKobini
  7. // @homepageURL https://www.torn.com/forums.php#/p=threads&t=16110079
  8. // ==/UserScript==
  9.  
  10. /* Script Setup */
  11. loadCSS();
  12. addFunctions();
  13.  
  14. function loadCSS() {
  15. if ($("#dkkutilscss").length) return;
  16. $("head").append("<style id='dkkutilscss'>"
  17. + ".dkk-button, .dkk-button-green { -webkit-appearance: button; -moz-appearance: button; appearance: button; text-decoration: none; ext-shadow: rgba(0, 0, 0, 0.05) 1px 1px 2px; cursor: pointer; font-weight: 400; text-transform: none; position: relative; text-align: center; line-height: 1.2; box-shadow: rgba(255, 255, 255, 0.5) 0px 1px 1px 0px inset, rgba(0, 0, 0, 0.25) 0px 1px 1px 1px; border-width: initial; border-style: none; border-color: initial; border-image: initial; padding: 2px 10px; border-radius: 4px; } "
  18. + ".dkk-button-green { background-color: rgba(255, 255, 255, 0.15); color: rgb(255, 255, 255); }"
  19. + ".dkk-widget { margin-top: 10px; }"
  20. + ".dkk-widget_red, .dkk-widget_green { background-image: linear-gradient(90deg, transparent 50%, rgba(0, 0, 0, 0.07) 0px); background-size: 4px; display: flex; align-items: center; color: rgb(255, 255, 255); font-size: 13px; letter-spacing: 1px; text-shadow: rgba(0, 0, 0, 0.65) 1px 1px 2px; padding: 6px 10px; border-radius: 5px 5px 0 0; } "
  21. + ".dkk-widget_green { background-color: rgb(144, 176, 46); }"
  22. + ".dkk-widget_red { background-color: rgb(251, 0, 25); }"
  23. + ".dkk-widget_title { flex-grow: 1; box-sizing: border-box; }"
  24. + ".dkk-widget_body { display: flex; padding: 0px; line-height: 1.4; background-color: rgb(242, 242, 242); }"
  25. + ".dkk-round-bottom { border-radius: 0 0 10px 10px; }"
  26. + ".dkk-round { border-radius: 5px; }"
  27. + ".dkk-panel-left, .dkk-panel-right, .dkk-panel-middle { flex: 1 0 0px; max-height: 120px; overflow: auto; min-height: 60px; }"
  28. + ".dkk-panel-left { border-left: 1px solid transparent; }"
  29. + ".dkk-panel-middle { display: flex-direction: column; }"
  30. + ".dkk-panel-right { display: flex-direction: column; border-radius: 0 0 5px 5px; }"
  31. + ".dkk-data-table { width: 100%; height: 100%; border-collapse: separate; text-align: left; }"
  32. + ".dkk-data-table > tbody > tr > th { height: 16px; white-space: nowrap; text-overflow: ellipsis; font-weight: 700; padding: 2px 10px; border-top: 1px solid rgb(255, 255, 255); border-bottom: 1px solid rgb(204, 204, 204); background: linear-gradient(rgb(255, 255, 255), rgb(215, 205, 220)); }"
  33. + ".dkk-data-table > tbody > tr > td { padding: 2px 10px; border-top: 1px solid rgb(255, 255, 255); border-right: 1px solid rgb(204, 204, 204); border-bottom: 1px solid rgb(204, 204, 204); }"
  34. + "</style>"
  35. );
  36. }
  37.  
  38. function addFunctions() {
  39. // formating for numbers
  40. Number.prototype.format = function(n, x) {
  41. var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')';
  42. return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,');
  43. };
  44. // string functions
  45. String.prototype.replaceAll = function(text, replace) {
  46. let str = this.toString();
  47. while (str.includes(text)) { str = str.replace(text, replace); }
  48. return str;
  49. };
  50. }
  51.  
  52. function initScript(options) {
  53. // some easy name conversion
  54. if (options.name) {
  55. if (!options.id) options.id = options.name.replaceAll(" ", "").toLowerCase();
  56. if (!options.abbr) options.abbr = "";
  57. }
  58. if (!options.logging) {
  59. options.logging = "WARN";
  60. }
  61. // actually init
  62. if (options.api){
  63. if (options.apikey) _setAPI(options.apikey);
  64. requireAPI();
  65. }
  66. if (!unsafeWindow.scripts) unsafeWindow.scripts = { ids: [] };
  67. unsafeWindow.scripts.ids.push(options.id);
  68. unsafeWindow.scripts[options.id] = {
  69. name: options.name,
  70. abbr: options.abbr,
  71. api: options.api ? true : false
  72. };
  73. dkklog.level = options.logging;
  74. dkklog.prefix = "[" + options.abbr + "]";
  75. }
  76.  
  77. /* Messaging */
  78. class DKKLog {
  79. constructor(prefix, level) {
  80. this.levels = {
  81. FATAL: 0,
  82. ERROR: 1,
  83. WARN: 2,
  84. INFO: 3,
  85. DEBUG: 4,
  86. TRACE: 5,
  87. ALL: 6,
  88. OFF: 7
  89. },
  90. this.prefix = prefix;
  91. this._level = level || 2;
  92. }
  93. get level() {
  94. return this._level;
  95. }
  96. set level(val) {
  97. this._level = this.levels[val];
  98. }
  99. logging(level, message, objs) {
  100. if (this._level< this.levels[level]) return;
  101.  
  102. let msg = `${this.prefix}[${level}] ${message}`;
  103.  
  104. if (objs && objs.length) console.log(msg, ...objs);
  105. else console.log(msg);
  106. }
  107. fatal(message, ...objs) { this.logging("FATAL", message, objs); }
  108. error(message, ...objs) { this.logging("ERROR", message, objs); }
  109. warn(message, ...objs) { this.logging("WARN", message, objs); }
  110. info(message, ...objs) { this.logging("INFO", message, objs); }
  111. debug(message, ...objs) { this.logging("DEBUG", message, objs); }
  112. trace(message, ...objs) { this.logging("TRACE", message, objs); }
  113. all(message, ...objs) { this.logging("ALL", message, objs); }
  114. }
  115.  
  116. var dkklog = new DKKLog("[DKK]", 3);
  117.  
  118. /* Torn API */
  119. class TornAPI {
  120. constructor(callback, local) {
  121. this.key = local || localStorage.getItem("dkkutils_apikey2");
  122. if (!this.isValid()) {
  123. dkklog.trace("Asking for the api key.");
  124. let createPrompt = () => {
  125. if (!$("#dkkapi").length) {
  126. let selector;
  127. switch (location.pathname) {
  128. case "/christmas_town.php":
  129. selector = ".content-wrapper div[id*='root'] > div > div:eq(0)";
  130. break;
  131. default:
  132. selector = ".content-title";
  133. break;
  134. }
  135. $(selector).after(
  136. "<div><article class='dkk-widget' id='dkkapi'><header class='dkk-widget_green dkk-round'><span class='dkk-widget_title'>API Promt</span>"
  137. + "<input type='text' id='dkkapi-promt' style='margin-right: 8px;'><a id='dkkapi-save' class='dkk-button-green' href='#'>Save</a>"
  138. + "</header></article></div><div class='clear'></div>"
  139. );
  140. }
  141. $("#dkkapi-save").click(event => {
  142. event.preventDefault();
  143. this.key = $("#dkkapi-promt").val();
  144. if (this.isValid()) {
  145. $("#dkkapi").remove();
  146. localStorage.setItem("dkkutils_apikey", this.key);
  147. if (callback) callback();
  148. } else {
  149. $("#dkkapi-promt").val("");
  150. }
  151. });
  152. }
  153. if ($(".content-wrapper").length) createPrompt();
  154. else observeMutations(document, ".content-wrapper", true, createPromt, { childList: true, subtree: true });
  155. } else {
  156. if (callback) callback();
  157. }
  158. }
  159. isValid() {
  160. if (!this.key || this.key === undefined || this.key == "undefined" || this.key === null || this.key == "null" || this.key === "") return false;
  161. return true;
  162. }
  163. }
  164.  
  165. unsafeWindow.TornAPI = TornAPI;
  166.  
  167. var apiKey;
  168.  
  169. const API_LENGTH = 16;
  170. const STORAGE_LOCATION = "dkkutils_apikey";
  171.  
  172. function requireAPI() {
  173. dkklog.debug("Require API")
  174. apiKey = getAPI();
  175. if (!_isValidAPIKey(apiKey)) {
  176. dkklog.debug("Require API - no valid api found")
  177. let response = prompt("Please enter your API key: ");
  178. if (_isValidAPIKey(response)) {
  179. setAPI(response);
  180. } else {
  181. dkklog.debug("Require API - no valid api given")
  182. alert("Given API key was not valid, script might not work.\nRefresh to try again.")
  183. }
  184. }
  185. }
  186.  
  187. function _isValidAPIKey(key) {
  188. if (!key) key = apiKey;
  189.  
  190. if (!key || key === undefined || key == "undefined" || key === null || key == "null" || key === "") return false;
  191. if (key.length != API_LENGTH) return false;
  192.  
  193. return true;
  194. }
  195.  
  196. function sendAPIRequest(part, id, selections, key) {
  197. dkklog.debug(`Sending API request to ${part}/${selections} on id ${id}`);
  198. if (!key) key = apiKey;
  199.  
  200. return new Promise((resolve, reject) => {
  201. GM_xmlhttpRequest({
  202. method: "GET",
  203. url: `https://api.torn.com/${part}/${id}?selections=${selections}&key=${key}`,
  204. onreadystatechange: function(res) {
  205. if (res.readyState > 3 && res.status === 200) {
  206. dkklog.debug("API response received.")
  207. if (!isJsonString(res.responseText)) {
  208. reject("JSON Error", res.responseText);
  209. return;
  210. }
  211.  
  212. var json = JSON.parse(res.responseText);
  213. resolve(json);
  214.  
  215. if (json.error) {
  216. var code = json.error.code;
  217. dkklog.debug("API Error: " + code)
  218. if (code == 2) setAPI(null);
  219. }
  220. }
  221. },
  222. onerror: function(err) {
  223. console.log(err);
  224. reject('XHR error.');
  225. }
  226. })
  227. }).catch(e => {
  228. console.log(e);
  229. });
  230. }
  231.  
  232. function setAPI(key) {
  233. if (!_isValidAPIKey(key)) {
  234. localStorage.removeItem(STORAGE_LOCATION);
  235. dkklog.debug("Removed key from storage.")
  236. } else {
  237. localStorage.setItem(STORAGE_LOCATION, key);
  238. dkklog.debug(`Added key '${key}' to storage. '${localStorage.getItem(STORAGE_LOCATION)}'`)
  239. }
  240.  
  241. apiKey = key;
  242. }
  243.  
  244. function _setAPI(key) {
  245. if (!_isValidAPIKey(key)) localStorage.removeItem(STORAGE_LOCATION);
  246. else localStorage.setItem(STORAGE_LOCATION, key);
  247.  
  248. apiKey = key;
  249. }
  250.  
  251. function getAPI() {
  252. let utilsKey = localStorage.getItem(STORAGE_LOCATION);
  253. if (_isValidAPIKey(utilsKey)) {
  254. dkklog.debug("getAPI - from own storage '" + utilsKey.length + "'");
  255. return utilsKey;
  256. } else {
  257. dkklog.debug("getAPI - from own storage is invalid '" + utilsKey + "'");
  258. }
  259.  
  260. let key = localStorage.getItem("_apiKey") || localStorage.getItem("x_apikey") || localStorage.getItem("jebster.torn") || localStorage.getItem("TornApiKey");
  261.  
  262. if (_isValidAPIKey(key)) {
  263. dkklog.debug("getAPI - from other storage");
  264. setAPI(key);
  265. } else if (localStorage.getItem("_apiKey")) {
  266. dkklog.debug("getAPI - removed 1");
  267. localStorage.removeItem("_apiKey");
  268. } else if (localStorage.getItem("x_apikey")) {
  269. dkklog.debug("getAPI - removed 2");
  270. localStorage.removeItem("x_apikey");
  271. } else if (localStorage.getItem("jebster.torn")) {
  272. dkklog.debug("getAPI - removed 3");
  273. localStorage.removeItem("jebster.torn");
  274. } else if (localStorage.getItem("_apiKey")) {
  275. dkklog.debug("getAPI - removed 4");
  276. localStorage.removeItem("TornApiKey");
  277. }
  278.  
  279. return utilsKey;
  280. }
  281.  
  282. /* Torn General*/
  283. function getScriptUser() {
  284. let body = $("body")
  285. let contentWrapper = $("#mainContainer > .content-wrapper");
  286.  
  287. return {
  288. isJailed: body.hasClass("jail"),
  289. isHospitalized: body.hasClass("hospital"),
  290. isTravelling: contentWrapper.hasClass("travelling")
  291. }
  292. }
  293.  
  294. /* Networking */
  295.  
  296. function xhrIntercept(callback) {
  297. let oldXHROpen = window.XMLHttpRequest.prototype.open;
  298. window.XMLHttpRequest.prototype.open = function() {
  299. this.addEventListener('readystatechange', function() {
  300. if (this.readyState > 3 && this.status == 200) {
  301. var page = this.responseURL.substring(this.responseURL.indexOf("torn.com/") + "torn.com/".length, this.responseURL.indexOf(".php"));
  302.  
  303. var json, uri;
  304. if (isJsonString(this.response)) json = JSON.parse(this.response);
  305. else uri = getUrlParams(this.responseURL);
  306.  
  307. callback(page, json, uri, this);
  308. }
  309. });
  310.  
  311. return oldXHROpen.apply(this, arguments);
  312. }
  313. }
  314.  
  315. function ajax(callback) {
  316. $(document).ajaxComplete((event, xhr, settings) => {
  317. if (xhr.readyState > 3 && xhr.status == 200) {
  318. if (settings.url.indexOf("torn.com/") < 0) settings.url = "torn.com" + (settings.url.startsWith("/") ? "" : "/") + settings.url;
  319. var page = settings.url.substring(settings.url.indexOf("torn.com/") + "torn.com/".length, settings.url.indexOf(".php"));
  320.  
  321. var json, uri;
  322. if (isJsonString(xhr.responseText)) json = JSON.parse(xhr.responseText);
  323. else uri = getUrlParams(settings.url);
  324.  
  325. callback(page, json, uri, xhr, settings);
  326. }
  327. });
  328. }
  329.  
  330. function interceptFetch(url, callback) {
  331. unsafeWindow.fetch = async (input, options) => {
  332. const response = await fetch(input, options)
  333.  
  334. if (response.url.startsWith("https://www.torn.com/" + url)) {
  335. let res = response.clone();
  336.  
  337. Promise.resolve(res.json().then((json) => callback(json, res.url)));
  338. }
  339.  
  340. return response;
  341. }
  342. }
  343.  
  344. /* DOM */
  345. function observeMutationsFull(root, callback, options) {
  346. if (!options) options = {
  347. childList: true
  348. };
  349.  
  350. new MutationObserver(callback).observe(root, options);
  351. }
  352.  
  353. function observeMutations(root, selector, runOnce, callback, options, callbackRemoval) {
  354. var ran = false;
  355. observeMutationsFull(root, function(mutations, me) {
  356. var check = $(selector);
  357.  
  358. if (check.length) {
  359. if (runOnce) me.disconnect();
  360.  
  361. ran = true;
  362. callback(mutations, me);
  363. } else if (ran) {
  364. ran = false;
  365. if (callbackRemoval) callbackRemoval(mutations, me);
  366. }
  367. }, options);
  368. }
  369.  
  370. /* Caching */
  371. function setCache(key, value, time, sub) {
  372. var end = time == -1 ? -1 : Date.now() + time;
  373.  
  374. var obj = sub ? value : {
  375. value: value,
  376. end: Date.now() + time
  377. };
  378.  
  379. GM_setValue(key, JSON.stringify(obj));
  380. }
  381.  
  382. async function getCache(key, subbed) {
  383. let _obj = await GM_getValue(key, subbed ? "{}" : "{\"end\":0}");
  384. let obj = JSON.parse(_obj);
  385.  
  386. var end = obj.end;
  387. if (!end || end == -1 || end > Date.now())
  388. return subbed ? obj : obj.value;
  389.  
  390. return undefined;
  391. }
  392.  
  393. function getSubCache(cache, id) {
  394. if (cache[id]) {
  395. var end = cache[id].end;
  396. if (end == -1 || end > Date.now())
  397. return cache[id].value;
  398. }
  399.  
  400. return undefined;
  401. }
  402.  
  403. /* General Utilities */
  404.  
  405. function isJsonString(str) {
  406. if (!str || str == "") return false;
  407. try {
  408. JSON.parse(str);
  409. } catch (e) {
  410. return false;
  411. }
  412. return true;
  413. }
  414.  
  415. /**
  416. * JavaScript Get URL Parameter (https://www.kevinleary.net/javascript-get-url-parameters/)
  417. *
  418. * @param String prop The specific URL parameter you want to retreive the value for
  419. * @return String|Object If prop is provided a string value is returned, otherwise an object of all properties is returned
  420. */
  421. function getUrlParams(url, prop) {
  422. var params = {};
  423. var search = decodeURIComponent(((url) ? url : window.location.href).slice(window.location.href.indexOf('?') + 1));
  424. var definitions = search.split('&');
  425.  
  426. definitions.forEach(function(val, key) {
  427. var parts = val.split('=', 2);
  428. params[parts[0]] = parts[1];
  429. });
  430.  
  431. return (prop && prop in params) ? params[prop] : params;
  432. }
  433.  
  434. function getSpecialSearch() {
  435. let hash = window.location.hash;
  436.  
  437. hash = hash.replace("#/", "?");
  438. hash = hash.replace("#!", "?");
  439.  
  440. return hash;
  441. }
  442.  
  443. function stripHtml(html) {
  444. var tmp = document.createElement("DIV");
  445. tmp.innerHTML = html;
  446. var stripped = tmp.textContent || tmp.innerText || "";
  447.  
  448. stripped = stripped.replaceAll("\n", "");
  449. stripped = stripped.replaceAll("\t", "");
  450. stripped = stripped.replaceAll(" ", " ");
  451.  
  452. return stripped;
  453. }
  454.  
  455. function getNewDay() {
  456. let now = new Date();
  457. let newDay = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate() - 1, 0, 0, 0));
  458.  
  459. if (Date.now() >= newDay.getTime()) newDay.setUTCDate(newDay.getUTCDate() + 1);
  460. if (Date.now() >= newDay.getTime()) newDay.setUTCDate(newDay.getUTCDate() + 1);
  461.  
  462. return newDay;
  463. }
  464.  
  465. function getMillisUntilNewDay() {
  466. return getNewDay().getTime() - Date.now();
  467. }
  468.  
  469. function _isMobile() {
  470. return navigator.userAgent.match(/Android/i) ||
  471. navigator.userAgent.match(/webOS/i) ||
  472. navigator.userAgent.match(/iPhone/i) ||
  473. navigator.userAgent.match(/iPad/i) ||
  474. navigator.userAgent.match(/iPod/i) ||
  475. navigator.userAgent.match(/BlackBerry/i) ||
  476. navigator.userAgent.match(/Windows Phone/i);
  477. }
  478.  
  479. function runOnEvent(funct, event, runBefore) {
  480. if (runBefore) funct();
  481.  
  482. $(window).bind(event, function() {
  483. funct();
  484. });
  485. }
  486.  
  487. function timeSince(timeStamp) {
  488. let now = new Date();
  489. let secondsPast = (now.getTime() - timeStamp.getTime()) / 1000;
  490.  
  491. if (secondsPast < 60) return parseInt(secondsPast) + 's';
  492. else if (secondsPast < 3600) return parseInt(secondsPast / 60) + 'm';
  493. else if (secondsPast <= 86400) return parseInt(secondsPast / 3600) + 'h';
  494. else if (secondsPast > 86400) {
  495. let day = timeStamp.getDate();
  496. let month = timeStamp.toDateString().match(/ [a-zA-Z]*/)[0].replace(" ", "");
  497. let year = timeStamp.getFullYear() == now.getFullYear() ? "" : " " + timeStamp.getFullYear();
  498. return day + " " + month + year;
  499. }
  500. }