AtoZ Utilities DEV

Utilities that are frequently used in other scripts.

当前为 2020-08-02 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.gf.qytechs.cn/scripts/404603/833029/AtoZ%20Utilities%20DEV.js

  1. // ==UserScript==
  2. // @name AtoZ Utilities DEV
  3. // @namespace AtoZ
  4. // @author AlienZombie [2176352]
  5. // @credit Jox [1714547] {For using various concepts and pieces of code to achieve my objectives}
  6. // @description Utilities that are frequently used in other scripts.
  7. // @version 1.0.0.21
  8. // @source https://gf.qytechs.cn/en/scripts/404603-atoz-utilities
  9. // @connect servicehub.online
  10. // @grant GM_getValue
  11. // @grant GM_setValue
  12. // ==/UserScript==
  13.  
  14.  
  15. initialize();
  16.  
  17. function initialize() {
  18. Number.prototype.format = function(n, x) {
  19. var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')';
  20. return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,');
  21. };
  22. }
  23.  
  24. const localStorageAPIKey = "AtoZ_apikey";
  25. const localStorageDKKAPIKey = "dkkutils_apikey";
  26. const tornPlayerIdCookieName = "uid";
  27.  
  28. var Logging = {
  29. Identifier: "*** AtoZ ***",
  30. Debugging: {
  31. Active: false,
  32. Identifier: "*** AtoZ DEBUG ***"
  33. }
  34. }
  35.  
  36. var thisScriptName = "Utilities";
  37. var tornAPIKey = null;
  38. var tornPlayerId = getCookie(tornPlayerIdCookieName);
  39.  
  40. //#region General Purpose
  41. var setCheckbox = function(origin) {
  42. createDebugLog(thisScriptName, "setCheckbox", " origin Id: " + origin.target.id + " value" + origin.target.checked ? "1" : "0")
  43. localStorage.setItem(origin.target.id, origin.target.checked ? "1" : "0");
  44. //GM_setValue(origin.target.id, origin.target.checked ? "1" : "0");
  45. };
  46.  
  47. var setText = function(origin) {
  48. createDebugLog(thisScriptName, "setText", " origin Id: " + origin.target.id + " value" + origin.target.value)
  49. localStorage.setItem(origin.target.id, origin.target.value);
  50. //GM_setValue(origin.target.id, origin.target.value);
  51. };
  52.  
  53. function Startup(needAPI, activateDebugging) {
  54. if (!validateEmpty(needAPI) && needAPI) {
  55. if (validateEmpty(tornAPIKey)) {
  56. requestAPIKey();
  57. }
  58. }
  59.  
  60. if (!validateEmpty(activateDebugging) && activateDebugging) {
  61. Logging.Debugging.Active = activateDebugging;
  62. }
  63. }
  64.  
  65. function validateEmpty(value) {
  66. if (!value || value === undefined || value == "undefined" || value === null || value == "null" || value === ""){
  67. return true;
  68. }
  69. else {
  70. return false;
  71. }
  72. }
  73.  
  74. function verifyJSONString(JSONString) {
  75. let response = {
  76. isError: null,
  77. errorName: null,
  78. errorMessage: null,
  79. content: null
  80. };
  81.  
  82. let json = null;
  83.  
  84. if (validateEmpty(JSONString)) {
  85. response.isError = true;
  86. response.errorName = "EmptyString";
  87. response.errorMessage = "The JSON string is empty.";
  88. return response;
  89. }
  90. try {
  91. json = JSON.parse(JSONString);
  92. } catch (e) {
  93. response.isError = true;
  94. response.errorName = e.errorName;
  95. response.errorMessage = e.errorMessage;
  96. return response;
  97. }
  98.  
  99. response.isError = false;
  100. response.content = json;
  101. return response;
  102. }
  103.  
  104. function observeMutationsFull(root, callback, options) {
  105. if (!options) options = {
  106. childList: true
  107. };
  108.  
  109. new MutationObserver(callback).observe(root, options);
  110. }
  111.  
  112. function observeMutations(root, selector, runOnce, callback, options, callbackRemoval) {
  113. var ran = false;
  114. observeMutationsFull(root, function(mutations, me) {
  115. var check = $(selector);
  116.  
  117. if (check.length) {
  118. if (runOnce) me.disconnect();
  119.  
  120. ran = true;
  121. callback(mutations, me);
  122. } else if (ran) {
  123. ran = false;
  124. if (callbackRemoval) callbackRemoval(mutations, me);
  125. }
  126. }, options);
  127. }
  128.  
  129. function ajax(callback) {
  130. let funcName = "ajax";
  131.  
  132. $(document).ajaxComplete((event, xhr, settings) => {
  133. if (xhr.readyState > 3 && xhr.status == 200) {
  134. if (settings.url.indexOf("torn.com/") < 0) settings.url = "torn.com" + (settings.url.startsWith("/") ? "" : "/") + settings.url;
  135. var page = settings.url.substring(settings.url.indexOf("torn.com/") + "torn.com/".length, settings.url.indexOf(".php"));
  136.  
  137. var json, uri;
  138.  
  139. let verifyJSON = verifyJSONString(xhr.responseText);
  140. createDebugLog(thisScriptName, funcName, "Ajax Json verify response:");
  141. logDebugObject(verifyJSON);
  142. if (verifyJSON.isError) {
  143. createDebugLog(thisScriptName, funcName, "JSON Error: " + verifyJSON.errorName + " - " + verifyJSON.errorMessage + " ResponseText: " + xhr.responseText);
  144. uri = getUrlParams(xhr.responseText);
  145. } else if (verifyJSON.content.error) {
  146. createDebugLog(thisScriptName, funcName, "ajax Error: " + verifyJSON.content.error.code)
  147. uri = getUrlParams(xhr.responseText);
  148. } else {
  149. json = verifyJSON.content;
  150. }
  151.  
  152. callback(page, json, uri, xhr, settings);
  153. }
  154. });
  155. }
  156.  
  157. function getUrlParams(url, prop) {
  158. var params = {};
  159. var search = decodeURIComponent(((url) ? url : window.location.href).slice(window.location.href.indexOf('?') + 1));
  160. var definitions = search.split('&');
  161.  
  162. definitions.forEach(function(val, key) {
  163. var parts = val.split('=', 2);
  164. params[parts[0]] = parts[1];
  165. });
  166.  
  167. return (prop && prop in params) ? params[prop] : params;
  168. }
  169.  
  170.  
  171. //#endregion General Purpose
  172.  
  173. //#region API Key
  174.  
  175. function validateAPIKey(apiKey) {
  176. let funcName = "validateAPIKey";
  177.  
  178. if (validateEmpty(apiKey)) {
  179. if (validateEmpty(tornAPIKey)) {
  180. createDebugLog(thisScriptName, funcName, "[failure]: " + apiKey);
  181. return null;
  182. }
  183. else {
  184. apiKey = tornAPIKey;
  185. }
  186. }
  187.  
  188. if (apiKey.length != 16) {
  189. createDebugLog(thisScriptName, funcName, "[failure]: " + apiKey);
  190. return null;
  191. }
  192.  
  193. createDebugLog(thisScriptName, funcName, "[success]: " + apiKey);
  194. return apiKey;
  195. }
  196.  
  197. function storeAPIKey(apiKey) {
  198. let funcName = "storeAPIKey";
  199.  
  200. createDebugLog(thisScriptName, funcName, "Checking key for storage")
  201. let apiVar = validateAPIKey(apiKey);
  202.  
  203. if (validateEmpty(apiVar)) {
  204. createDebugLog(thisScriptName, funcName, "[failure]: " + apiVar);
  205. localStorage.removeItem(localStorageAPIKey);
  206. }
  207. else{
  208. localStorage.setItem(localStorageAPIKey, apiVar);
  209. createDebugLog(thisScriptName, funcName, "[success]: " + apiVar);
  210. }
  211.  
  212. tornAPIKey = apiVar;
  213. }
  214.  
  215. function clearAPIKey() {
  216. localStorage.removeItem(localStorageAPIKey);
  217. tornAPIKey = null;
  218. createDebugLog(thisScriptName, "clearAPIKey", "User API Key removed.")
  219. }
  220.  
  221. function retrieveAPIKey() {
  222. let funcName = "retrieveAPIKey";
  223.  
  224. createDebugLog(thisScriptName, funcName, "Check for local API Key")
  225. let apiVar = validateAPIKey(localStorage.getItem(localStorageAPIKey));
  226. if (!validateEmpty(apiVar)) {
  227. createDebugLog(thisScriptName, funcName, "[success]: " + apiVar);
  228. return apiVar;
  229. }
  230. //Maybe the user has DKK scripts, so use that key instead:
  231. createDebugLog(thisScriptName, funcName, "No local key, trying DKK key")
  232. apiVar = validateAPIKey(localStorage.getItem(localStorageDKKAPIKey));
  233. if (!validateEmpty(apiVar)) {
  234. storeAPIKey(apiVar);
  235. return apiVar;
  236. }
  237.  
  238. createDebugLog(thisScriptName, funcName, "[failure]:" + apiVar);
  239. return null
  240. }
  241.  
  242. function requestAPIKey() {
  243. let funcName = "requestAPIKey";
  244.  
  245. tornAPIKey = retrieveAPIKey();
  246. if (validateEmpty(tornAPIKey)) {
  247. createDebugLog(thisScriptName, funcName, "No api key")
  248. let response = prompt("Enter your API key for the AtoZ script(s) to work: ");
  249. tornAPIKey = validateAPIKey(response);
  250. if (!validateEmpty(tornAPIKey)) {
  251. createDebugLog(thisScriptName, funcName, "[VALID] key obtained from user: " + tornAPIKey)
  252. storeAPIKey(tornAPIKey);
  253. } else {
  254. createDebugLog(thisScriptName, funcName, "[INVALID] key obtained from user: " + tornAPIKey)
  255. alert("The key you entered is invalid.\nWithout it, this script cannot work.\nRefresh to try again.")
  256. }
  257. }
  258. }
  259.  
  260. //#endregion API Key
  261.  
  262. //#region Logging
  263.  
  264. function createDebugLog(scriptName, functionName, debugMessage) {
  265. if (!Logging.Debugging.Active) {
  266. return;
  267. }
  268.  
  269. console.log(Logging.Debugging.Identifier + " [" + scriptName + "] - [" + functionName + "] - " + debugMessage);
  270. }
  271.  
  272. function logDebugObject(object) {
  273. if (!Logging.Debugging.Active) {
  274. return;
  275. }
  276.  
  277. console.log(JSON.parse(JSON.stringify(object)));
  278. }
  279.  
  280. function createLog(scriptName, functionName, message) {
  281. console.log(Logging.Identifier + " [" + scriptName + "] - [" + functionName + "] - " + message);
  282. }
  283.  
  284. function logObject(object) {
  285. console.log(JSON.parse(JSON.stringify(object)));
  286. }
  287.  
  288. //#endregion Logging
  289.  
  290. //#region Torn API
  291.  
  292. var tornAPIParts = {
  293. User: {
  294. Key: "user",
  295. Selections: {
  296. Ammo: "ammo",
  297. Attacks: "attacks",
  298. AttacksFull: "attacksfull",
  299. Bars: "bars",
  300. Basic: "basic",
  301. BattleStats: "battlestats",
  302. Bazaar: "bazaar",
  303. Cooldowns: "cooldowns",
  304. Crimes: "crimes",
  305. Discord: "discord",
  306. Display: "display",
  307. Education: "education",
  308. Events: "events",
  309. Gym: "gym",
  310. Hof: "hof",
  311. Honors: "honors",
  312. Icons: "icons",
  313. Inventory: "inventory",
  314. JobPoints: "jobpoints",
  315. Medals: "medals",
  316. Merits: "merits",
  317. Messages: "messages",
  318. Money: "money",
  319. Networth: "networth",
  320. Notifications: "notifications",
  321. Perks: "perks",
  322. PersonalStats: "personalstats",
  323. Profile: "profile",
  324. Properties: "properties",
  325. ReceivedEvents: "receivedevents",
  326. Refills: "refills",
  327. Revives: "revives",
  328. RevivesFull: "revivesfull",
  329. Stocks: "stocks",
  330. Timestamp: "timestamp",
  331. Travel: "travel",
  332. WeaponExp: "weaponexp",
  333. WorkStats: "workstats"
  334. }
  335. },
  336. Properties: {
  337. Key: "property",
  338. Selections: null
  339. },
  340. Faction: {
  341. Key: "faction",
  342. Selections: null
  343. },
  344. Company: {
  345. Key: "company",
  346. Selections: null
  347. },
  348. ItemMarket: {
  349. Key: "market",
  350. Selections: null
  351. },
  352. Torn: {
  353. Key: "torn",
  354. Selections: null
  355. }
  356. }
  357.  
  358. function tornAPIRequest(part, selections, key) {
  359. let funcName = "tornAPIRequest";
  360.  
  361. createDebugLog(thisScriptName, funcName, `Torn API request for Part: ${part} Player Id: ${tornPlayerId} Selections: ${selections}`);
  362. if (validateEmpty(key)) {
  363. key = tornAPIKey;
  364. }
  365.  
  366. return new Promise((resolve, reject) => {
  367.  
  368. GM_xmlhttpRequest({
  369. method: "GET",
  370. url: `https://api.torn.com/${part}/${tornPlayerId}?selections=${selections}&key=${key}`,
  371. onreadystatechange: function(response) {
  372. if (response.readyState > 3 && response.status === 200) {
  373. createDebugLog(thisScriptName, funcName, "Torn API response received: ")
  374. logDebugObject(response);
  375. let verifyJSON = verifyJSONString(response.responseText);
  376. createDebugLog(thisScriptName, funcName, "Torn API Json verify response:");
  377. logDebugObject(verifyJSON);
  378. if (verifyJSON.isError) {
  379. createDebugLog(thisScriptName, funcName, "JSON Error: " + verifyJSON.errorName + " - " + verifyJSON.errorMessage + " ResponseText: " + response.responseText);
  380. reject("JSON Error", response.responseText);
  381. return;
  382. }
  383.  
  384. resolve(verifyJSON.content);
  385.  
  386. if (verifyJSON.content.error) {
  387. createDebugLog(thisScriptName, funcName, "Torn API Error: " + verifyJSON.content.error.code)
  388. if (verifyJSON.content.error.code == 2) {
  389. clearAPIKey();
  390. }
  391. }
  392. }
  393. },
  394. onerror: function(errorResponse) {
  395. createDebugLog(thisScriptName, funcName, "httpRequest Error: " + errorResponse);
  396. reject('httpRequest error.');
  397. }
  398. })
  399. }).catch(err => {
  400. createDebugLog(thisScriptName, funcName, "Promise Error: " + err);
  401. });
  402. }
  403.  
  404. //#endregion Torn API
  405.  
  406. //#region Generic API
  407.  
  408. function genericAPIRequest(destUrl, requestMethod) {
  409. let funcName = "genericAPIRequest";
  410.  
  411. createDebugLog(thisScriptName, funcName, `API request to ${destUrl}`);
  412.  
  413. return new Promise((resolve, reject) => {
  414. GM_xmlhttpRequest({
  415. method: requestMethod,
  416. url: `${destUrl}`,
  417. headers: {'Cookie': document.cookie},
  418. onreadystatechange: function(response) {
  419. createDebugLog(thisScriptName, funcName, "Generic API response received: ")
  420. logDebugObject(response);
  421. },
  422. onerror: function(errorResponse) {
  423. createDebugLog(thisScriptName, funcName, "httpRequest Error: " + errorResponse);
  424. reject('httpRequest error.');
  425. }
  426. })
  427. }).catch(err => {
  428. createDebugLog(thisScriptName, funcName, "Promise Error: " + err);
  429. });
  430. }
  431.  
  432. //#endregion Generic API
  433.  
  434.  
  435. //#region Cookies
  436.  
  437. function getCookie(cname) {
  438. var name = cname + "=";
  439. var ca = document.cookie.split(';');
  440. for(var i = 0; i < ca.length; i++) {
  441. var c = ca[i];
  442. while (c.charAt(0) == ' ') {
  443. c = c.substring(1);
  444. }
  445. if (c.indexOf(name) == 0) {
  446. return c.substring(name.length, c.length);
  447. }
  448. }
  449. return "";
  450. }
  451.  
  452. //#endregion

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址