AtoZ Utilities

Utilities that are frequently used in other scripts.

当前为 2020-06-07 提交的版本,查看 最新版本

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

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

QingJ © 2025

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