QOS-Handler

QOS-Handler(window param ver)

目前為 2021-08-03 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.cn-greasyfork.org/scripts/430297/956917/QOS-Handler.js

  1. // ==UserScript==
  2. // @name QOS-Handler
  3. // @namespace http://greasyfork.org/
  4. // @version 0.1
  5. // @description QOS-Handler(window param ver)
  6. // @author Cosil.C
  7. // @license GPL
  8. // ==/UserScript==
  9.  
  10. /* jshint esversion: 6 */
  11. /**
  12. * @description 流控相关
  13. */
  14. document.defaultView.qos = {
  15. /**
  16. * @description 记录这次的访问时间戳,并返回是否超出限制
  17. * @param sec 时间限制
  18. * @param timesLimit 次数限制
  19. * @returns sec秒内访问了超过timesLimit次 ? true : false
  20. */
  21. record: (sec, timesLimit) => {
  22. sec = sec || 5;
  23. timesLimit = timesLimit || 10;
  24. console.log(`start qos recording...\nsec:${sec},timesLimit:${timesLimit}`);
  25. let timestamp = new Date().getTime(), historyArr = document.defaultView.qos.getRecord();
  26. historyArr.push(timestamp);
  27. if (historyArr.length > timesLimit) {
  28. let shift;
  29. do {
  30. shift = parseInt(historyArr.shift());
  31. } while (historyArr.length > timesLimit);
  32. //
  33. if (timestamp - shift <= sec * 1000) {
  34. let format = function (target) {
  35. return new Date(target).toTimeString().substr(0, 8);
  36. };
  37. console.log(`current:${format(timestamp)}, shift:${format(shift)}, interval(sec):${(timestamp - shift) / 1000}`);
  38. return true;
  39. }
  40. }
  41. localStorage.setItem('historyArr', JSON.stringify(historyArr));
  42. console.log('qos recorded');
  43. return false;
  44. },
  45. /**
  46. * @description 清除缓存中的记录
  47. */
  48. clearRecord: () => {
  49. localStorage.removeItem('historyArr');
  50. },
  51. /**
  52. * @description 获取记录的历史
  53. * @returns 历史记录数组
  54. */
  55. getRecord: () => {
  56. let historyArr;
  57. try {
  58. historyArr = JSON.parse(localStorage.getItem('historyArr') || '[]');
  59. } catch (e) {
  60. console.error(e);
  61. console.error(`cause:${localStorage.getItem('historyArr')}`);
  62. document.defaultView.qos.clearRecord();
  63. historyArr = [];
  64. }
  65. return historyArr;
  66. }
  67. };