QOS-Handler

QOS-Handler(window param ver)

此脚本不应直接安装,它是供其他脚本使用的外部库。如果你需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/430297/1128326/QOS-Handler.js

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