Library of TORN helper

reusable functions

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

  1. function commaSeparateNumber(val){
  2. while (/(\d+)(\d{3})/.test(val.toString())){
  3. val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
  4. }
  5. return val;
  6. }
  7.  
  8. function isNull(v) {
  9. return v != null ? v : 0;
  10. }
  11.  
  12. function checkAPIusage(num) {
  13. var apiUsage = JSON.parse(localStorage.apiUsage || '[]');
  14. var currentTime = moment().unix();
  15.  
  16. for(var i = 0; i < apiUsage.length; i++) {
  17. if((currentTime - apiUsage[0]) > 60)
  18. apiUsage.splice(0,1);
  19. else
  20. break;
  21. }
  22.  
  23. localStorage.apiUsage = JSON.stringify(apiUsage);
  24.  
  25. if((num + apiUsage.length) <= 60)
  26. return true;
  27. else
  28. {
  29. console.warn("cooldown API usage to avoid temporary API banned");
  30. alert("Hold down, your api request is almost reach the limit (100 request per minute). Please try again in a few seconds.")
  31. return false;
  32. }
  33. }
  34.  
  35. function addAPIusage() {
  36. var apiUsage = JSON.parse(localStorage.apiUsage || '[]');
  37. var currentTime = moment().unix();
  38. apiUsage.push(currentTime);
  39. localStorage.apiUsage = JSON.stringify(apiUsage);
  40. }
  41.  
  42. function getCookie(name) {
  43. var value = "; " + document.cookie;
  44. var parts = value.split("; " + name + "=");
  45. if (parts.length == 2) return parts.pop().split(";").shift();
  46. }
  47.  
  48. function getParameterByName(name, url) {
  49. if (!url) url = window.location.href;
  50. name = name.replace(/[\[\]]/g, "\\$&");
  51. var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
  52. results = regex.exec(url);
  53. if (!results) return null;
  54. if (!results[2]) return '';
  55. return decodeURIComponent(results[2].replace(/\+/g, " "));
  56. }
  57.  
  58. function unique(list) {
  59. var result = [];
  60. $.each(list, function(i, e) {
  61. if ($.inArray(e, result) == -1) result.push(e);
  62. });
  63. return result;
  64. }
  65.  
  66. function requireAPI(callback) {
  67. if (localStorage.getItem("_apiKey") === null && !$("#scbox").length) {
  68. $('div.content-title').after(`
  69. <div id='scbox' class="m-top10">
  70. <div class="title-gray top-round" role="heading" aria-level="5">
  71. <i class="issue-attention-icon"></i>
  72. <span id="title">API Key required</span>
  73. </div>
  74. <div class="bottom-round cont-gray p10" id="msg">
  75. <fieldset class="submit-wrap">
  76. <p>You are currently using <strong>${GM.info.script.name}</strong> script that require API key. Please fill your correct API key to use it.</p><br/>
  77. <div class="cont-quantity left">
  78. <div class="input-money-group"><span title="Fill with your correct API key" class="input-money-symbol">KEY</span><input id="quantity-price" class="quantity price input-money" type="text" value=""></div>
  79. </div>
  80. <div class="cont-button left" id="apiSignIn" style="margin-left: 10px;">
  81. <span class="btn-wrap silver">
  82. <span class="btn c-pointer bold" style="padding: 0 15px 0 10px;"><span>SIGN IN</span></span>
  83. </span>
  84. </div>
  85. <div class="clear"></div>
  86. </fieldset>
  87. </div>
  88. <!--div class="clear"></div-->
  89. <hr class="page-head-delimiter m-top10">
  90. </div>`);
  91.  
  92. $("div#scbox #apiSignIn").click(function() {
  93. var apikey = $("div#scbox input").val();
  94. if(!checkAPIusage(1)) return 0;
  95. $.getJSON('https://api.torn.com/user/?selections=basic&key='+apikey, function(data) {
  96. if(data.error != undefined) {
  97. alert(data.error.error);
  98. $("div#scbox .input-money-group").addClass("error");
  99. }
  100. else {
  101. localStorage._apiKey = apikey;
  102. addAPIusage();
  103. $("div#scbox #msg").text("Hi " + data.name +", you have successfully signed in your API key. Thank you.");
  104. setTimeout(() => {
  105. location.reload();
  106. }, 3000);
  107. }
  108. });
  109. });
  110. }
  111. else {
  112. var apikey = localStorage.getItem("_apiKey");
  113. if(!checkAPIusage(1)) return 0;
  114. $.getJSON('https://api.torn.com/user/?selections=profile,discord&key='+apikey, function(data) {
  115. if(data.error != undefined) {
  116. localStorage.removeItem("_apiKey");
  117. }
  118. else {
  119. addAPIusage();
  120. callback(data);
  121. }
  122. });
  123. }
  124. }
  125.  
  126. function fetching(url, callback) {
  127. const noop = () => {}
  128.  
  129. const custom_fetch = (fetch, {
  130. onrequest = noop,
  131. onresponse = noop,
  132. onresult = noop,
  133. onbody = [],
  134. }) => async (input, init) => {
  135. onrequest(input, init)
  136. const response = await fetch(input, init)
  137. onresponse(response)
  138.  
  139. for (const handler of onbody) {
  140. if (handler.match(response)) {
  141. Promise.resolve(handler.execute(response.clone()))
  142. .then((result) => onresult(result))
  143. }
  144. }
  145.  
  146. return response
  147. }
  148.  
  149. const intercept_fetch = (options) => (unsafeWindow.fetch = custom_fetch(fetch, options))
  150.  
  151. intercept_fetch({
  152. // onrequest: (input, init) => console.log('FETCH CALL', input, init),
  153. // onresponse: (response) => console.log('FETCH RESPONSE', response),
  154.  
  155. onbody: [{
  156. match: (response) => response.url.startsWith('https://www.torn.com/' + url),
  157. execute: (response) => response.json().then((json) => callback(json, response.url)),
  158. }],
  159. })
  160. }
  161.  
  162. function xhr(url, data, method, callback) {
  163. $( document ).ajaxComplete(function( event, xhr, settings ) {
  164. settings.data = settings.type == 'POST' ? settings.data : '';
  165. console.log(settings.url.indexOf(url) != -1, settings.data.indexOf(data) != -1);
  166. if(settings.type == method && settings.url.indexOf(url) != -1 && settings.data.indexOf(data) != -1) {
  167. callback(xhr.responseText);
  168. }
  169. });
  170. }
  171.  
  172. function xhr2(urlParam, respParam, callback) {
  173. let oldXHROpen = window.XMLHttpRequest.prototype.open;
  174. window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
  175. this.addEventListener('load', function() {
  176. if(url.indexOf(urlParam) != -1 && this.responseText.indexOf(respParam) != -1) {
  177. callback(this.responseText);
  178. }
  179. });
  180. return oldXHROpen.apply(this, arguments);
  181. }
  182. }
  183.  
  184. function observe(selector, callback) {
  185. var observer = new MutationObserver(function(mutations) {
  186. callback();
  187. });
  188. var observerTarget = $(selector)[0];
  189. var observerConfig = { attributes: false, childList: true, characterData: false, subtree: true };
  190. observer.observe(observerTarget, observerConfig);
  191. }
  192.  
  193. function timeHumanize(seconds) {
  194. var time = moment.duration(seconds * 1000);
  195. var text = '';
  196. months = time.months();
  197. days = time.days();
  198. hours = time.hours();
  199. minutes = time.minutes();
  200. seconds = time.seconds();
  201.  
  202. text += (months > 0) ? (months + " months ") : "";
  203. text += (days > 0) ? (days + " days ") : "";
  204. text += (hours > 0) ? (hours + " hours ") : "";
  205. text += (minutes > 0) ? (minutes + " minutes ") : "";
  206. text += (seconds > 0) ? (seconds + " seconds ") : "";
  207.  
  208. return text;
  209. }
  210.  
  211. var livetime = function(time, elementID, format) {
  212. duration = moment.duration(Math.abs(moment.unix(time).diff(moment())));
  213. // Long
  214. if(format === 'L') {
  215. duration = duration.days() + ' days ' + duration.hours() + ' hours ' + duration.minutes() + ' minutes ' + duration.seconds() + ' seconds ';
  216. }
  217. // Short
  218. if(format === 'S') {
  219. duration = duration.days() + 'D ' + duration.hours() + 'H ' + duration.minutes() + 'M ' + duration.seconds() + 'S ';
  220. }
  221. // Time
  222. if(format === 'T') {
  223. duration = duration.days() + ':' + duration.hours() + ':' + duration.minutes() + ':' + duration.seconds();
  224. }
  225. $("#" + elementID).text(duration);
  226. };
  227.  
  228. function notify(title, msg, icon, url) {
  229. if (Notification.permission !== "granted")
  230. Notification.requestPermission();
  231. else {
  232. var notification = new Notification(title, {
  233. icon: icon,
  234. body: msg,
  235. });
  236.  
  237. notification.onclick = function () {
  238. window.open(url);
  239. };
  240.  
  241. }
  242.  
  243. }

QingJ © 2025

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