auto-task-v4

自动完成 Freeanywhere,Giveawaysu,GiveeClub,Givekey,Gleam,Indiedb,keyhub,OpiumPulses,Opquests,SweepWidget 等网站的任务。

当前为 2025-03-03 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name auto-task-v4
  3. // @namespace auto-task-v4
  4. // @version 4.6.5
  5. // @description 自动完成 Freeanywhere,Giveawaysu,GiveeClub,Givekey,Gleam,Indiedb,keyhub,OpiumPulses,Opquests,SweepWidget 等网站的任务。
  6. // @description:en Automatically complete the tasks of FreeAnyWhere, GiveawaySu, GiveeClub, Givekey, Gleam, Indiedb, keyhub, OpiumPulses, Opquests, SweepWidget websites.
  7. // @author HCLonely
  8. // @license MIT
  9. // @run-at document-start
  10. // @homepage https://auto-task-doc.js.org/
  11. // @supportURL https://github.com/HCLonely/auto-task-v4/issues
  12. // @icon https://auto-task-v4.hclonely.com/favicon.ico
  13.  
  14. // @include *://freeanywhere.net/*
  15. // @include *://giveaway.su/giveaway/view/*
  16. // @include *://givee.club/*/event/*
  17. // @include *://givekey.ru/giveaway/*
  18. // @include *://www.indiedb.com/giveaways*
  19. // @include *://key-hub.eu/giveaway/*
  20. // @include *://keylol.com/*
  21. // @include *://www.opiumpulses.com/giveaways
  22. // @include *://prys.revadike.com/giveaway/?id=*
  23. // @include *://opquests.com/quests/*
  24. // @include *://gleam.io/*
  25. // @include *://sweepwidget.com/view/*
  26. // @include *://giveawayhopper.com/c/*
  27.  
  28. // @include *://discord.com/*
  29. // @include *://www.twitch.tv/*
  30. // @include *://www.youtube.com/*
  31. // @include *://*.reddit.com/*
  32. // @include *://twitter.com/settings/account?k*
  33. // @include *://x.com/settings/account*
  34. // @include *://steamcommunity.com/*
  35. // @include *://store.steampowered.com/*
  36. // @include https://auto-task-v4.hclonely.com/setting.html
  37. // @include https://auto-task-v4.hclonely.com/history.html
  38.  
  39. // @grant GM_setValue
  40. // @grant GM_getValue
  41. // @grant GM_listValues
  42. // @grant GM_deleteValue
  43. // @grant GM_addStyle
  44. // @grant GM_xmlhttpRequest
  45. // @grant GM_registerMenuCommand
  46. // @grant GM_info
  47. // @grant GM_openInTab
  48. // @grant GM_setClipboard
  49. // @grant GM_getResourceText
  50. // @grant GM_cookie
  51. // @grant GM_addValueChangeListener
  52. // @grant GM_removeValueChangeListener
  53. // @grant unsafeWindow
  54. // @grant window.close
  55. // @grant window.localStorage
  56. // @grant window.sessionStorage
  57. // @grant window.focus
  58.  
  59. // @connect cdn.jsdelivr.net
  60. // @connect store.steampowered.com
  61. // @connect steamcommunity.com
  62. // @connect login.steampowered.com
  63. // @connect twitter.com
  64. // @connect x.com
  65. // @connect api.twitter.com
  66. // @connect youtube.com
  67. // @connect www.youtube.com
  68. // @connect facebook.com
  69. // @connect instagram.com
  70. // @connect vk.com
  71. // @connect twitch.tv
  72. // @connect www.twitch.tv
  73. // @connect gql.twitch.tv
  74. // @connect github.com
  75. // @connect discordapp.com
  76. // @connect discord.gg
  77. // @connect discord.com
  78. // @connect www.reddit.com
  79. // @connect oauth.reddit.com
  80. // @connect raw.githubusercontent.com
  81. // @connect t.me
  82. // @connect bit.ly
  83. // @connect giveaway.su
  84. // @connect google.com
  85. // @connect www.vloot.io
  86. // @connect givee.club
  87. // @connect gleam.io
  88. // @connect www.indiedb.com
  89. // @connect key-hub.eu
  90. // @connect opquests.com
  91. // @connect itch.io
  92. // @connect auto-task-v4.hclonely.com
  93. // @connect giveawayhopper.com
  94. // @connect *
  95. // @require https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
  96. // @require https://cdn.jsdelivr.net/npm/js-cookie@3.0.1/dist/js.cookie.min.js
  97. // @require https://cdn.jsdelivr.net/npm/regenerator-runtime@0.13.5/runtime.min.js
  98. // @require https://cdn.jsdelivr.net/npm/js-sha1@0.6.0/src/sha1.min.js
  99. // @require https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js
  100. // @resource style https://cdn.jsdelivr.net/npm/sweetalert2@11.3.5/dist/sweetalert2.min.css
  101. // @require https://cdn.jsdelivr.net/npm/keyboardjs@2.6.4/dist/keyboard.min.js
  102. // @require https://cdn.jsdelivr.net/npm/dayjs@1.10.7/dayjs.min.js
  103.  
  104. // @noframes
  105. // ==/UserScript==
  106.  
  107. console.log('%c%s', 'color:blue', 'Auto-Task[Load]: 脚本开始加载');
  108. (function() {
  109. var __webpack_modules__ = {
  110. 991: function(__unused_webpack_module, exports) {
  111. !function(e, n) {
  112. true ? n(exports) : 0;
  113. }(this, function(e) {
  114. 'use strict';
  115. var t = function() {
  116. return (t = Object.assign || function(e) {
  117. for (var n, o = 1, t = arguments.length; o < t; o++) {
  118. for (var r in n = arguments[o]) {
  119. Object.prototype.hasOwnProperty.call(n, r) && (e[r] = n[r]);
  120. }
  121. }
  122. return e;
  123. }).apply(this, arguments);
  124. };
  125. function r(e, n, o) {
  126. if (o || 2 === arguments.length) {
  127. for (var t, r = 0, i = n.length; r < i; r++) {
  128. !t && r in n || ((t = t || Array.prototype.slice.call(n, 0, r))[r] = n[r]);
  129. }
  130. }
  131. return e.concat(t || Array.prototype.slice.call(n));
  132. }
  133. function d(e) {
  134. return '[object Object]' === n(e);
  135. }
  136. function l(e, n) {
  137. var o = r(r([], n || [], !0), [ '_' ], !1).join('|');
  138. return e.replace(new RegExp('(('.concat(o, ')[a-z])+'), 'g'), function(e, n) {
  139. return n.replace(new RegExp(o), '').toLocaleUpperCase();
  140. });
  141. }
  142. var n = function(e) {
  143. return Object.prototype.toString.call(e);
  144. };
  145. var o = (i.prototype.init = function() {
  146. try {
  147. this.getSystemName(), this.getBrowserName();
  148. } catch (e) {
  149. console.warn('[UA formatter error] '.concat(e));
  150. }
  151. }, i.prototype.getEngine = function() {
  152. var e = this.agent;
  153. return -1 !== e.indexOf('Trident') ? 'Trident' : -1 !== e.indexOf('Firefox') ? 'Gecko' : -1 !== e.indexOf('Presto') ? 'Presto' : 'WebKit';
  154. }, i.prototype.getSystemName = function() {
  155. var e, n = (this.agent.match(/^[a-z]+\/\d+\.\d+\s?\(([a-z\d\s:;./_-]+)\)/i) || [])[1];
  156. try {
  157. var o = '';
  158. if (/Windows/i.test(n)) {
  159. var t = (n.match(/NT\s(\d+\.\d+)/) || [])[1];
  160. switch (this.info.os = 'Windows', t) {
  161. case '6.3':
  162. o = '8.1';
  163. break;
  164.  
  165. case '6.2':
  166. o = '8';
  167. break;
  168.  
  169. case '6.1':
  170. o = '7';
  171. break;
  172.  
  173. case '5.2':
  174. case '5.1':
  175. o = 'XP';
  176. break;
  177.  
  178. default:
  179. o = t;
  180. }
  181. return this.info.device = 'PC', void (this.info.osVersion = o);
  182. }
  183. if (/^Macintosh/i.test(n)) {
  184. return o = (n.match(/X\s((\d+(_|\.))+\d+)/) || [])[1], this.info.os = 'Macintosh',
  185. this.info.device = 'PC', void (this.info.osVersion = null !== (e = null == o ? void 0 : o.replace(/_/g, '.')) && void 0 !== e ? e : 'Unknown');
  186. }
  187. if (/^iPad/i.test(n)) {
  188. return o = (n.match(/((\d+_)+\d+)/) || [])[1], this.info.os = 'iPad',
  189. this.info.device = 'Tablet', void (this.info.osVersion = o.replace(/_/g, '.'));
  190. }
  191. if (/^iPhone/i.test(n)) {
  192. return o = (n.match(/((\d+_)+\d+)/) || [])[1], this.info.os = 'iPhone',
  193. this.info.device = 'Mobile', void (this.info.osVersion = o.replace(/_/g, '.'));
  194. }
  195. if (-1 !== n.indexOf('Android')) {
  196. var r = (n.match(/Android\s((\d+\.?)+\d?)/) || [])[1];
  197. return this.info.device = 'Mobile', this.info.os = 'Android', void (this.info.osVersion = r);
  198. }
  199. if (/Linux\s[a-z\d_]+/.test(n)) {
  200. return this.info.os = 'Linux', void (this.info.osVersion = 'Unknown');
  201. }
  202. this.info.os = 'Unknown', this.info.osVersion = 'Unknown';
  203. } catch (e) {
  204. this.info.os = 'Unknown', this.info.osVersion = 'Unknown';
  205. }
  206. }, i.prototype.getBrowserName = function() {
  207. var e = Object.keys(this.browserNameMap).map(function(e) {
  208. return new RegExp(''.concat(e, '(\\/|\\s)(\\d+\\.)+\\d+'));
  209. }), n = 1 < (n = (this.agent.match(/[a-z\d]+(\/|\s)(\d+\.)+\d+/gi) || []).filter(function(n) {
  210. return -1 !== e.findIndex(function(e) {
  211. return e.test(n);
  212. });
  213. })).length && !/^Safari/.test(n[n.length - 1]) ? n.reverse() : n;
  214. this.info = t(t({}, this.info), this._formatBrowserVersion(n[0]));
  215. }, i.prototype._formatBrowserVersion = function(e) {
  216. var n, o, t, r;
  217. try {
  218. for (var i = null !== (o = null === (n = e.match(/(?<name>[a-z\d]+)(\/|\s)(?<version>(\d+\.)+\d+)/i)) || void 0 === n ? void 0 : n.groups) && void 0 !== o ? o : {}, s = i.name, a = i.version, c = {}, f = 0, u = Object.entries(this.browserNameMap); f < u.length; f++) {
  219. var d = u[f], l = d[0], h = d[1];
  220. if (new RegExp(l).test(s)) {
  221. c = h;
  222. break;
  223. }
  224. }
  225. var p = {
  226. browserVersion: null != a ? a : 'Unknown',
  227. browser: null !== (t = c.en) && void 0 !== t ? t : 'Unknown',
  228. browserZH: null !== (r = (null == c ? void 0 : c.zh) || c.en) && void 0 !== r ? r : 'Unknown'
  229. };
  230. return 'Trident' === s && (p.browserVersion = {
  231. '4.0': 8,
  232. '5.0': 9,
  233. '6.0': 10,
  234. '7.0': 11
  235. }[a]), p;
  236. } catch (e) {
  237. return console.warn('[UA formatter error] '.concat(e)), {
  238. browser: 'Unknown',
  239. browserVersion: 'Unknown'
  240. };
  241. }
  242. }, i);
  243. function i(e) {
  244. this.agent = '', this.info = {
  245. browser: '',
  246. browserZH: '',
  247. browserVersion: '',
  248. os: '',
  249. osVersion: '',
  250. device: 'Unknown',
  251. engine: 'WebKit'
  252. }, this.browserNameMap = {
  253. MicroMessenger: {
  254. en: 'MicroMessenger',
  255. zh: '微信'
  256. },
  257. MetaSr: {
  258. en: 'MetaSr',
  259. zh: '搜狗浏览器'
  260. },
  261. 'QQ(Browser)?': {
  262. en: 'QQBrowser',
  263. zh: 'QQ浏览器'
  264. },
  265. UCBrowser: {
  266. en: 'UCBrowser',
  267. zh: 'UC浏览器'
  268. },
  269. '2345Explorer': {
  270. en: '2345Explorer',
  271. zh: '2345极速浏览器'
  272. },
  273. Mb2345Browser: {
  274. en: 'Mb2345Browser',
  275. zh: '2345手机浏览器'
  276. },
  277. Trident: {
  278. en: 'Internet Explorer'
  279. },
  280. 'Edge?': {
  281. en: 'Edge'
  282. },
  283. OPR: {
  284. en: 'Opera'
  285. },
  286. Vivaldi: {
  287. en: 'Vivaldi'
  288. },
  289. Firefox: {
  290. en: 'Firefox'
  291. },
  292. Chrome: {
  293. en: 'Chrome'
  294. },
  295. Safari: {
  296. en: 'Safari'
  297. }
  298. }, this.agent = e, this.init();
  299. var n = this.info, o = n.browser, e = n.browserVersion, n = n.osVersion;
  300. this.info = t(t({}, this.info), {
  301. engine: this.getEngine(),
  302. browserVersion: 'Safari' === o ? n : e
  303. });
  304. }
  305. function s() {
  306. this.cookies = {}, this.init();
  307. }
  308. var a = new (s.prototype.init = function() {
  309. var o = {};
  310. document.cookie.split(/;\s/).forEach(function(e) {
  311. var n = e.split(/=/), e = n[0], n = n[1];
  312. o[e] = n;
  313. }), this.cookies = o;
  314. }, s.prototype.getItem = function(e) {
  315. return this.cookies[e];
  316. }, s.prototype.getAllItems = function() {
  317. return this.cookies;
  318. }, s.prototype.setItem = function(e, n, o, t, r, i) {
  319. document.cookie = ''.concat(e, '=').concat(n).concat(o ? '; expires='.concat(o) : '').concat(t ? '; path='.concat(t) : '').concat(r ? '; domain='.concat(r) : '').concat(i ? '; secure' : '');
  320. }, s)();
  321. e.countDown = function e(n, o, t, r) {
  322. if (!window) {
  323. throw new Error('window is not defind.');
  324. }
  325. if (0 < n) {
  326. return r && r(), n--, window[o] = window.setTimeout(function() {
  327. e(n, o, t, r);
  328. }, 1e3), function() {
  329. return clearTimeout(window[o]);
  330. };
  331. }
  332. clearTimeout(window[o]), t && t();
  333. }, e.createRandomID = function(e) {
  334. void 0 === e && (e = 12);
  335. for (var n = [], o = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''), t = o.length, r = 0; r < e; r++) {
  336. n.push(o[Math.round(Math.random() * t)]);
  337. }
  338. return n.join('');
  339. }, e.dCookie = a, e.debounce = function(o, t, r) {
  340. var i;
  341. void 0 === t && (t = 0);
  342. var s = r = void 0 === r ? !1 : r;
  343. return function() {
  344. var e = this, n = arguments;
  345. s && (o.apply(this, arguments), s = !1), clearTimeout(i), i = setTimeout(function() {
  346. r ? s = !0 : o.apply(e, n);
  347. }, t);
  348. };
  349. }, e.deepCopy = function e(n) {
  350. if (d(n) || Array.isArray(n)) {
  351. var o, t = Array.isArray(n) ? [] : {};
  352. for (o in n) {
  353. t[o] = e(n[o]);
  354. }
  355. return t;
  356. }
  357. return n;
  358. }, e.formatQueryParams = function(e) {
  359. e = null === (e = /\?(?<params>(.*)=.+)/.exec(decodeURIComponent(e))) || void 0 === e ? void 0 : e.groups;
  360. if (!e) {
  361. return {};
  362. }
  363. for (var n = e.params.split('&'), t = {}, o = 0; o < n.length; o++) {
  364. n[o].replace(/([^?&]*)=([^?&]*)/, function(e, n, o) {
  365. return t[n] = o, e;
  366. });
  367. }
  368. return t;
  369. }, e.formatThousandth = function(e) {
  370. var n = ''.concat(e).split('.'), e = n[0], n = n[1], n = void 0 === n ? '' : n, e = e.replace(/\d{1,3}(?=(\d{3})+$)/g, '$&,');
  371. return ''.concat(e).concat(n ? '.'.concat(n) : '');
  372. }, e.generateTree = function e(n, o, t, r) {
  373. for (var i = [], s = 0; s < n.length; s++) {
  374. var a = n[s];
  375. a[t] === o && (i.push(a), a.children = e(n, a[null != r ? r : 'id'], t, r));
  376. }
  377. return i;
  378. }, e.isEmpty = function(e) {
  379. return Array.isArray(e) ? 0 === e.length : d(e) ? 0 === Object.keys(e).length : [ '[object Set]', '[object Map]' ].includes(n(e)) ? 0 === e.size : [ null, void 0, '' ].includes(e);
  380. }, e.isFunction = function(e) {
  381. return '[object Function]' === n(e);
  382. }, e.isImageUrl = function(e) {
  383. return /\.((png)|(jpe?g)|(gif)|(svg)|(webp))$/gi.test(e);
  384. }, e.isObject = d, e.isRegexp = function(e) {
  385. return '[object RegExp]' === n(e);
  386. }, e.objectKeyToCamelCase = function e(n, o, t) {
  387. if (Array.isArray(n)) {
  388. for (var r = [], i = 0; i < n.length; i++) {
  389. r[i] = e(o && n[i][o] ? n[i][o] : n[i], o, t);
  390. }
  391. } else if (d(n)) {
  392. r = {};
  393. for (var s = o && n[o] ? n[o] : n, a = 0, c = Object.entries(s); a < c.length; a++) {
  394. var f = (u = c[a])[0], u = u[1];
  395. Array.isArray(u) || d(s) ? r[l(f, t)] = e(u, o, t) : r[l(f, t)] = u;
  396. }
  397. } else {
  398. r = n;
  399. }
  400. return r;
  401. }, e.realType = n, e.searchParams = function(e, n) {
  402. return void 0 === e && (e = null === location || void 0 === location ? void 0 : location.search),
  403. new URLSearchParams(e).get(n);
  404. }, e.toLowerCamelCase = l, e.toUnderline = function(e) {
  405. return e.replace(/([A-Z])/g, function(e) {
  406. return '_'.concat(e.toLocaleLowerCase());
  407. });
  408. }, e.ua = function(e) {
  409. return void 0 === e && (e = navigator.userAgent), new o(e).info;
  410. }, Object.defineProperty(e, '__esModule', {
  411. value: !0
  412. });
  413. });
  414. },
  415. 675: function(module, __webpack_exports__, __webpack_require__) {
  416. 'use strict';
  417. __webpack_require__.d(__webpack_exports__, {
  418. A: function() {
  419. return __WEBPACK_DEFAULT_EXPORT__;
  420. }
  421. });
  422. var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(601);
  423. var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = __webpack_require__.n(_node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
  424. var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(314);
  425. var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = __webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
  426. var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()(_node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default());
  427. ___CSS_LOADER_EXPORT___.push([ module.id, `.colorful-button,#auto-task-buttons a.auto-task-website-btn,.show-button-div a.auto-task-website-btn,body.auto-task-options .auto-task-form table button{position:relative;padding:5px 10px;text-align:center;color:#fff;text-decoration:none;background:linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);border-radius:30px;background-size:400%;text-transform:capitalize}.colorful-button:hover,#auto-task-buttons a.auto-task-website-btn:hover,.show-button-div a.auto-task-website-btn:hover,body.auto-task-options .auto-task-form table button:hover{transform:scale(1.05);box-shadow:0 6px 20px rgba(0,0,0,.3);cursor:pointer}.colorful-button:hover::before,#auto-task-buttons a.auto-task-website-btn:hover::before,.show-button-div a.auto-task-website-btn:hover::before,body.auto-task-options .auto-task-form table button:hover::before{filter:blur(10px);opacity:1}.colorful-button::before,#auto-task-buttons a.auto-task-website-btn::before,.show-button-div a.auto-task-website-btn::before,body.auto-task-options .auto-task-form table button::before{content:"";position:absolute;top:-5px;left:-5px;right:-5px;bottom:-5px;z-index:-1;background:linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);border-radius:40px;background-size:400%;opacity:-1}#auto-task-info{z-index:999999999 !important}#auto-task-info{position:fixed;bottom:10px;right:10px;width:60%;max-width:500px;max-height:60%;overflow-y:auto;color:#000;background-color:#fff;padding-left:5px;border:solid 2px #add8e6;border-radius:10px}#auto-task-info li{text-align:left}#auto-task-info li a.high-light{color:#00aeff;font-weight:bold}#auto-task-info .success{color:green}#auto-task-info .error{color:red}#auto-task-info .warning{color:blue}#auto-task-info .info{color:#ff0}#auto-task-info .update-text{color:green;border:solid 2px #8dcb69;margin:5px 10px 5px 20px;border-radius:10px;padding:5px 20px}.auto-task-keylol{text-decoration:none !important}.auto-task-keylol{display:inline-block;text-transform:capitalize;margin-left:10px;border:solid 1px;border-radius:5px;padding:0 2px}.auto-task-keylol[selected=selected]{background-color:blue !important;color:#fff !important}.auto-task-form table{font-family:verdana,arial,sans-serif;font-size:11px;color:#333;border-width:1px;border-color:#999;border-collapse:collapse;width:100%}.auto-task-form table thead td{border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9;font-weight:bold;background-color:#fff}.auto-task-form table tbody tr{background-color:#d4e3e5}.auto-task-form table tbody tr:hover{background-color:#ff6 !important}.auto-task-form table tbody tr th{background-color:#c3dde0;border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9;text-transform:capitalize}.auto-task-form table tbody tr td{border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9}.swal2-modal{width:70% !important;max-width:1000px !important}body.auto-task-options{padding-top:10px;text-align:center}body.auto-task-options .auto-task-form{width:80%;max-width:1000px;margin:0 auto;padding-bottom:20px}body.auto-task-options .auto-task-form table input.editOption{width:80%}body.auto-task-options .auto-task-form table #getTwitterUserId,body.auto-task-options .auto-task-form table #getYoutubeChannelId{margin-top:5px}body.auto-task-options .auto-task-form table button{z-index:1}body.auto-task-options .auto-task-form table input[type=text]{outline-style:none;border:1px solid #ccc;border-radius:3px;padding:5px 10px;font-size:14px}body.auto-task-options .auto-task-form table input[type=text]:focus{border-color:#66afe9;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}body.auto-task-options .auto-task-form table label{position:relative;width:160px;height:80px;cursor:pointer;transform:scale(0.25);margin:-25% 0;top:-30px;display:inline-block}body.auto-task-options .auto-task-form table label input{position:relative;z-index:1;appearance:none}body.auto-task-options .auto-task-form table label input:checked~span{background:#05be05;box-shadow:0 15px 25px rgba(5,190,5,.4)}body.auto-task-options .auto-task-form table label input:checked~span i{left:84px}body.auto-task-options .auto-task-form table label input:checked~span i::before{background:#05be05;box-shadow:35px 0 0 #05be05}body.auto-task-options .auto-task-form table label input:checked~span i::after{bottom:12px;height:15px;border-bottom-left-radius:15px;border-bottom-right-radius:15px;background:#05be05}body.auto-task-options .auto-task-form table label span{position:absolute;top:0;left:0;width:100%;height:100%;background:#fe0000;border-radius:80px;transition:.5s;box-shadow:0 15px 25px rgba(254,0,0,.4)}body.auto-task-options .auto-task-form table label span i{position:absolute;top:4px;left:4px;width:72px;height:72px;background:#fff;border-radius:50%}body.auto-task-options .auto-task-form table label span i::before{content:"";position:absolute;top:22px;left:12px;width:12px;height:12px;border-radius:50%;background:#fe0000;box-shadow:35px 0 0 #fe0000;transition:.5s}body.auto-task-options .auto-task-form table label span i::after{content:"";position:absolute;bottom:15px;left:calc(50% - 15px);width:30px;height:6px;border-radius:6px;background:#fe0000;transition:.5s}body.auto-task-history{font-size:15px;font-weight:400;line-height:1.5}body.auto-task-history .container a{color:#007bff;text-decoration:none;background-color:rgba(0,0,0,0)}body.auto-task-history .container .card{width:80%;max-width:800px;border-radius:10px;background:rgba(118,118,118,.1019607843);border-top:1px solid rgba(255,255,255,.5019607843);-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);box-shadow:0 15px 25px rgba(0,0,0,.1019607843);margin:20px auto;position:relative;display:flex;flex-direction:column;word-wrap:break-word;-webkit-background-clip:border-box;background-clip:border-box;border:1px solid rgba(0,0,0,.125);border-radius:.25rem}body.auto-task-history .container .card .title{text-align:center;font-size:30px;font-weight:bold;margin:5px 0}body.auto-task-history .container .card .title a:hover{text-decoration:none;background:#93e1ff;border-radius:10px;padding:3px}body.auto-task-history .container .card ul{margin-bottom:25px}body.auto-task-history .container .card ul li{margin-bottom:5px;line-height:20px}body.auto-task-history .container .card ul a:hover{text-decoration:underline}body.auto-task-history .container .card .delete-task{right:10px;width:38px;height:35px;position:absolute;font-size:24px;cursor:pointer;border-radius:10px}body.auto-task-history .container .card .delete-task:hover{background:#fff}body.auto-task-history .container .card .time{right:5px;position:absolute;bottom:0;color:#e83e8c;font-family:'SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace';font-size:15px}#auto-task-buttons,.show-button-div{z-index:999999999 !important}#auto-task-buttons,.show-button-div{position:fixed;top:30px;right:15px;width:124px;transform:scale(0.85)}#auto-task-buttons p,.show-button-div p{margin:5px !important}#auto-task-buttons p,.show-button-div p{line-height:30px;height:40px;text-align:center}#auto-task-buttons a.auto-task-website-btn,.show-button-div a.auto-task-website-btn{width:105px;line-height:27px;font-size:20px;display:block}.show-button-div{width:20px}.auto-task-capitalize{text-transform:capitalize !important}.swal2-file:focus,.swal2-input:focus,.swal2-textarea:focus{box-shadow:inset 0px 0px 4px 1px rgba(100,150,200,.5) !important}.swal2-checkbox-custom{align-items:center;justify-content:center;background:#fff;color:inherit;margin:1em auto}.swal2-checkbox-custom input{flex-shrink:0;margin:0 .4em}.giveaway-actions #getKey{display:none !important}.auto-task-giveaway-status{color:#fff;border-radius:10px;padding:0 5px;margin-left:5px}.auto-task-giveaway-status.active{background-color:#5cb85c}.auto-task-giveaway-status.not-active{background-color:#d9534f}`, '' ]);
  428. const __WEBPACK_DEFAULT_EXPORT__ = ___CSS_LOADER_EXPORT___.toString();
  429. },
  430. 314: function(module) {
  431. 'use strict';
  432. module.exports = function(cssWithMappingToString) {
  433. var list = [];
  434. list.toString = function toString() {
  435. return this.map(function(item) {
  436. var content = '';
  437. var needLayer = typeof item[5] !== 'undefined';
  438. if (item[4]) {
  439. content += '@supports ('.concat(item[4], ') {');
  440. }
  441. if (item[2]) {
  442. content += '@media '.concat(item[2], ' {');
  443. }
  444. if (needLayer) {
  445. content += '@layer'.concat(item[5].length > 0 ? ' '.concat(item[5]) : '', ' {');
  446. }
  447. content += cssWithMappingToString(item);
  448. if (needLayer) {
  449. content += '}';
  450. }
  451. if (item[2]) {
  452. content += '}';
  453. }
  454. if (item[4]) {
  455. content += '}';
  456. }
  457. return content;
  458. }).join('');
  459. };
  460. list.i = function i(modules, media, dedupe, supports, layer) {
  461. if (typeof modules === 'string') {
  462. modules = [ [ null, modules, undefined ] ];
  463. }
  464. var alreadyImportedModules = {};
  465. if (dedupe) {
  466. for (var k = 0; k < this.length; k++) {
  467. var id = this[k][0];
  468. if (id != null) {
  469. alreadyImportedModules[id] = true;
  470. }
  471. }
  472. }
  473. for (var _k = 0; _k < modules.length; _k++) {
  474. var item = [].concat(modules[_k]);
  475. if (dedupe && alreadyImportedModules[item[0]]) {
  476. continue;
  477. }
  478. if (typeof layer !== 'undefined') {
  479. if (typeof item[5] === 'undefined') {
  480. item[5] = layer;
  481. } else {
  482. item[1] = '@layer'.concat(item[5].length > 0 ? ' '.concat(item[5]) : '', ' {').concat(item[1], '}');
  483. item[5] = layer;
  484. }
  485. }
  486. if (media) {
  487. if (!item[2]) {
  488. item[2] = media;
  489. } else {
  490. item[1] = '@media '.concat(item[2], ' {').concat(item[1], '}');
  491. item[2] = media;
  492. }
  493. }
  494. if (supports) {
  495. if (!item[4]) {
  496. item[4] = ''.concat(supports);
  497. } else {
  498. item[1] = '@supports ('.concat(item[4], ') {').concat(item[1], '}');
  499. item[4] = supports;
  500. }
  501. }
  502. list.push(item);
  503. }
  504. };
  505. return list;
  506. };
  507. },
  508. 601: function(module) {
  509. 'use strict';
  510. module.exports = function(i) {
  511. return i[1];
  512. };
  513. }
  514. };
  515. var __webpack_module_cache__ = {};
  516. function __webpack_require__(moduleId) {
  517. var cachedModule = __webpack_module_cache__[moduleId];
  518. if (cachedModule !== undefined) {
  519. return cachedModule.exports;
  520. }
  521. var module = __webpack_module_cache__[moduleId] = {
  522. id: moduleId,
  523. exports: {}
  524. };
  525. __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  526. return module.exports;
  527. }
  528. !function() {
  529. __webpack_require__.n = function(module) {
  530. var getter = module && module.__esModule ? function() {
  531. return module['default'];
  532. } : function() {
  533. return module;
  534. };
  535. __webpack_require__.d(getter, {
  536. a: getter
  537. });
  538. return getter;
  539. };
  540. }();
  541. !function() {
  542. __webpack_require__.d = function(exports, definition) {
  543. for (var key in definition) {
  544. if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  545. Object.defineProperty(exports, key, {
  546. enumerable: true,
  547. get: definition[key]
  548. });
  549. }
  550. }
  551. };
  552. }();
  553. !function() {
  554. __webpack_require__.o = function(obj, prop) {
  555. return Object.prototype.hasOwnProperty.call(obj, prop);
  556. };
  557. }();
  558. var __webpack_exports__ = {};
  559. !function() {
  560. 'use strict';
  561. const external_Swal_namespaceObject = Swal;
  562. var external_Swal_default = __webpack_require__.n(external_Swal_namespaceObject);
  563. const external_Cookies_namespaceObject = Cookies;
  564. var external_Cookies_default = __webpack_require__.n(external_Cookies_namespaceObject);
  565. var auto_task = __webpack_require__(675);
  566. var javascript_utils_umd_min = __webpack_require__(991);
  567. const httpRequest = async (options, times = 0) => {
  568. if (window.TRACE) {
  569. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  570. }
  571. try {
  572. const result = await new Promise(resolve => {
  573. if (options.dataType) {
  574. options.responseType = options.dataType;
  575. }
  576. const requestObj = {
  577. ...{
  578. timeout: 3e4,
  579. ontimeout(data) {
  580. resolve({
  581. result: 'Error',
  582. statusText: 'Timeout',
  583. status: 601,
  584. data: data,
  585. options: options
  586. });
  587. },
  588. onabort(data) {
  589. resolve({
  590. result: 'Error',
  591. statusText: 'Aborted',
  592. status: 602,
  593. data: data,
  594. options: options
  595. });
  596. },
  597. onerror(data) {
  598. resolve({
  599. result: 'Error',
  600. statusText: 'Error',
  601. status: 603,
  602. data: data,
  603. options: options
  604. });
  605. },
  606. onload(data) {
  607. const headers = {};
  608. data.responseHeaders?.split('\n').forEach(header => {
  609. const headerArr = header.trim().split(':');
  610. const name = headerArr.shift()?.trim() || '';
  611. const value = headerArr.join(':').trim();
  612. if (name && value) {
  613. if (headers[name]) {
  614. if (Array.isArray(headers[name])) {
  615. headers[name].push(value);
  616. } else {
  617. headers[name] = [ headers[name], value ];
  618. }
  619. } else {
  620. headers[name] = value;
  621. }
  622. }
  623. });
  624. if (headers['set-cookie'] && !Array.isArray(headers['set-cookie'])) {
  625. headers['set-cookie'] = [ headers['set-cookie'] ];
  626. }
  627. data.responseHeadersText = data.responseHeaders;
  628. data.responseHeaders = headers;
  629. data.finalUrl = data.responseHeaders?.location || data.finalUrl;
  630. if (options.responseType === 'json' && data?.response && typeof data.response !== 'object') {
  631. try {
  632. data.response = JSON.parse(data.responseText);
  633. } catch (error) {}
  634. }
  635. resolve({
  636. result: 'Success',
  637. statusText: 'Load',
  638. status: 600,
  639. data: data,
  640. options: options
  641. });
  642. }
  643. },
  644. ...options
  645. };
  646. GM_xmlhttpRequest(requestObj);
  647. });
  648. if (window.DEBUG) {
  649. console.log('%cAuto-Task[httpRequest]:', 'color:blue', JSON.stringify(result));
  650. }
  651. if (result.status !== 600 && times < 2) {
  652. return await httpRequest(options, times + 1);
  653. }
  654. return result;
  655. } catch (error) {
  656. console.log('%cAuto-Task[httpRequest]:', 'color:red', JSON.stringify({
  657. errorMsg: error,
  658. options: options
  659. }));
  660. throwError(error, 'httpRequest');
  661. return {
  662. result: 'JsError',
  663. statusText: 'Error',
  664. status: 604,
  665. error: error,
  666. options: options
  667. };
  668. }
  669. };
  670. const tools_httpRequest = httpRequest;
  671. const echoLog = ({
  672. type,
  673. text,
  674. html,
  675. id
  676. }) => {
  677. const emptyStatus = {
  678. success: () => emptyStatus,
  679. error: () => emptyStatus,
  680. warning: () => emptyStatus,
  681. info: () => emptyStatus,
  682. view: () => emptyStatus
  683. };
  684. try {
  685. let ele;
  686. if (type) {
  687. switch (type) {
  688. case 'joiningSteamGroup':
  689. case 'leavingSteamGroup':
  690. case 'gettingSteamGroupId':
  691. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/groups/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  692. break;
  693.  
  694. case 'joiningSteamOfficialGroup':
  695. case 'leavingSteamOfficialGroup':
  696. case 'gettingSteamOfficialGroupId':
  697. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/games/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  698. break;
  699.  
  700. case 'subscribingForum':
  701. case 'unsubscribingForum':
  702. case 'gettingForumId':
  703. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/app/${text}/discussions/" target="_blank">${text}</a>]...<font></font></li>`);
  704. break;
  705.  
  706. case 'followingCurator':
  707. case 'unfollowingCurator':
  708. case 'gettingCuratorId':
  709. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/${text?.includes('/') ? text : `curator/${text}`}" target="_blank">${text}</a>]...<font></font></li>`);
  710. break;
  711.  
  712. case 'addingToWishlist':
  713. case 'removingFromWishlist':
  714. case 'followingGame':
  715. case 'unfollowingGame':
  716. case 'gettingSubid':
  717. case 'addingFreeLicense':
  718. case 'requestingPlayTestAccess':
  719. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/app/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  720. break;
  721.  
  722. case 'addingFreeLicenseSubid':
  723. ele = $(`<li>${i18n('addingFreeLicense')}[<a href="https://steamdb.info/sub/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  724. break;
  725.  
  726. case 'favoritingWorkshop':
  727. case 'unfavoritingWorkshop':
  728. case 'gettingWorkshopAppId':
  729. case 'votingUpWorkshop':
  730. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/sharedfiles/filedetails/?id=${text}" target="_blank">
  731. ${text}</a>]...<font></font></li>`);
  732. break;
  733.  
  734. case 'gettingAnnouncementParams':
  735. case 'likingAnnouncement':
  736. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/news/app/${text}/view/${id}" target="_blank">
  737. ${id}</a>]...<font></font></li>`);
  738. break;
  739.  
  740. case 'joiningDiscordServer':
  741. case 'gettingDiscordGuild':
  742. ele = $(`<li>${i18n(type)}[<a href="https://discord.com/invite/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  743. break;
  744.  
  745. case 'leavingDiscordServer':
  746. ele = $(`<li>${i18n(type)}[<a href="https://discord.com/channels/@me/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  747. break;
  748.  
  749. case 'updateDiscordAuth':
  750. ele = $(`<li style="color:red;">${i18n('updateDiscordAuth')}</li>`);
  751. break;
  752.  
  753. case 'followingTwitchChannel':
  754. case 'unfollowingTwitchChannel':
  755. case 'gettingTwitchChannelId':
  756. ele = $(`<li>${i18n(type)}[<a href="https://www.twitch.tv/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  757. break;
  758.  
  759. case 'gettingInsUserId':
  760. case 'followingIns':
  761. case 'unfollowingIns':
  762. ele = $(`<li>${i18n(type)}[<a href="https://www.instagram.com/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  763. break;
  764.  
  765. case 'gettingTwitterUserId':
  766. case 'followingTwitterUser':
  767. case 'unfollowingTwitterUser':
  768. ele = $(`<li>${i18n(type)}[<a href="https://x.com/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  769. break;
  770.  
  771. case 'retweetting':
  772. case 'unretweetting':
  773. ele = $(`<li>${i18n(type)}${text}...<font></font></li>`);
  774. break;
  775.  
  776. case 'joiningReddit':
  777. case 'leavingReddit':
  778. ele = $(`<li>${i18n(type)}[<a href="https://www.reddit.com/r/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  779. break;
  780.  
  781. case 'followingRedditUser':
  782. case 'unfollowingRedditUser':
  783. ele = $(`<li>${i18n(type)}[<a href="https://www.reddit.com/user/${text?.replace('u_', '')}" target="_blank">
  784. ${text?.replace('u_', '')}</a>]...<font></font></li>`);
  785. break;
  786.  
  787. case 'followingYtbChannel':
  788. case 'unfollowingYtbChannel':
  789. ele = $(`<li>${i18n(type)}[<a href="https://www.youtube.com/channel/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  790. break;
  791.  
  792. case 'likingYtbVideo':
  793. case 'unlikingYtbVideo':
  794. ele = $(`<li>${i18n(type)}[<a href="https://www.youtube.com/watch?v=${text}" target="_blank">${text}</a>]...<font></font></li>`);
  795. break;
  796.  
  797. case 'gettingVkId':
  798. case 'joiningVkGroup':
  799. case 'leavingVkGroup':
  800. case 'joiningVkPublic':
  801. case 'leavingVkPublic':
  802. case 'sendingVkWall':
  803. case 'deletingVkWall':
  804. ele = $(`<li>${i18n(type)}[<a href="https://vk.com/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  805. break;
  806.  
  807. case 'visitingLink':
  808. ele = $(`<li>${i18n('visitingLink')}[<a href="${text}" target="_blank">${text}</a>]...<font></font></li>`);
  809. break;
  810.  
  811. case 'verifyingInsAuth':
  812. case 'text':
  813. ele = $(`<li>${i18n(text)}<font></font></li>`);
  814. break;
  815.  
  816. case 'html':
  817. ele = $(text || html);
  818. break;
  819.  
  820. case 'whiteList':
  821. ele = $(`<li><font class="warning">${i18n('skipTask')}[${text}(${id})](${i18n('whiteList')})</font></li>`);
  822. break;
  823.  
  824. case 'globalOptionsSkip':
  825. ele = $(`<li>${i18n('skipTaskOption')}<font class="warning">${text}</font></li>`);
  826. break;
  827.  
  828. default:
  829. ele = $(`<li>${i18n('unKnown')}:${type}(${text})...<font></font></li>`);
  830. break;
  831. }
  832. } else if (text) {
  833. ele = $(`<li>${i18n(text)}<font></font></li>`);
  834. } else if (html) {
  835. ele = $(html);
  836. } else {
  837. ele = $('<li><font></font></li>');
  838. }
  839. ele.addClass('card-text');
  840. $('#auto-task-info').append(ele);
  841. ele[0]?.scrollIntoView();
  842. const font = ele.find('font');
  843. const status = {
  844. font: font,
  845. success(text = 'Success', html = false) {
  846. this.font?.attr('class', '').addClass('success');
  847. html ? this.font?.html(text) : this.font?.text(text);
  848. return this;
  849. },
  850. error(text = 'Error', html = false) {
  851. this.font?.attr('class', '').addClass('error');
  852. html ? this.font?.html(text) : this.font?.text(text);
  853. return this;
  854. },
  855. warning(text = 'Warning', html = false) {
  856. this.font?.attr('class', '').addClass('warning');
  857. html ? this.font?.html(text) : this.font?.text(text);
  858. return this;
  859. },
  860. info(text = 'Info', html = false) {
  861. this.font?.attr('class', '').addClass('info');
  862. html ? this.font?.html(text) : this.font?.text(text);
  863. return this;
  864. },
  865. view() {
  866. this.font?.[0].scrollIntoView();
  867. return this;
  868. }
  869. };
  870. return status;
  871. } catch (error) {
  872. throwError(error, 'echoLog');
  873. return emptyStatus;
  874. }
  875. };
  876. const scripts_echoLog = echoLog;
  877. const unique = array => {
  878. try {
  879. return [ ...new Set(array) ];
  880. } catch (error) {
  881. throwError(error, 'unique');
  882. return [];
  883. }
  884. };
  885. const delay = (time = 1e3) => new Promise(resolve => {
  886. setTimeout(() => {
  887. resolve(true);
  888. }, time);
  889. });
  890. const getRedirectLink = async link => {
  891. try {
  892. if (!link) {
  893. return null;
  894. }
  895. const redirectLinksCache = GM_getValue('redirectLinks') || {};
  896. if (redirectLinksCache[link]) {
  897. redirectLinksCache[link];
  898. }
  899. return await tools_httpRequest({
  900. url: link,
  901. method: 'GET'
  902. }).then(({
  903. data
  904. }) => {
  905. if (data?.finalUrl) {
  906. redirectLinksCache[link] = data.finalUrl;
  907. GM_setValue('redirectLinks', redirectLinksCache);
  908. return data.finalUrl;
  909. }
  910. return null;
  911. });
  912. } catch (error) {
  913. throwError(error, 'getRedirectLink');
  914. return null;
  915. }
  916. };
  917. const visitLink = async (link, options) => {
  918. try {
  919. const logStatus = scripts_echoLog({
  920. type: 'visitLink',
  921. text: link
  922. });
  923. return await tools_httpRequest({
  924. url: link,
  925. method: 'GET',
  926. ...options
  927. }).then(({
  928. result,
  929. statusText,
  930. status
  931. }) => {
  932. if (result === 'Success') {
  933. logStatus.success();
  934. return true;
  935. }
  936. logStatus.error(`${result}:${statusText}(${status})`);
  937. return false;
  938. });
  939. } catch (error) {
  940. throwError(error, 'visitLink');
  941. return false;
  942. }
  943. };
  944. const getUrlQuery = url => {
  945. try {
  946. const query = {};
  947. if (url) {
  948. if (url.includes('?')) {
  949. url.split('?')[1].replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  950. query[key] = value;
  951. return str;
  952. });
  953. }
  954. } else {
  955. window.location.search.replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  956. query[key] = value;
  957. return str;
  958. });
  959. }
  960. return query;
  961. } catch (error) {
  962. throwError(error, 'getUrlQuery');
  963. return {};
  964. }
  965. };
  966. const getUuid = () => {
  967. const uuidUrl = URL.createObjectURL(new Blob()).toString();
  968. return uuidUrl.slice(uuidUrl.lastIndexOf('/') + 1);
  969. };
  970. const stringToColour = str => {
  971. try {
  972. let hash = 0;
  973. for (let i = 0; i < str.length; i++) {
  974. hash = str.charCodeAt(i) + ((hash << 5) - hash);
  975. }
  976. let colour = '#';
  977. for (let i = 0; i < 3; i++) {
  978. const value = hash >> i * 8 & 255;
  979. colour += `00${value.toString(16)}`.slice(-2);
  980. }
  981. return colour;
  982. } catch (error) {
  983. throwError(error, 'stringToColour');
  984. return '#fff';
  985. }
  986. };
  987. const debug = (log, data) => {
  988. if (!window.DEBUG) {
  989. return;
  990. }
  991. console.log('%c%s', 'color:#a7a7a7', `Auto-Task[Debug]: ${log}`);
  992. if (data) {
  993. console.log('%c%s', 'color:#a7a7a7', 'Auto-Task[Debug]: ', data);
  994. }
  995. };
  996. const defaultGlobalOptions = {
  997. doTask: {
  998. discord: {
  999. servers: true
  1000. },
  1001. instagram: {
  1002. users: true
  1003. },
  1004. twitch: {
  1005. channels: true
  1006. },
  1007. twitter: {
  1008. users: true,
  1009. retweets: true
  1010. },
  1011. vk: {
  1012. names: true
  1013. },
  1014. youtube: {
  1015. channels: true,
  1016. likes: true
  1017. },
  1018. reddit: {
  1019. reddits: true
  1020. },
  1021. steam: {
  1022. groups: true,
  1023. officialGroups: true,
  1024. wishlists: true,
  1025. follows: true,
  1026. forums: true,
  1027. workshops: true,
  1028. curators: true,
  1029. workshopVotes: true,
  1030. announcements: true,
  1031. licenses: true,
  1032. playtests: true
  1033. }
  1034. },
  1035. undoTask: {
  1036. discord: {
  1037. servers: true
  1038. },
  1039. instagram: {
  1040. users: true
  1041. },
  1042. twitch: {
  1043. channels: true
  1044. },
  1045. twitter: {
  1046. users: true,
  1047. retweets: true
  1048. },
  1049. vk: {
  1050. names: true
  1051. },
  1052. youtube: {
  1053. channels: true,
  1054. likes: true
  1055. },
  1056. reddit: {
  1057. reddits: true
  1058. },
  1059. steam: {
  1060. groups: true,
  1061. officialGroups: true,
  1062. wishlists: true,
  1063. follows: true,
  1064. forums: true,
  1065. workshops: true,
  1066. curators: true
  1067. }
  1068. },
  1069. ASF: {
  1070. AsfEnabled: false,
  1071. AsfIpcUrl: '',
  1072. AsfIpcPassword: '',
  1073. AsfBotname: 'asf'
  1074. },
  1075. position: {
  1076. buttonSideX: 'right',
  1077. buttonSideY: 'top',
  1078. buttonDistance: '15,30',
  1079. showButtonSideX: 'right',
  1080. showButtonSideY: 'top',
  1081. showButtonDistance: '15,30',
  1082. logSideX: 'right',
  1083. logSideY: 'bottom',
  1084. logDistance: '10,10'
  1085. },
  1086. hotKey: {
  1087. doTaskKey: 'alt + d',
  1088. undoTaskKey: 'alt + u',
  1089. toggleLogKey: 'alt + l'
  1090. },
  1091. other: {
  1092. twitterVerifyId: '783214',
  1093. youtubeVerifyChannel: 'UCrXUsMBcfTVqwAS7DKg9C0Q',
  1094. autoUpdateSource: 'jsdelivr',
  1095. language: 'zh',
  1096. checkLogin: true,
  1097. checkLeftKey: true,
  1098. defaultShowButton: true,
  1099. defaultShowLog: true,
  1100. debug: false,
  1101. receivePreview: true
  1102. }
  1103. };
  1104. const userDefinedGlobalOptions = GM_getValue('globalOptions') || {};
  1105. const assignObject = (obj1, obj2) => {
  1106. try {
  1107. const newObj = {};
  1108. for (const [ key, value ] of Object.entries(obj1)) {
  1109. if (Object.prototype.toString.call(value) === '[object Object]' && Object.prototype.toString.call(obj2[key]) === '[object Object]') {
  1110. newObj[key] = assignObject(value, obj2[key]);
  1111. } else {
  1112. newObj[key] = obj2[key] ?? value;
  1113. }
  1114. }
  1115. return newObj;
  1116. } catch (error) {
  1117. throwError(error, 'assignObject');
  1118. return defaultGlobalOptions;
  1119. }
  1120. };
  1121. const globalOptions = assignObject(defaultGlobalOptions, userDefinedGlobalOptions);
  1122. const saveData = () => {
  1123. try {
  1124. const data = {};
  1125. $('#globalOptionsForm').serializeArray().map(value => {
  1126. data[value.name] = value.value;
  1127. return value;
  1128. });
  1129. $.makeArray($('#globalOptionsForm input')).map(element => {
  1130. const name = $(element).attr('name');
  1131. const keys = name.split('.');
  1132. if (keys.length === 3) {
  1133. globalOptions[keys[0]][keys[1]][keys[2]] = data[name] ? data[name] === 'on' ? true : data[name] : false;
  1134. } else if (keys.length === 2) {
  1135. globalOptions[keys[0]][keys[1]] = data[name] ? data[name] === 'on' ? true : data[name] : false;
  1136. }
  1137. return element;
  1138. });
  1139. GM_setValue('globalOptions', globalOptions);
  1140. external_Swal_default().fire({
  1141. title: i18n('changeGlobalOptionsSuccess'),
  1142. icon: 'success'
  1143. });
  1144. } catch (error) {
  1145. throwError(error, 'saveData');
  1146. }
  1147. };
  1148. const changeGlobalOptions = showType => {
  1149. try {
  1150. let globalOptionsForm = `<form id="globalOptionsForm" class="auto-task-form">
  1151. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  1152. for (const [ type, data1 ] of Object.entries(globalOptions)) {
  1153. for (const [ option, data2 ] of Object.entries(data1)) {
  1154. if ([ 'other', 'position', 'hotKey', 'ASF' ].includes(type)) {
  1155. if (typeof data2 === 'boolean') {
  1156. globalOptionsForm += `<tr style="background-color: ${stringToColour(type)}44">${Object.keys(data1).indexOf(option) === 0 ? `<th rowspan="${Object.keys(data1).length}">${i18n(type)}</th>` : ''}<td>${i18n(option)}</td><td><label><input type="checkbox" name="${type}.${option}"${data2 ? ' checked="checked"' : ''}/><span><i></i></span></label></td></tr>`;
  1157. } else {
  1158. globalOptionsForm += `<tr style="background-color: ${stringToColour(type)}44">${Object.keys(data1).indexOf(option) === 0 ? `<th rowspan="${Object.keys(data1).length}" style="background-color: ${stringToColour(type)}66">${i18n(type)}</th>` : ''}<td>${i18n(option)}</td><td><input class="editOption" type="text" name="${type}.${option}" value="${data2}"/></td></tr>`;
  1159. }
  1160. } else {
  1161. for (const [ socialType, data3 ] of Object.entries(data2)) {
  1162. globalOptionsForm += `<tr style="background-color: ${stringToColour(option)}66">${Object.keys(data1).indexOf(option) === 0 ? `<th rowspan="${Object.keys(data1).map(key => Object.keys(data1[key]).length).reduce((acr, cur) => acr + cur)}" style="background-color: ${stringToColour(type)}66">${i18n(type)}</th>` : ''}<td>${option}.${i18n(socialType)}</td><td><label><input type="checkbox" name="${type}.${option}.${socialType}"${data3 ? ' checked="checked"' : ''}/><span><i></i></span></label></td></tr>`;
  1163. }
  1164. }
  1165. }
  1166. }
  1167. globalOptionsForm += '</tbody></table></form>';
  1168. if (showType === 'swal') {
  1169. external_Swal_default().fire({
  1170. title: i18n('globalOptions'),
  1171. html: globalOptionsForm,
  1172. showConfirmButton: true,
  1173. confirmButtonText: i18n('save'),
  1174. showCancelButton: true,
  1175. cancelButtonText: i18n('close')
  1176. }).then(({
  1177. isConfirmed
  1178. }) => {
  1179. if (isConfirmed) {
  1180. saveData();
  1181. }
  1182. });
  1183. } else {
  1184. $('body').append(`<h2>${i18n('globalOptions')}</h2>${globalOptionsForm}`);
  1185. }
  1186. } catch (error) {
  1187. throwError(error, 'changeGlobalOptions');
  1188. }
  1189. };
  1190. const data = {
  1191. website: '网站',
  1192. type: '类型',
  1193. edit: '编辑',
  1194. whiteList: '白名单',
  1195. skipTask: '跳过撤销任务',
  1196. whiteListOptions: '白名单设置',
  1197. changeWhiteListOption: '设置白名单(%0)',
  1198. whiteListNotFound: '找不到此项白名单: %0',
  1199. changeWhiteListSuccess: '白名单修改成功,刷新生效!',
  1200. changeWebsiteOptions: '网站设置',
  1201. changeGlobalOptions: '全局设置',
  1202. ok: '是',
  1203. save: '保存',
  1204. close: '关闭',
  1205. return: '返回',
  1206. option: '选项',
  1207. value: '值',
  1208. websiteOptions: '当前网站设置',
  1209. changeWebsiteOptionsSuccess: '更改当前网站设置成功,刷新生效!',
  1210. changeGlobalOptionsSuccess: '更改全局设置成功,刷新生效!',
  1211. needLogin: '请先登录!',
  1212. getTasksInfo: '正在获取并处理任务信息...',
  1213. gettingKey: '正在获取Key...',
  1214. verifyingTask: '正在验证任务',
  1215. notice: '自动任务脚本提醒',
  1216. noKeysLeft: '此页面已经没有剩余key了,是否关闭?',
  1217. giveawayEnded: '此活动已结束,是否关闭?',
  1218. giveawayNotWork: '此活动因某些原因(已结束/暂停/未开始...)不可用(如果是脚本误判请及时反馈),是否关闭?',
  1219. confirm: '确定',
  1220. cancel: '取消',
  1221. unKnown: '未知',
  1222. unKnownTaskType: '未识别的任务',
  1223. doing: '正在做任务',
  1224. allTasksComplete: '所有任务已完成!',
  1225. getTaskIdFailed: '获取任务Id失败!',
  1226. initSuccess: '%0 初始化成功!',
  1227. initFailed: '%0 初始化失败!',
  1228. errorLink: '链接错误: %0',
  1229. needInit: '请先初始化',
  1230. verifyingAuth: '正在验证%0凭证...',
  1231. updatingAuth: '正在更新%0凭证...',
  1232. refreshingToken: '正在刷新%0凭证...',
  1233. settingToken: '正在设置%0凭证...',
  1234. steamStoreTab: 'Steam商店(弹窗)',
  1235. steamCommunityTab: 'Steam社区(弹窗)',
  1236. initing: '正在初始化...',
  1237. getFailed: '获取%0失败!',
  1238. checkLoginFailed: '检测登录状态失败!',
  1239. checkLeftKeyFailed: '检测剩余Key失败!',
  1240. userId: '用户Id',
  1241. joiningGiveaway: '正在加入赠Key',
  1242. needJoinGiveaway: '需要先加入赠Key',
  1243. cannotUndo: '此网站不支持取消任务',
  1244. verifyAuth: '正在验证 %0 凭证...',
  1245. closePageNotice: '如果此页面没有自动关闭,请自行关闭本页面。',
  1246. errorReport: '检测到脚本报错,是否前往反馈BUG?',
  1247. visitingLink: '正在访问链接: ',
  1248. doTask: '做任务',
  1249. undoTask: '撤销任务',
  1250. verifyTask: '验证任务',
  1251. getKey: '获取Key',
  1252. selectAll: '全选',
  1253. selectNone: '全不选',
  1254. invertSelect: '反选',
  1255. doFreeTask: '加入免费赠品',
  1256. doPointTask: '加入点数赠品',
  1257. skipTaskOption: '设置中已配置跳过任务',
  1258. other: '其他',
  1259. globalOptions: '全局设置',
  1260. checkLogin: '登录检测</br>需要登录的网站自动登录,部分网站支持',
  1261. checkLeftKey: '剩余Key检测</br>赠Key活动结束提示是否关闭,部分网站支持',
  1262. twitterVerifyId: '通过尝试关注该账号验证Twitter凭证</br>默认为Twitter官方帐号 783214</br>不想关注官方账号可以改为自己的帐号',
  1263. youtubeVerifyChannel: '通过尝试订阅该频道验证YouTube凭证</br>默认为YouTube官方频道 UCrXUsMBcfTVqwAS7DKg9C0Q</br>不想关注官方频道可以改为自己的频道',
  1264. autoUpdateSource: '更新源</br>github: 需代理,实时更新</br>jsdelivr: 可不用代理,更新有延迟</br>standby: 备用</br>auto: 依次使用github, jsdelivr, standby源进行尝试更新',
  1265. saveGlobalOptions: '保存设置',
  1266. settingPage: '设置页面',
  1267. name: '名称',
  1268. version: '版本',
  1269. scriptManager: '脚本管理器',
  1270. script: '脚本',
  1271. environment: '环境',
  1272. os: '系统',
  1273. browser: '浏览器',
  1274. getId: '获取 %0 id',
  1275. getTwitterUserId: '获取Twitter用户id(获取id功能仅在设置页面可用)',
  1276. getYoutubeChannelId: '获取Youtube频道id(获取id功能仅在设置页面可用)',
  1277. showButton: '显示按钮',
  1278. hideButton: '隐藏按钮',
  1279. showLog: '显示日志',
  1280. hideLog: '隐藏日志',
  1281. defaultShowButton: '默认显示按钮',
  1282. defaultShowLog: '默认显示日志',
  1283. debug: '输出调试日志,不要开启此选项!',
  1284. receivePreview: '接收预览版更新',
  1285. position: '组件位置',
  1286. buttonSideX: '按钮区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1287. buttonSideY: '按钮区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1288. buttonDistance: '按钮区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1289. showButtonSideX: '显示按钮水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1290. showButtonSideY: '显示按钮垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1291. showButtonDistance: '显示按钮距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1292. logSideX: '日志区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1293. logSideY: '日志区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1294. logDistance: '日志区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1295. hotKey: '快捷键',
  1296. doTaskKey: '做任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1297. undoTaskKey: '撤销任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1298. toggleLogKey: '显示/隐藏日志快捷键</br>(实时预览功能仅在设置页面可用)',
  1299. tasksHistory: '任务历史',
  1300. clearHistory: '清空历史',
  1301. clearHistoryFinished: '已清空任务历史!',
  1302. deleteTask: '删除任务',
  1303. lastChangeTime: '最后一次修改时间',
  1304. clearTaskFinished: '删除以下任务完成!',
  1305. clearTaskFailed: '删除任务失败,没有找到任务名!',
  1306. syncData: '数据同步',
  1307. settingData: '正在上传数据...',
  1308. gettingData: '正在获取数据...',
  1309. help: '帮助',
  1310. fileName: '文件名',
  1311. upload2gist: '同步到Gist',
  1312. downloadFromGist: '从Gist同步',
  1313. saveAndTest: '保存配置并测试',
  1314. testSuccess: '测试成功!',
  1315. testFailed: '测试失败!',
  1316. saveAndTestNotice: '请先保存配置并测试!',
  1317. processingData: '正在处理数据...',
  1318. updatingData: '正在上传数据...',
  1319. syncDataSuccess: '同步数据成功!',
  1320. syncDataFailed: '同步数据失败,请在控制台查看错误信息!',
  1321. downloadingData: '正在下载数据...',
  1322. checkedNoData: '没有检测到远程数据,请确认配置是否正确!',
  1323. savingData: '正在保存数据...',
  1324. syncHistory: '同步任务历史',
  1325. checkUpdateFailed: '检测更新失败',
  1326. newVersionNotice: '检测到新版本V%0, <a class="high-light" href="%1" target="_blank">点此更新</a>',
  1327. language: '语言</br>目前仅支持zh: 中文, en: 英文',
  1328. gistOptions: 'Gist 设置',
  1329. swalNotice: '检测到您第一次安装V4版本脚本,请前往阅读用前必读内容!',
  1330. echoNotice: '检测到您第一次安装V4版本脚本,请<a class="high-light" href="%0" target="_blank">点此前往</a>阅读用前必读内容!',
  1331. noticeLink: 'https://auto-task-doc.js.org/guide/#用前必读',
  1332. toGithub: '前往Github反馈',
  1333. toKeylol: '前往其乐论坛反馈',
  1334. copySuccess: '错误信息已复制到剪切板,是否前往其乐论坛反馈?',
  1335. copyFailed: '请复制下方错误信息后前往Keylol论坛反馈!',
  1336. updateText: '%0 版本更新内容:',
  1337. Active: '进行中',
  1338. Ended: '已结束',
  1339. Banned: '已封禁',
  1340. Paused: '已暂停',
  1341. notStart: '未开始',
  1342. noRemoteData: '检测到远程无数据',
  1343. errorRemoteDataFormat: '远程数据格式错误',
  1344. updateHistory: '历史更新记录<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">点此查看</a>',
  1345. AsfEnabled: '使用ASF做Steam相关任务(需<a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a>插件)',
  1346. AsfIpcUrl: 'ASF IPC 地址',
  1347. AsfIpcPassword: 'ASF IPC 密码',
  1348. versionNotMatched: '脚本管理器版本过低,需TamperMonkey >= 5.2.0或TamperMonkey Beta >= 5.2.6196',
  1349. groups: '组',
  1350. officialGroups: '官方组',
  1351. wishlists: '愿望单',
  1352. follows: '游戏关注',
  1353. forums: '论坛',
  1354. workshops: '创意工坊收藏',
  1355. curators: '鉴赏家',
  1356. workshopVotes: '创意工坊点赞',
  1357. announcements: '社区通知',
  1358. steamCommunity: 'Steam社区',
  1359. steamStore: 'Steam商店',
  1360. licenses: '入库免费游戏',
  1361. playtests: '请求访问权限',
  1362. needLoginSteamStore: '请先<a href="https://store.steampowered.com/login/" target="_blank">登录Steam商店</a>',
  1363. needLoginSteamCommunity: '请先<a href="https://steamcommunity.com/login/home/" target="_blank">登录Steam社区</a>',
  1364. joiningSteamGroup: '正在加入Steam组',
  1365. leavingSteamGroup: '正在退出Steam组',
  1366. gettingSteamGroupId: '正在获取Steam组Id',
  1367. joiningSteamOfficialGroup: '正在加入Steam官方组',
  1368. leavingSteamOfficialGroup: '正在退出Steam官方组',
  1369. gettingSteamOfficialGroupId: '正在获取Steam官方组Id',
  1370. subscribingForum: '正在订阅Steam论坛',
  1371. unsubscribingForum: '正在取消订阅Steam论坛',
  1372. gettingForumId: '正在获取Steam论坛Id',
  1373. followingCurator: '正在关注Steam鉴赏家',
  1374. unfollowingCurator: '正在取关Steam鉴赏家',
  1375. gettingCuratorId: '正在获取Steam鉴赏家Id',
  1376. addingToWishlist: '正在添加游戏到Steam愿望单',
  1377. removingFromWishlist: '正在从Steam愿望单移除游戏',
  1378. followingGame: '正在关注Steam游戏',
  1379. unfollowingGame: '正在取关Steam游戏',
  1380. favoritingWorkshop: '正在收藏Steam创意工坊物品',
  1381. unfavoritingWorkshop: '正在取消收藏Steam创意工坊物品',
  1382. gettingWorkshopAppId: '正在获取Steam创意工坊物品Id',
  1383. votingUpWorkshop: '正在点赞Steam创意工坊物品',
  1384. gettingAnnouncementParams: '正在获取Steam通知信息',
  1385. likingAnnouncement: '正在点赞Steam通知',
  1386. changingArea: '正在更换Steam地区: %0...',
  1387. notNeededChangeArea: '当前地区不需要更换',
  1388. noAnotherArea: '请检测是否开启正确开启代理',
  1389. gettingAreaInfo: '正在获取Steam地区信息...',
  1390. changeAreaNotice: '疑似锁区游戏,尝试换区执行',
  1391. steamFinishNotice: 'Steam任务完成,尝试将购物车地区换回',
  1392. gettingSubid: '正在获取游戏subid',
  1393. addingFreeLicense: '正在入库',
  1394. missParams: '缺少参数',
  1395. gettingLicenses: '正在获取Licenses...',
  1396. requestingPlayTestAccess: '正在请求访问权限',
  1397. tryChangeAreaNotice: '此功能无法检测游戏是否限区,因此会尝试换区后再入库,换区失败也不影响后续入库',
  1398. gettingUserLink: '正在获取Steam用户社区链接...',
  1399. retry: '重试',
  1400. owned: '已拥有',
  1401. redirect: '重定向',
  1402. noSubid: '无法获取,跳过',
  1403. initingASF: '正在初始化ASF...',
  1404. servers: '服务器',
  1405. joiningDiscordServer: '正在加入Discord服务器',
  1406. leavingDiscordServer: '正在退出Discord服务器',
  1407. gettingDiscordGuild: '正在获取Discord服务器Id',
  1408. getDiscordAuthFailed: '获取Discord凭证失败,请检测Discord帐号是否已登录',
  1409. discordImportantNotice: '重要提醒!!!',
  1410. discordImportantNoticeText: '由于Discord网站后台更新,目前使用此脚本加组后可能会导致Discord帐号被强制退出,且需要两步验证才能正常登录,请谨慎使用!!!',
  1411. continue: '继续',
  1412. skipDiscordTask: '跳过Discord任务',
  1413. continueAndDontRemindAgain: '继续且不再提醒',
  1414. users: '用户',
  1415. loginIns: '请先<a href="https://www.instagram.com/accounts/login/" target="_blank">登录Instagram</a>',
  1416. insBanned: '您的Instagram账户已被封禁',
  1417. verifyingInsAuth: '正在验证Instagram凭证...',
  1418. gettingInsUserId: '正在获取Instagram用户Id',
  1419. followingIns: '正在关注Instagram用户',
  1420. unfollowingIns: '正在取关Instagram用户',
  1421. reddits: '社区/用户',
  1422. loginReddit: '请先<a href="https://www.reddit.com/login/" target="_blank">登录Reddit</a>',
  1423. changingRedditVersion: '正在切换Reddit为新版页面...',
  1424. joiningReddit: '正在加入Reddit社区',
  1425. leavingReddit: '正在退出Reddit社区',
  1426. followingRedditUser: '正在关注Reddit用户',
  1427. unfollowingRedditUser: '正在取关Reddit用户',
  1428. channels: '频道',
  1429. followingTwitchChannel: '正在关注Twitch频道',
  1430. unfollowingTwitchChannel: '正在取关Twitch频道',
  1431. gettingTwitchChannelId: '正在获取Twitch频道Id',
  1432. checkingTwitchIntegrity: '正在检查Twitch完整性...',
  1433. twitterUser: '推特用户',
  1434. retweets: '转推',
  1435. gettingTwitterUserId: '正在获取推特用户Id',
  1436. followingTwitterUser: '正在关注推特用户',
  1437. unfollowingTwitterUser: '正在取关推特用户',
  1438. retweetting: '正在转推',
  1439. unretweetting: '正在撤销转推',
  1440. names: '组/社区/动态',
  1441. loginVk: '请先<a href="https://vk.com/login/" target="_blank">登录Vk</a>',
  1442. gettingVkId: '正在获取Vk任务Id',
  1443. joiningVkGroup: '正在加入Vk组',
  1444. leavingVkGroup: '正在退出Vk组',
  1445. joiningVkPublic: '正在加入Vk社区',
  1446. leavingVkPublic: '正在退出Vk社区',
  1447. sendingVkWall: '正在转发Vk动态',
  1448. deletingVkWall: '正在撤销转发Vk动态',
  1449. youtubeChannel: 'YouTube频道',
  1450. likes: '点赞',
  1451. loginYtb: '请先<a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">登录YouTube</a>',
  1452. tryUpdateYtbAuth: '请尝试<a href="https://www.youtube.com/#auth" target="_blank">更新YouTube凭证</a>',
  1453. gettingYtbToken: '正在获取YouTube Token...',
  1454. followingYtbChannel: '正在订阅YouTube频道',
  1455. unfollowingYtbChannel: '正在退订YouTube频道',
  1456. likingYtbVideo: '正在点赞YouTube视频',
  1457. unlikingYtbVideo: '正在取消点赞YouTube视频',
  1458. giveKeyNoticeBefore: '每次验证间隔15s',
  1459. giveKeyNoticeAfter: '如果没有key, 请在<a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>查看',
  1460. noPoints: '点数不够,跳过抽奖',
  1461. getNeedPointsFailed: '获取所需点数失败,跳过抽奖',
  1462. joiningLottery: '正在加入抽奖',
  1463. doingGleamTask: '正在做Gleam任务...',
  1464. gettingGleamLink: '正在获取Gleam任务链接...',
  1465. gleamTaskNotice: '如果此页面长时间未关闭,请完成任一任务后自行关闭!',
  1466. verifiedGleamTasks: '已尝试验证所有任务,验证失败的任务请尝试手动验证或完成!',
  1467. campaign: '检测到人机验证,请完成验证后重新验证任务!',
  1468. gsNotice: '为避免得到"0000-0000-0000"key, 已自动屏蔽"Grab Key"按钮,获取key时请关闭脚本!',
  1469. giveeClubVerifyNotice: '正在验证任务...',
  1470. giveeClubVerifyFinished: '请等待验证完成后自行加入赠Key',
  1471. doingKeyhubTask: '正在做Keyhub任务...',
  1472. SweepWidgetNotice: '正在处理并验证任务,每次验证任务有1~3s间隔防止触发验证过快警告...',
  1473. tasksNotCompleted: '任务未完成',
  1474. confirmingTask: '正在跳过警告页面...'
  1475. };
  1476. const zh_CN = data;
  1477. const en_US_data = {
  1478. website: 'Website',
  1479. type: 'Type',
  1480. edit: 'Edit',
  1481. whiteList: 'Whitelist',
  1482. skipTask: 'Skip undo task',
  1483. whiteListOptions: 'Whitelist options',
  1484. changeWhiteListOption: 'Whitelist option(%0)',
  1485. whiteListNotFound: 'Cannot find this whitelist: %0',
  1486. changeWhiteListSuccess: 'The whitelist is successfully modified, and the page refresh will take effect!',
  1487. changeWebsiteOptions: 'Website options',
  1488. changeGlobalOptions: 'Global options',
  1489. ok: 'OK',
  1490. save: 'Save',
  1491. close: 'Close',
  1492. return: 'Return',
  1493. option: 'Option',
  1494. value: 'Value',
  1495. websiteOptions: 'Current website settings',
  1496. changeWebsiteOptionsSuccess: 'The current website setting is changed successfully, and the page refresh will take effect!',
  1497. changeGlobalOptionsSuccess: 'The global setting is changed successfully, and the refresh will take effect!',
  1498. needLogin: 'Please log in first!',
  1499. getTasksInfo: 'Obtaining and processing task information...',
  1500. gettingKey: 'Getting Key...',
  1501. verifyingTask: 'Verifying task',
  1502. notice: 'Automatic task script notice',
  1503. noKeysLeft: 'There are no more keys left on this page. Do you want to close it?',
  1504. giveawayEnded: 'This event has ended, do you want to close it?',
  1505. giveawayNotWork: 'This activity is unavailable for some reasons (banned/ended/paused/not started...)' + ' (if it is a script misjudgment, please give us feedback in time), is it closed?',
  1506. confirm: 'Confirm',
  1507. cancel: 'Cancel',
  1508. unKnown: 'Unknown',
  1509. unKnownTaskType: 'Unrecognized task',
  1510. doing: 'Doing a task',
  1511. allTasksComplete: 'All tasks have been completed!',
  1512. getTaskIdFailed: 'Failed to obtain task Id!',
  1513. initSuccess: '%0 was initialized successfully!',
  1514. initFailed: '%0 initialization failed!',
  1515. errorLink: 'Link error: %0',
  1516. needInit: 'Please initialize first',
  1517. verifyingAuth: 'Verifying %0 token...',
  1518. updatingAuth: 'Update %0 token...',
  1519. refreshingToken: 'Refreshing %0 token...',
  1520. settingToken: 'Setting %0 token...',
  1521. steamStoreTab: 'Steam store (new tab)',
  1522. steamCommunityTab: 'Steam community(new tab)',
  1523. initing: 'Initializing...',
  1524. getFailed: 'Failed to get %0!',
  1525. checkLoginFailed: 'Failed to detect login status!',
  1526. checkLeftKeyFailed: 'Failed to detect the remaining keys!',
  1527. userId: 'User Id',
  1528. joiningGiveaway: 'Joining giveaway',
  1529. needJoinGiveaway: 'Need to join the giveaway first',
  1530. cannotUndo: 'This website does not support canceling tasks',
  1531. verifyAuth: 'Verifying %0 token...',
  1532. closePageNotice: 'f this page does not close automatically, please close this page yourself.',
  1533. errorReport: 'A script error is detected, do you want to report the BUG?',
  1534. visitingLink: 'Visiting link: ',
  1535. doTask: 'DoTask',
  1536. undoTask: 'UndoTask',
  1537. verifyTask: 'Verify',
  1538. getKey: 'GetKey',
  1539. selectAll: 'SelectAll',
  1540. selectNone: 'SelectNone',
  1541. invertSelect: 'InvertSelect',
  1542. doFreeTask: 'FreeTask',
  1543. doPointTask: 'PointTask',
  1544. skipTaskOption: 'Skip task has been configured in the settings',
  1545. other: 'Other',
  1546. globalOptions: 'Global Options',
  1547. checkLogin: 'Login detection</br>Need to log in to the website automatically log in, part of this website supports.',
  1548. checkLeftKey: 'Key remaining detection</br>The end of the giveaway event prompts whether to close or not, part of this website supports.',
  1549. twitterVerifyId: 'Verify Twitter token by trying to follow the account.</br>The default is the official Twitter account 783214.</br>' + 'If you don\'t want to follow the official account, you can change it to your own account.',
  1550. youtubeVerifyChannel: 'Verify YouTube token by trying to subscribe to the channel.</br>' + 'The default is the official YouTube channel UCrXUsMBcfTVqwAS7DKg9C0Q.</br>' + 'If you don\'t want to follow the official channel, you can change it to your own channel.',
  1551. autoUpdateSource: 'The source to update</br>github: Fast update.</br>jsdelivr: Update is delayed.</br>' + 'standby: Standby source.</br>auto: Try to update using github, jsdelivr, standby sources in turn.',
  1552. saveGlobalOptions: 'SaveSettings',
  1553. settingPage: 'Setting Page',
  1554. name: 'Name',
  1555. version: 'Version',
  1556. scriptManager: 'Script Manager',
  1557. script: 'Script',
  1558. environment: 'Environment',
  1559. os: 'OS',
  1560. browser: 'Browser',
  1561. getId: 'Get %0 id',
  1562. getTwitterUserId: 'Get Twitter user id (Get id function is only available on the settings page).',
  1563. getYoutubeChannelId: 'Get Youtube channel id (Get id function is only available on the settings page).',
  1564. showButton: 'ShowButton',
  1565. hideButton: 'HideButton',
  1566. showLog: 'ShowLog',
  1567. hideLog: 'HideLog',
  1568. defaultShowButton: 'Default display button',
  1569. defaultShowLog: 'Display log by default',
  1570. debug: 'Output debug log, do not enable this option!',
  1571. receivePreview: 'Receive preview updates',
  1572. position: 'Component position',
  1573. buttonSideX: 'Horizontal positioning of the button area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1574. buttonSideY: 'The button area is positioned in the vertical direction (real-time preview function is only available on the settings page).' + '</br>top: top | bottom: bottom',
  1575. buttonDistance: 'The distance between the button area and the edge (the real-time preview function is only available on the setting page).' + '</br> Format: X distance, Y distance',
  1576. showButtonSideX: 'ShowButton horizontal positioning (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1577. showButtonSideY: 'ShowButton vertical positioning (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  1578. showButtonDistance: 'The distance between the ShowButton and the edge (real-time preview function is only available on the setting page).' + '</br> Format: X distance, Y distance',
  1579. logSideX: 'Horizontal positioning of the log area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1580. logSideY: 'Vertical positioning of the log area (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  1581. logDistance: 'The distance between the log area and the edge (the real-time preview function is only available on the setting page).' + '</br> Format: X distance, Y distance',
  1582. hotKey: 'Shortcut key',
  1583. doTaskKey: 'DoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  1584. undoTaskKey: 'UndoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  1585. toggleLogKey: 'ShowLog/HideLog shortcut keys</br> (real-time preview function is only available on the settings page).',
  1586. tasksHistory: 'TasksHistory',
  1587. clearHistory: 'Clear history',
  1588. clearHistoryFinished: 'The mission history has been cleared!',
  1589. deleteTask: 'Delete task',
  1590. lastChangeTime: 'Last Change Time',
  1591. clearTaskFinished: 'Delete the following tasks completed!',
  1592. clearTaskFailed: 'Failed to delete the task, the task name was not found!',
  1593. syncData: 'DataSync',
  1594. settingData: 'Uploading data...',
  1595. gettingData: 'Getting data...',
  1596. help: 'Help',
  1597. fileName: 'Filename',
  1598. upload2gist: 'Sync to Gist',
  1599. downloadFromGist: 'Sync from Gist',
  1600. saveAndTest: 'Save configuration and test',
  1601. testSuccess: 'Test success!',
  1602. testFailed: 'Test failed!',
  1603. saveAndTestNotice: 'Please save the configuration and test first!',
  1604. processingData: 'Processing data...',
  1605. updatingData: 'Uploading data...',
  1606. syncDataSuccess: 'Synchronized data successfully!',
  1607. syncDataFailed: 'Failed to synchronize data, please check the error message on the console!',
  1608. downloadingData: 'Downloading data...',
  1609. checkedNoData: 'No remote data is detected, please confirm whether the configuration is correct!',
  1610. savingData: 'Saving data...',
  1611. syncHistory: 'Synchronize tasks history',
  1612. checkUpdateFailed: 'Check update failed',
  1613. newVersionNotice: 'Checked a new version V%0, <a class="high-light" href="%1" target="_blank">click to update</a>',
  1614. language: 'Language</br> Currently only supports zh: Chinese, en: English',
  1615. gistOptions: 'Gist Settings',
  1616. swalNotice: 'It is detected that you are installing the V4 version script for the first time' + ', please go to read the READ ME FIRST content before use!',
  1617. echoNotice: 'It is detected that you are installing the V4 version script for the first time' + ', please <a class="high-light" href="%0" target="_blank">click here</a> to read the READ ME FIRST content before use!',
  1618. noticeLink: 'https://auto-task-doc.js.org/en/guide/#read-me-first',
  1619. toGithub: 'Feedback(Github)',
  1620. toKeylol: 'Feedback(Keylol)',
  1621. copySuccess: 'The error message has been copied to the clipboard. Do you want to go to the Keylol forum to give feedback?',
  1622. copyFailed: 'Please copy the error information below and report back to the Keylol forum!',
  1623. updateText: 'Updates in version %0:',
  1624. Active: 'Active',
  1625. Ended: 'Ended',
  1626. Banned: 'Banned',
  1627. Paused: 'Paused',
  1628. notStart: 'notStart',
  1629. noRemoteData: 'No data remotely',
  1630. errorRemoteDataFormat: 'Remote data has wrong format',
  1631. updateHistory: '<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">Click here</a>' + ' to view the historical update record.',
  1632. AsfEnabled: 'Use ASF to do Steam related tasks (requires <a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a> plugin)',
  1633. AsfIpcUrl: 'ASF IPC URL',
  1634. AsfIpcPassword: 'ASF IPC Password',
  1635. groups: 'Group',
  1636. officialGroups: 'Official Group',
  1637. wishlists: 'Wishlist',
  1638. follows: 'Follow Game',
  1639. forums: 'Forum',
  1640. workshops: 'Favorite Workshop',
  1641. curators: 'Curator',
  1642. workshopVotes: 'Voteup Workshop',
  1643. announcements: 'Announcement',
  1644. steamCommunity: 'Steam Community',
  1645. steamStore: 'Steam Store',
  1646. licenses: 'Add License',
  1647. playtests: 'Playtest Access',
  1648. needLoginSteamStore: 'Please <a href="https://store.steampowered.com/login/" target="_blank">log in to the Steam Store</a>',
  1649. needLoginSteamCommunity: 'Please <a href="https://steamcommunity.com/login/home/" target="_blank">log in to the Steam Community</a>',
  1650. joiningSteamGroup: 'Joining Steam Group',
  1651. leavingSteamGroup: 'Leaving Steam Group',
  1652. gettingSteamGroupId: 'Getting Steam Group Id',
  1653. joiningSteamOfficialGroup: 'Joining Steam Official Group',
  1654. leavingSteamOfficialGroup: 'Leaving Steam Official Group',
  1655. gettingSteamOfficialGroupId: 'Getting Steam Official Group Id',
  1656. subscribingForum: 'Subscribing the Steam Forum',
  1657. unsubscribingForum: 'Unsubscribing the Steam Forum',
  1658. gettingForumId: 'Getting Steam Forum Id',
  1659. followingCurator: 'Following Steam Curator',
  1660. unfollowingCurator: 'Unfollowing Steam Curator',
  1661. gettingCuratorId: 'Getting Steam Curator Id',
  1662. addingToWishlist: 'Adding the game to the Steam wishlist',
  1663. removingFromWishlist: 'Removing the game from the Steam wishlist',
  1664. followingGame: 'Following Steam games',
  1665. unfollowingGame: 'Unfollowing Steam games',
  1666. favoritingWorkshop: 'Favouring Steam Workshop Items',
  1667. unfavoritingWorkshop: 'Unfavoriting Steam Workshop Items',
  1668. gettingWorkshopAppId: 'Getting Steam Workshop Item Id',
  1669. votingUpWorkshop: 'Liking Steam workshop items',
  1670. gettingAnnouncementParams: 'Getting Steam announcement information',
  1671. likingAnnouncement: 'Liking Steam announcement',
  1672. changingArea: 'Changing Steam area: %0...',
  1673. notNeededChangeArea: 'The current area does not need to be changed',
  1674. noAnotherArea: 'Please check whether the proxy is turned on correctly',
  1675. gettingAreaInfo: 'Getting Steam area information...',
  1676. changeAreaNotice: 'Suspected of a locked zone game, try to change the zone to execute',
  1677. steamFinishNotice: 'Steam task completed, try to change the shopping cart area back to ',
  1678. gettingSubid: 'Getting subid',
  1679. addingFreeLicense: 'Adding free license',
  1680. missParams: 'Missing parameters',
  1681. gettingLicenses: 'Getting licenses...',
  1682. requestingPlayTestAccess: 'Requesting play test access',
  1683. tryChangeAreaNotice: 'This function cannot detect whether the game is limited, so it will try to change the area before entering the library' + '. Failure to change the area will not affect the subsequent storage.',
  1684. versionNotMatched: 'The script manager version is too low, requiring TamperMonkey >= 5.2.0 or TamperMonkey Beta >= 5.2.6196',
  1685. gettingUserLink: 'Getting steam user community link...',
  1686. retry: 'Retry',
  1687. owned: 'Owned',
  1688. redirect: 'Redirect',
  1689. noSubid: 'skip due to unrecognized',
  1690. initingASF: 'Initing ASF...',
  1691. servers: 'Server',
  1692. joiningDiscordServer: 'Joining Discord Server',
  1693. leavingDiscordServer: 'Leaving Discord Server',
  1694. gettingDiscordGuild: 'Getting Discord server Id',
  1695. getDiscordAuthFailed: 'Failed to get Discord token, please check whether the Discord account is logged in',
  1696. discordImportantNotice: 'Important Reminder! ! !',
  1697. discordImportantNoticeText: 'Due to the background update of the Discord website, currently using this script to join a group may cause the Discord account to be forcibly logged out, and two-step verification is required to log in normally, please use it with caution! ! !',
  1698. continue: 'Continue',
  1699. skipDiscordTask: 'Skip',
  1700. continueAndDontRemindAgain: 'Continue without Reminders',
  1701. users: 'User',
  1702. loginIns: 'Please <a href="https://www.instagram.com/accounts/login/" target="_blank">log in to Instagram</a>',
  1703. insBanned: 'Your Instagram account has been banned',
  1704. verifyingInsAuth: 'Verifying Instagram token...',
  1705. gettingInsUserId: 'Getting Instagram user Id',
  1706. followingIns: 'Following Instagram user',
  1707. unfollowingIns: 'Unfollowing Instagram user',
  1708. reddits: 'Reddit/User',
  1709. loginReddit: 'Please <a href="https://www.reddit.com/login/" target="_blank">log in to Reddit</a>',
  1710. changingRedditVersion: 'Switching Reddit to a new version page...',
  1711. joiningReddit: 'Joining the Reddit',
  1712. leavingReddit: 'Leaving the Reddit',
  1713. followingRedditUser: 'Following Reddit User',
  1714. unfollowingRedditUser: 'Unfollowing Reddit User',
  1715. channels: 'Channel',
  1716. followingTwitchChannel: 'Following Twitch Channel',
  1717. unfollowingTwitchChannel: 'Unfollowing Twitch Channel',
  1718. gettingTwitchChannelId: 'Getting Twitch Channel Id',
  1719. checkingTwitchIntegrity: 'Checking Twitch integrity...',
  1720. twitterUser: 'Twitter User',
  1721. retweets: 'Retweet',
  1722. gettingTwitterUserId: 'Getting Twitter User Id',
  1723. followingTwitterUser: 'Following Twitter User',
  1724. unfollowingTwitterUser: 'Unfollowing Twitter User',
  1725. retweetting: 'Retweetting',
  1726. unretweetting: 'Unretweetting',
  1727. names: 'Group/Public/Wall',
  1728. loginVk: 'Please <a href="https://vk.com/login/" target="_blank">log in to Vk</a>',
  1729. gettingVkId: 'Getting Vk task Id',
  1730. joiningVkGroup: 'Joining Vk Group',
  1731. leavingVkGroup: 'Leaving Vk Group',
  1732. joiningVkPublic: 'Joining Vk Public',
  1733. leavingVkPublic: 'Leaving Vk Public',
  1734. sendingVkWall: 'Sending Vk Wall',
  1735. deletingVkWall: 'Deleting Vk Wall',
  1736. youtubeChannel: 'YouTube Channel',
  1737. likes: 'Like',
  1738. loginYtb: 'Please <a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">log in to YouTube</a>',
  1739. tryUpdateYtbAuth: 'Please try to <a href="https://www.youtube.com/#auth" target="_blank">update YouTube token</a>',
  1740. gettingYtbToken: 'Getting YouTube Token...',
  1741. followingYtbChannel: 'Subscribing to YouTube channel',
  1742. unfollowingYtbChannel: 'Unsubscribing to YouTube channel',
  1743. likingYtbVideo: 'Liking YouTube video',
  1744. unlikingYtbVideo: 'Unliking YouTube video',
  1745. giveKeyNoticeBefore: 'Each verification interval is 15s',
  1746. giveKeyNoticeAfter: 'If there is no key, please check at <a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>',
  1747. noPoints: 'Not enough points, skip the lottery',
  1748. getNeedPointsFailed: 'ailed to obtain the required points, skip the lottery',
  1749. joiningLottery: 'Joining the lottery',
  1750. doingGleamTask: 'Doing Gleam Task...',
  1751. gettingGleamLink: 'Getting Gleam task link...',
  1752. gleamTaskNotice: 'If this page has not been closed for a long time, please close it yourself after completing any task!',
  1753. verifiedGleamTasks: 'Attempted to verify all tasks. If the verification fails, please try to verify manually or complete it!',
  1754. campaign: 'ReCAPTCHA detected, please complete it and re-verify the tasks!',
  1755. gsNotice: 'In order to avoid getting the "0000-0000-0000" key, the "Grab Key" button has been hidden,' + ' please close the script when obtaining the key!',
  1756. giveeClubVerifyNotice: 'Verifying task...',
  1757. giveeClubVerifyFinished: 'Wait for the verification to complete and join it by yourself',
  1758. doingKeyhubTask: 'Doing Keyhub Task...',
  1759. SweepWidgetNotice: 'The task is being processed and verified. ' + 'There is an interval of 1~3s for each verification task to prevent the triggering of too fast verification warning...',
  1760. tasksNotCompleted: 'Tasks Not Completed',
  1761. confirmingTask: 'Confirming task...'
  1762. };
  1763. const en_US = en_US_data;
  1764. const languages = {
  1765. zh: zh_CN,
  1766. en: en_US
  1767. };
  1768. const language = [ 'zh', 'en' ].includes(globalOptions.other.language) ? globalOptions.other.language : 'en';
  1769. const I18n = (key, ...argvs) => {
  1770. if (!languages[language]?.[key]) {
  1771. return key;
  1772. }
  1773. return languages[language][key].replace(/%([\d]+)/g, (match, index) => argvs[parseInt(index, 10)]);
  1774. };
  1775. const i18n = I18n;
  1776. function throwError(error, name) {
  1777. if (window.TRACE) {
  1778. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  1779. }
  1780. external_Swal_default().fire({
  1781. title: i18n('errorReport'),
  1782. icon: 'error',
  1783. showCancelButton: true,
  1784. confirmButtonText: i18n('toGithub'),
  1785. showDenyButton: true,
  1786. denyButtonText: i18n('toKeylol'),
  1787. cancelButtonText: i18n('close')
  1788. }).then(({
  1789. isDenied,
  1790. isConfirmed
  1791. }) => {
  1792. if (isConfirmed) {
  1793. GM_openInTab(`https://github.com/HCLonely/auto-task-v4/issues/new?title=${encodeURIComponent(`[BUG] 脚本报错: ${name}`)}&labels=bug&template=bug_report.yml&website=${encodeURIComponent(window.location.href)}&browser=${encodeURIComponent(JSON.stringify((0,
  1794. javascript_utils_umd_min.ua)(), null, 4))}&manager=${encodeURIComponent(`${GM_info.scriptHandler} ${GM_info.version}`)}&user-script=${encodeURIComponent(GM_info.script.version)}&logs=${encodeURIComponent(error.stack || 'null')}&run-logs=${encodeURIComponent($.makeArray($('#auto-task-info>li')).map(element => element.innerText).join('\n'))}`, {
  1795. active: true
  1796. });
  1797. } else if (isDenied) {
  1798. const text = `错误链接: [url=${window.location.href}]${window.location.href}[/url]
  1799.  
  1800. 环境:
  1801.  
  1802. [code]${JSON.stringify((0, javascript_utils_umd_min.ua)(), null, 4)}[/code]
  1803.  
  1804. 脚本管理器: ${GM_info.scriptHandler} ${GM_info.version}
  1805. 脚本版本: ${GM_info.script.version}
  1806.  
  1807. 报错信息:
  1808. [code]${error.stack}[/code]
  1809.  
  1810. 执行日志:
  1811. [code]${$.makeArray($('#auto-task-info>li')).map(element => element.innerText).join('\n')}[/code]`;
  1812. GM_setClipboard(text);
  1813. external_Swal_default().fire({
  1814. title: i18n('copySuccess'),
  1815. icon: 'success',
  1816. confirmButtonText: i18n('ok')
  1817. }).then(() => {
  1818. GM_openInTab('https://keylol.com/forum.php?mod=post&action=reply&fid=319&tid=777450', {
  1819. active: true
  1820. });
  1821. });
  1822. }
  1823. });
  1824. console.log('%c%s', 'color:white;background:red', `Auto-Task[Error]: ${name}\n${error.stack}`);
  1825. }
  1826. class Social {
  1827. tasks;
  1828. getRealParams(name, links, doTask, link2param) {
  1829. try {
  1830. let realParams = [];
  1831. if (links.length > 0) {
  1832. realParams = [ ...realParams, ...links.map(link => link2param(link)).filter(link => link) ];
  1833. }
  1834. if (!doTask && this.tasks[name].length > 0) {
  1835. realParams = [ ...realParams, ...this.tasks[name] ];
  1836. }
  1837. return unique(realParams);
  1838. } catch (error) {
  1839. throwError(error, 'Social.getRealParams');
  1840. return [];
  1841. }
  1842. }
  1843. }
  1844. const social_Social = Social;
  1845. class Discord extends social_Social {
  1846. tasks;
  1847. whiteList;
  1848. #auth = GM_getValue('discordAuth') || {};
  1849. #cache = GM_getValue('discordCache') || {};
  1850. #initialized = false;
  1851. constructor() {
  1852. super();
  1853. const defaultTasksTemplate = {
  1854. servers: []
  1855. };
  1856. this.tasks = defaultTasksTemplate;
  1857. this.whiteList = {
  1858. ...defaultTasksTemplate,
  1859. ...GM_getValue('whiteList')?.discord || {}
  1860. };
  1861. }
  1862. async init(action) {
  1863. try {
  1864. if (!GM_getValue('dontRemindDiscordAgain')) {
  1865. const result = await external_Swal_default().fire({
  1866. title: i18n('discordImportantNotice'),
  1867. text: i18n('discordImportantNoticeText'),
  1868. showCancelButton: true,
  1869. showDenyButton: true,
  1870. confirmButtonText: i18n('continue'),
  1871. cancelButtonText: i18n('skipDiscordTask'),
  1872. denyButtonText: i18n('continueAndDontRemindAgain')
  1873. }).then(({
  1874. isConfirmed,
  1875. isDenied
  1876. }) => {
  1877. if (isConfirmed) {
  1878. return true;
  1879. }
  1880. if (isDenied) {
  1881. GM_setValue('dontRemindDiscordAgain', true);
  1882. return true;
  1883. }
  1884. return false;
  1885. });
  1886. if (!result) {
  1887. this.#initialized = false;
  1888. return 'skip';
  1889. }
  1890. }
  1891. if (GM_getValue('dontRemindDiscordAgain') || action === 'do' && !globalOptions.doTask.discord.servers || action === 'undo' && !globalOptions.undoTask.discord.servers) {
  1892. this.#initialized = false;
  1893. return 'skip';
  1894. }
  1895. if (this.#initialized) {
  1896. return true;
  1897. }
  1898. if (!this.#auth.auth) {
  1899. if (await this.#updateAuth()) {
  1900. this.#initialized = true;
  1901. return true;
  1902. }
  1903. return false;
  1904. }
  1905. const isVerified = await this.#verifyAuth();
  1906. if (isVerified) {
  1907. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  1908. this.#initialized = true;
  1909. return true;
  1910. }
  1911. GM_setValue('discordAuth', {
  1912. auth: null
  1913. });
  1914. if (await this.#updateAuth()) {
  1915. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  1916. this.#initialized = true;
  1917. return true;
  1918. }
  1919. scripts_echoLog({}).error(i18n('initFailed', 'Discord'));
  1920. return false;
  1921. } catch (error) {
  1922. throwError(error, 'Discord.init');
  1923. return false;
  1924. }
  1925. }
  1926. async #verifyAuth() {
  1927. try {
  1928. const logStatus = scripts_echoLog({
  1929. text: i18n('verifyingAuth', 'Discord')
  1930. });
  1931. const {
  1932. result,
  1933. statusText,
  1934. status,
  1935. data
  1936. } = await tools_httpRequest({
  1937. url: 'https://discord.com/api/v6/users/@me',
  1938. method: 'HEAD',
  1939. headers: {
  1940. authorization: this.#auth.auth
  1941. }
  1942. });
  1943. if (result === 'Success') {
  1944. if (data?.status === 200) {
  1945. logStatus.success();
  1946. return true;
  1947. }
  1948. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  1949. return false;
  1950. }
  1951. logStatus.error(`${result}:${statusText}(${status})`);
  1952. return false;
  1953. } catch (error) {
  1954. throwError(error, 'Discord.verifyAuth');
  1955. return false;
  1956. }
  1957. }
  1958. async #updateAuth() {
  1959. try {
  1960. const logStatus = scripts_echoLog({
  1961. text: i18n('updatingAuth', 'Discord')
  1962. });
  1963. return await new Promise(resolve => {
  1964. const newTab = GM_openInTab('https://discord.com/channels/@me', {
  1965. active: true,
  1966. insert: true,
  1967. setParent: true
  1968. });
  1969. newTab.name = 'ATv4_discordAuth';
  1970. newTab.onclose = async () => {
  1971. const auth = GM_getValue('discordAuth')?.auth;
  1972. if (auth) {
  1973. this.#auth = {
  1974. auth: auth
  1975. };
  1976. logStatus.success();
  1977. resolve(await this.#verifyAuth());
  1978. } else {
  1979. logStatus.error('Error: Update discord auth failed!');
  1980. resolve(false);
  1981. }
  1982. };
  1983. });
  1984. } catch (error) {
  1985. throwError(error, 'Discord.updateAuth');
  1986. return false;
  1987. }
  1988. }
  1989. async #joinServer(inviteId) {
  1990. try {
  1991. const logStatus = scripts_echoLog({
  1992. type: 'joiningDiscordServer',
  1993. text: inviteId
  1994. });
  1995. const {
  1996. result,
  1997. statusText,
  1998. status,
  1999. data
  2000. } = await tools_httpRequest({
  2001. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2002. method: 'POST',
  2003. dataType: 'json',
  2004. headers: {
  2005. authorization: this.#auth.auth,
  2006. origin: 'https://discord.com',
  2007. referer: `https://discord.com/invite/${inviteId}`
  2008. }
  2009. });
  2010. if (result === 'Success' && data?.status === 200) {
  2011. logStatus.success();
  2012. const guild = String(data.response?.guild?.id);
  2013. if (guild) {
  2014. this.#setCache(inviteId, guild);
  2015. this.tasks.servers = unique([ ...this.tasks.servers, inviteId ]);
  2016. }
  2017. return true;
  2018. }
  2019. logStatus.error(`${result}:${statusText}(${status})`);
  2020. return false;
  2021. } catch (error) {
  2022. throwError(error, 'Discord.joinServer');
  2023. return false;
  2024. }
  2025. }
  2026. async #leaveServer(inviteId) {
  2027. try {
  2028. if (this.whiteList.servers.includes(inviteId)) {
  2029. scripts_echoLog({
  2030. type: 'whiteList',
  2031. text: 'Discord.leaveServer',
  2032. id: inviteId
  2033. });
  2034. return true;
  2035. }
  2036. const guild = await this.#getGuild(inviteId);
  2037. if (!guild) {
  2038. return false;
  2039. }
  2040. const logStatus = scripts_echoLog({
  2041. type: 'leavingDiscordServer',
  2042. text: guild
  2043. });
  2044. const {
  2045. result,
  2046. statusText,
  2047. status,
  2048. data
  2049. } = await tools_httpRequest({
  2050. url: `https://discord.com/api/v9/users/@me/guilds/${guild}`,
  2051. method: 'DELETE',
  2052. headers: {
  2053. authorization: this.#auth.auth
  2054. }
  2055. });
  2056. if (result === 'Success' && data?.status === 204) {
  2057. logStatus.success();
  2058. return true;
  2059. }
  2060. logStatus.error(`${result}:${statusText}(${status})`);
  2061. return false;
  2062. } catch (error) {
  2063. throwError(error, 'Discord.leaveServer');
  2064. return false;
  2065. }
  2066. }
  2067. async #getGuild(inviteId) {
  2068. try {
  2069. const logStatus = scripts_echoLog({
  2070. type: 'gettingDiscordGuild',
  2071. text: inviteId
  2072. });
  2073. const guild = this.#cache[inviteId];
  2074. if (guild) {
  2075. logStatus.success();
  2076. return guild;
  2077. }
  2078. const {
  2079. result,
  2080. statusText,
  2081. status,
  2082. data
  2083. } = await tools_httpRequest({
  2084. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2085. responseType: 'json',
  2086. method: 'GET'
  2087. });
  2088. if (result === 'Success' && data?.status === 200) {
  2089. const guild = data.response?.guild?.id;
  2090. if (guild) {
  2091. logStatus.success();
  2092. this.#setCache(inviteId, guild);
  2093. return guild;
  2094. }
  2095. logStatus.error(`${result}:${statusText}(${status})`);
  2096. return false;
  2097. }
  2098. logStatus.error(`${result}:${statusText}(${status})`);
  2099. return false;
  2100. } catch (error) {
  2101. throwError(error, 'Discord.getGuild');
  2102. return false;
  2103. }
  2104. }
  2105. async toggle({
  2106. doTask = true,
  2107. serverLinks = []
  2108. }) {
  2109. try {
  2110. if (!this.#initialized) {
  2111. scripts_echoLog({
  2112. text: i18n('needInit')
  2113. });
  2114. return false;
  2115. }
  2116. const prom = [];
  2117. if (doTask && !globalOptions.doTask.discord.servers || !doTask && !globalOptions.undoTask.discord.servers) {
  2118. scripts_echoLog({
  2119. type: 'globalOptionsSkip',
  2120. text: 'discord.servers'
  2121. });
  2122. } else {
  2123. const realServers = this.getRealParams('servers', serverLinks, doTask, link => link.match(/invite\/(.+)/)?.[1]);
  2124. if (realServers.length > 0) {
  2125. for (const server of realServers) {
  2126. if (doTask) {
  2127. prom.push(this.#joinServer(server));
  2128. } else {
  2129. prom.push(this.#leaveServer(server));
  2130. }
  2131. await delay(1e3);
  2132. }
  2133. }
  2134. }
  2135. return await Promise.all(prom).then(() => true);
  2136. } catch (error) {
  2137. throwError(error, 'Discord.toggleServers');
  2138. return false;
  2139. }
  2140. }
  2141. #setCache(inviteId, guild) {
  2142. try {
  2143. this.#cache[inviteId] = guild;
  2144. GM_setValue('discordCache', this.#cache);
  2145. } catch (error) {
  2146. throwError(error, 'Discord.setCache');
  2147. }
  2148. }
  2149. }
  2150. const social_Discord = Discord;
  2151. class Instagram extends social_Social {
  2152. tasks;
  2153. whiteList;
  2154. #cache = GM_getValue('instagramCache') || {};
  2155. #auth = {};
  2156. #initialized = false;
  2157. constructor() {
  2158. super();
  2159. const defaultTasksTemplate = {
  2160. users: []
  2161. };
  2162. this.tasks = defaultTasksTemplate;
  2163. this.whiteList = {
  2164. ...defaultTasksTemplate,
  2165. ...GM_getValue('whiteList')?.instagram || {}
  2166. };
  2167. }
  2168. async init() {
  2169. try {
  2170. if (this.#initialized) {
  2171. return true;
  2172. }
  2173. const isVerified = await this.#getUserInfo();
  2174. if (isVerified) {
  2175. scripts_echoLog({}).success(i18n('initSuccess', 'Instagram'));
  2176. this.#initialized = true;
  2177. return true;
  2178. }
  2179. scripts_echoLog({}).error(i18n('initFailed', 'Instagram'));
  2180. return false;
  2181. } catch (error) {
  2182. throwError(error, 'Instagram.init');
  2183. return false;
  2184. }
  2185. }
  2186. async #getUserInfo(name = 'instagram') {
  2187. try {
  2188. const logStatus = scripts_echoLog({
  2189. type: name === 'instagram' ? 'verifyingInsAuth' : 'gettingInsUserId',
  2190. text: name
  2191. });
  2192. const userId = this.#cache[name];
  2193. if (userId && name !== 'instagram') {
  2194. logStatus.success();
  2195. return userId;
  2196. }
  2197. const {
  2198. result,
  2199. statusText,
  2200. status,
  2201. data
  2202. } = await tools_httpRequest({
  2203. url: `https://www.instagram.com/${name}/`,
  2204. method: 'GET'
  2205. });
  2206. if (result === 'Success') {
  2207. if (data?.finalUrl.includes('accounts/login')) {
  2208. logStatus.error(`Error:${i18n('loginIns')}`, true);
  2209. return false;
  2210. } else if (data?.finalUrl.includes('www.instagram.com/challenge')) {
  2211. logStatus.error(`Error:${i18n('insBanned')}`);
  2212. return false;
  2213. }
  2214. if (data?.status === 200) {
  2215. const csrftoken = data.responseText.match(/"csrf_token":"(.+?)"/)?.[1];
  2216. const hash = data.responseText.match(/"rollout_hash":"(.+?)"/)?.[1];
  2217. if (name === 'instagram') {
  2218. if (csrftoken && hash) {
  2219. this.#auth = {
  2220. csrftoken: csrftoken,
  2221. hash: hash
  2222. };
  2223. return true;
  2224. }
  2225. return false;
  2226. }
  2227. const id = data.responseText.match(/"profilePage_([\d]+?)"/)?.[1];
  2228. if (id) {
  2229. this.#setCache(name, id);
  2230. logStatus.success();
  2231. return id;
  2232. }
  2233. logStatus.error('Error: Get ins data error!');
  2234. return false;
  2235. }
  2236. logStatus.error(`${result}:${statusText}(${status})`);
  2237. return false;
  2238. }
  2239. return false;
  2240. } catch (error) {
  2241. throwError(error, 'Instagram.getUserInfo');
  2242. return false;
  2243. }
  2244. }
  2245. async #followUser(name) {
  2246. try {
  2247. const id = await this.#getUserInfo(name);
  2248. if (!id) {
  2249. return false;
  2250. }
  2251. const logStatus = scripts_echoLog({
  2252. type: 'followingIns',
  2253. text: name
  2254. });
  2255. const {
  2256. result,
  2257. statusText,
  2258. status,
  2259. data
  2260. } = await tools_httpRequest({
  2261. url: `https://www.instagram.com/web/friendships/${id}/follow/`,
  2262. method: 'POST',
  2263. dataType: 'json',
  2264. headers: {
  2265. 'x-csrftoken': this.#auth.csrftoken,
  2266. origin: 'https://www.instagram.com',
  2267. referer: `https://www.instagram.com/${name}/`,
  2268. 'content-type': 'application/x-www-form-urlencoded',
  2269. 'sec-fetch-site': 'same-origin',
  2270. 'x-instagram-ajax': this.#auth.hash
  2271. }
  2272. });
  2273. if (result === 'Success') {
  2274. if (data?.status === 200 && data.response?.result === 'following') {
  2275. logStatus.success();
  2276. this.tasks.users = unique([ ...this.tasks.users, name ]);
  2277. return true;
  2278. }
  2279. logStatus.error(`Error:${data?.response?.feedback_message || `${data?.statusText}(${data?.status})`}`);
  2280. return false;
  2281. }
  2282. logStatus.error(`${result}:${statusText}(${status})`);
  2283. return false;
  2284. } catch (error) {
  2285. throwError(error, 'Instagram.followUser');
  2286. return false;
  2287. }
  2288. }
  2289. async #unfollowUser(name) {
  2290. try {
  2291. if (this.whiteList.users.includes(name)) {
  2292. scripts_echoLog({
  2293. type: 'whiteList',
  2294. text: 'Instagram.unfollowUser',
  2295. id: name
  2296. });
  2297. return true;
  2298. }
  2299. const id = await this.#getUserInfo(name);
  2300. if (!id) {
  2301. return false;
  2302. }
  2303. const logStatus = scripts_echoLog({
  2304. type: 'unfollowingIns',
  2305. text: name
  2306. });
  2307. const {
  2308. result,
  2309. statusText,
  2310. status,
  2311. data
  2312. } = await tools_httpRequest({
  2313. url: `https://www.instagram.com/web/friendships/${id}/unfollow/`,
  2314. method: 'POST',
  2315. dataType: 'json',
  2316. headers: {
  2317. 'x-csrftoken': this.#auth.csrftoken,
  2318. origin: 'https://www.instagram.com',
  2319. referer: `https://www.instagram.com/${name}/`,
  2320. 'content-type': 'application/x-www-form-urlencoded',
  2321. 'sec-fetch-site': 'same-origin',
  2322. 'x-instagram-ajax': this.#auth.hash
  2323. }
  2324. });
  2325. if (result === 'Success') {
  2326. if (data?.status === 200 && data.response?.status === 'ok') {
  2327. logStatus.success();
  2328. return true;
  2329. }
  2330. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2331. return false;
  2332. }
  2333. logStatus.error(`${result}:${statusText}(${status})`);
  2334. return false;
  2335. } catch (error) {
  2336. throwError(error, 'Instagram.unfollowUser');
  2337. return false;
  2338. }
  2339. }
  2340. async toggle({
  2341. doTask = true,
  2342. userLinks = []
  2343. }) {
  2344. try {
  2345. if (!this.#initialized) {
  2346. scripts_echoLog({
  2347. text: i18n('needInit')
  2348. });
  2349. return false;
  2350. }
  2351. const prom = [];
  2352. if (doTask && !globalOptions.doTask.instagram.users || !doTask && !globalOptions.undoTask.instagram.users) {
  2353. scripts_echoLog({
  2354. type: 'globalOptionsSkip',
  2355. text: 'instagram.users'
  2356. });
  2357. } else {
  2358. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1]);
  2359. if (realUsers.length > 0) {
  2360. for (const username of realUsers) {
  2361. if (doTask) {
  2362. prom.push(this.#followUser(username));
  2363. } else {
  2364. prom.push(this.#unfollowUser(username));
  2365. }
  2366. await delay(1e3);
  2367. }
  2368. }
  2369. }
  2370. return await Promise.all(prom).then(() => true);
  2371. } catch (error) {
  2372. throwError(error, 'Instagram.toggleUsers');
  2373. return false;
  2374. }
  2375. }
  2376. #setCache(name, id) {
  2377. try {
  2378. this.#cache[name] = id;
  2379. GM_setValue('instagramCache', this.#cache);
  2380. } catch (error) {
  2381. throwError(error, 'Instagram.setCache');
  2382. }
  2383. }
  2384. }
  2385. const social_Instagram = Instagram;
  2386. class Reddit extends social_Social {
  2387. tasks;
  2388. whiteList;
  2389. #auth;
  2390. #initialized = false;
  2391. constructor() {
  2392. super();
  2393. const defaultTasksTemplate = {
  2394. reddits: []
  2395. };
  2396. this.tasks = defaultTasksTemplate;
  2397. this.whiteList = {
  2398. ...defaultTasksTemplate,
  2399. ...GM_getValue('whiteList')?.reddit || {}
  2400. };
  2401. }
  2402. async init() {
  2403. try {
  2404. if (this.#initialized) {
  2405. return true;
  2406. }
  2407. const isVerified = await this.#updateAuth();
  2408. if (isVerified) {
  2409. scripts_echoLog({}).success(i18n('initSuccess', 'Reddit'));
  2410. this.#initialized = true;
  2411. return true;
  2412. }
  2413. scripts_echoLog({}).error(i18n('initFailed', 'Reddit'));
  2414. return false;
  2415. } catch (error) {
  2416. throwError(error, 'Reddit.init');
  2417. return false;
  2418. }
  2419. }
  2420. async #useBeta() {
  2421. try {
  2422. const logStatus = scripts_echoLog({
  2423. text: i18n('changingRedditVersion')
  2424. });
  2425. return await new Promise(resolve => {
  2426. const newTab = GM_openInTab('https://www.reddit.com/', {
  2427. active: true,
  2428. insert: true,
  2429. setParent: true
  2430. });
  2431. newTab.name = 'ATv4_redditAuth';
  2432. newTab.onclose = async () => {
  2433. logStatus.success();
  2434. resolve(await this.#updateAuth(true));
  2435. };
  2436. });
  2437. } catch (error) {
  2438. throwError(error, 'Reddit.useBeta');
  2439. return false;
  2440. }
  2441. }
  2442. async #updateAuth(beta = false) {
  2443. try {
  2444. const logStatus = scripts_echoLog({
  2445. text: i18n('updatingAuth', 'Reddit')
  2446. });
  2447. const {
  2448. result,
  2449. statusText,
  2450. status,
  2451. data
  2452. } = await tools_httpRequest({
  2453. url: 'https://www.reddit.com/',
  2454. method: 'GET',
  2455. nochche: true,
  2456. headers: {
  2457. 'Cache-Control': 'no-cache'
  2458. }
  2459. });
  2460. if (result === 'Success') {
  2461. if (data?.responseText.includes('www.reddit.com/login/')) {
  2462. logStatus.error(`Error:${i18n('loginReddit')}`, true);
  2463. return false;
  2464. }
  2465. if (data?.status === 200) {
  2466. if (data.responseText.includes('redesign-beta-optin-btn') && !beta) {
  2467. return await this.#useBeta();
  2468. }
  2469. const accessToken = data.responseText.match(/"accessToken":"(.*?)","expires":"(.*?)"/)?.[1];
  2470. if (accessToken) {
  2471. this.#auth = {
  2472. token: accessToken
  2473. };
  2474. logStatus.success();
  2475. return true;
  2476. }
  2477. logStatus.error('Error: Parameter "accessToken" not found!');
  2478. return false;
  2479. }
  2480. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2481. return false;
  2482. }
  2483. logStatus.error(`${result}:${statusText}(${status})`);
  2484. return false;
  2485. } catch (error) {
  2486. throwError(error, 'Reddit.updateAuth');
  2487. return false;
  2488. }
  2489. }
  2490. async #toggleTask({
  2491. name,
  2492. doTask = true
  2493. }) {
  2494. try {
  2495. if (!doTask && this.whiteList.reddits.includes(name)) {
  2496. scripts_echoLog({
  2497. type: 'whiteList',
  2498. text: 'Reddit.undoTask',
  2499. id: name
  2500. });
  2501. return true;
  2502. }
  2503. let type = doTask ? 'joiningReddit' : 'leavingReddit';
  2504. if (/^u_/.test(name)) {
  2505. type = doTask ? 'followingRedditUser' : 'unfollowingRedditUser';
  2506. }
  2507. const logStatus = scripts_echoLog({
  2508. type: type,
  2509. text: name
  2510. });
  2511. const {
  2512. result,
  2513. statusText,
  2514. status,
  2515. data
  2516. } = await tools_httpRequest({
  2517. url: 'https://oauth.reddit.com/api/subscribe?redditWebClient=desktop2x&app=desktop2x-client-production&raw_json=1&gilding_detail=1',
  2518. method: 'POST',
  2519. headers: {
  2520. authorization: `Bearer ${this.#auth.token}`,
  2521. 'content-type': 'application/x-www-form-urlencoded'
  2522. },
  2523. data: $.param({
  2524. action: doTask ? 'sub' : 'unsub',
  2525. sr_name: name,
  2526. api_type: 'json'
  2527. })
  2528. });
  2529. if (result === 'Success') {
  2530. if (data?.status === 200) {
  2531. logStatus.success();
  2532. if (doTask) {
  2533. this.tasks.reddits = unique([ ...this.tasks.reddits, name ]);
  2534. }
  2535. return true;
  2536. }
  2537. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2538. return false;
  2539. }
  2540. logStatus.error(`${result}:${statusText}(${status})`);
  2541. return false;
  2542. } catch (error) {
  2543. throwError(error, 'Reddit.toggleTask');
  2544. return false;
  2545. }
  2546. }
  2547. async toggle({
  2548. doTask = true,
  2549. redditLinks = []
  2550. }) {
  2551. try {
  2552. if (!this.#initialized) {
  2553. scripts_echoLog({
  2554. text: i18n('needInit')
  2555. });
  2556. return false;
  2557. }
  2558. const prom = [];
  2559. if (doTask && !globalOptions.doTask.reddit.reddits || !doTask && !globalOptions.undoTask.reddit.reddits) {
  2560. scripts_echoLog({
  2561. type: 'globalOptionsSkip',
  2562. text: 'reddit.reddits'
  2563. });
  2564. } else {
  2565. const realReddits = this.getRealParams('reddits', redditLinks, doTask, link => {
  2566. const name = link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1];
  2567. const userName = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1];
  2568. if (userName) {
  2569. return name || userName;
  2570. }
  2571. return name;
  2572. });
  2573. if (realReddits.length > 0) {
  2574. for (const name of realReddits) {
  2575. prom.push(this.#toggleTask({
  2576. name: name,
  2577. doTask: doTask
  2578. }));
  2579. await delay(1e3);
  2580. }
  2581. }
  2582. }
  2583. return await Promise.all(prom).then(() => true);
  2584. } catch (error) {
  2585. throwError(error, 'Reddit.toggle');
  2586. return false;
  2587. }
  2588. }
  2589. }
  2590. const social_Reddit = Reddit;
  2591. class Twitch extends social_Social {
  2592. tasks;
  2593. whiteList;
  2594. #auth = GM_getValue('twitchAuth') || {};
  2595. #cache = GM_getValue('twitchCache') || {};
  2596. #initialized = false;
  2597. #integrityToken;
  2598. constructor() {
  2599. super();
  2600. const defaultTasksTemplate = {
  2601. channels: []
  2602. };
  2603. this.tasks = defaultTasksTemplate;
  2604. this.whiteList = {
  2605. ...defaultTasksTemplate,
  2606. ...GM_getValue('whiteList')?.twitch || {}
  2607. };
  2608. }
  2609. async init() {
  2610. try {
  2611. if (this.#initialized) {
  2612. return true;
  2613. }
  2614. if (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId) {
  2615. if (await this.#updateAuth()) {
  2616. this.#initialized = true;
  2617. return true;
  2618. }
  2619. return false;
  2620. }
  2621. const isVerified = await this.#verifyAuth(true);
  2622. if (isVerified) {
  2623. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  2624. this.#initialized = true;
  2625. return true;
  2626. }
  2627. GM_setValue('twitchAuth', null);
  2628. if (await this.#updateAuth()) {
  2629. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  2630. this.#initialized = true;
  2631. return true;
  2632. }
  2633. scripts_echoLog({}).error(i18n('initFailed', 'Twitch'));
  2634. return false;
  2635. } catch (error) {
  2636. throwError(error, 'Twitch.init');
  2637. return false;
  2638. }
  2639. }
  2640. async #verifyAuth(isFirst) {
  2641. try {
  2642. const logStatus = scripts_echoLog({
  2643. text: i18n('verifyingAuth', 'Twitch')
  2644. });
  2645. const {
  2646. result,
  2647. statusText,
  2648. status,
  2649. data
  2650. } = await tools_httpRequest({
  2651. url: 'https://gql.twitch.tv/gql',
  2652. method: 'POST',
  2653. dataType: 'json',
  2654. headers: {
  2655. Authorization: `OAuth ${this.#auth.authToken}`,
  2656. 'Client-Id': this.#auth.clientId
  2657. },
  2658. data: '[{"operationName":"FrontPageNew_User","variables":{"limit":1},"extensions":{"persistedQuery":{"version":1,' + '"sha256Hash":"64bd07a2cbaca80699d62636d966cf6395a5d14a1f0a14282067dcb28b13eb11"}}}]'
  2659. });
  2660. if (result === 'Success') {
  2661. if (data?.status === 200 && data.response?.[0]?.data?.currentUser) {
  2662. await this.#integrity(isFirst);
  2663. logStatus.success();
  2664. return true;
  2665. }
  2666. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2667. return false;
  2668. }
  2669. logStatus.error(`${result}:${statusText}(${status})`);
  2670. return false;
  2671. } catch (error) {
  2672. throwError(error, 'Twitch.verifyAuth');
  2673. return false;
  2674. }
  2675. }
  2676. async #integrity(isFirst = true, ct = '') {
  2677. try {
  2678. const logStatus = scripts_echoLog({
  2679. text: i18n('checkingTwitchIntegrity')
  2680. });
  2681. if (isFirst && (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId)) {
  2682. return await this.#updateAuth(false);
  2683. }
  2684. const {
  2685. result,
  2686. statusText,
  2687. status,
  2688. data
  2689. } = await tools_httpRequest({
  2690. url: 'https://gql.twitch.tv/integrity',
  2691. method: 'POST',
  2692. dataType: 'json',
  2693. anonymous: true,
  2694. headers: {
  2695. Origin: 'https://www.twitch.tv',
  2696. Referer: 'https://www.twitch.tv/',
  2697. Authorization: `OAuth ${this.#auth.authToken}`,
  2698. 'Client-Id': this.#auth.clientId,
  2699. 'Client-Version': this.#auth.clientVersion,
  2700. 'X-Device-Id': this.#auth.deviceId,
  2701. 'Client-Session-Id': this.#auth.clientSessionId,
  2702. 'x-kpsdk-ct': ct
  2703. }
  2704. });
  2705. if (result === 'Success') {
  2706. if (!ct && data?.responseHeaders?.['x-kpsdk-ct']) {
  2707. return await this.#integrity(isFirst, data.responseHeaders['x-kpsdk-ct']);
  2708. }
  2709. if (data?.status === 200 && data.response?.token) {
  2710. this.#integrityToken = data.response.token;
  2711. logStatus.success();
  2712. return true;
  2713. }
  2714. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2715. return false;
  2716. }
  2717. logStatus.error(`${result}:${statusText}(${status})`);
  2718. return false;
  2719. } catch (error) {
  2720. throwError(error, 'Twitch.integrity');
  2721. return false;
  2722. }
  2723. }
  2724. async #updateAuth(isFirst = true) {
  2725. try {
  2726. const logStatus = scripts_echoLog({
  2727. text: i18n('updatingAuth', 'Twitch')
  2728. });
  2729. return await new Promise(resolve => {
  2730. const newTab = GM_openInTab('https://www.twitch.tv/', {
  2731. active: true,
  2732. insert: true,
  2733. setParent: true
  2734. });
  2735. newTab.name = 'ATv4_twitchAuth';
  2736. newTab.onclose = async () => {
  2737. const auth = GM_getValue('twitchAuth');
  2738. if (auth) {
  2739. this.#auth = auth;
  2740. logStatus.success();
  2741. resolve(await this.#verifyAuth(isFirst));
  2742. } else {
  2743. logStatus.error('Error: Update twitch auth failed!');
  2744. resolve(false);
  2745. }
  2746. };
  2747. });
  2748. } catch (error) {
  2749. throwError(error, 'Twitch.updateAuth');
  2750. return false;
  2751. }
  2752. }
  2753. async #toggleChannel({
  2754. name,
  2755. doTask = true
  2756. }) {
  2757. try {
  2758. if (!doTask && this.whiteList.channels.includes(name)) {
  2759. scripts_echoLog({
  2760. type: 'whiteList',
  2761. text: 'Twitch.unfollowChannel',
  2762. id: name
  2763. });
  2764. return true;
  2765. }
  2766. const channelId = await this.#getChannelId(name);
  2767. if (!channelId) {
  2768. return false;
  2769. }
  2770. const logStatus = scripts_echoLog({
  2771. type: `${doTask ? '' : 'un'}followingTwitchChannel`,
  2772. text: name
  2773. });
  2774. const followData = `[{"operationName":"FollowButton_FollowUser","variables":{"input":{"disableNotifications":false,"targetID":"${channelId}` + '"}},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"800e7346bdf7e5278a3c1d3f21b2b56e2639928f86815677a7126b093b2fdd08"}}}]';
  2775. const unfollowData = `[{"operationName":"FollowButton_UnfollowUser","variables":{"input":{"targetID":"${channelId}"}},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"f7dae976ebf41c755ae2d758546bfd176b4eeb856656098bb40e0a672ca0d880"}}}]';
  2776. const {
  2777. result,
  2778. statusText,
  2779. status,
  2780. data
  2781. } = await tools_httpRequest({
  2782. url: 'https://gql.twitch.tv/gql',
  2783. method: 'POST',
  2784. dataType: 'json',
  2785. anonymous: true,
  2786. headers: {
  2787. Origin: 'https://www.twitch.tv',
  2788. Referer: 'https://www.twitch.tv/',
  2789. Authorization: `OAuth ${this.#auth.authToken}`,
  2790. 'Client-Id': this.#auth.clientId,
  2791. 'Client-Version': this.#auth.clientVersion,
  2792. 'X-Device-Id': this.#auth.deviceId,
  2793. 'Client-Session-Id': this.#auth.clientSessionId,
  2794. 'Client-Integrity': this.#integrityToken
  2795. },
  2796. data: doTask ? followData : unfollowData
  2797. });
  2798. if (result === 'Success') {
  2799. if (data?.status === 200 && data.response?.[0] && !data.response[0].errors) {
  2800. logStatus.success();
  2801. if (doTask) {
  2802. this.tasks.channels = unique([ ...this.tasks.channels, name ]);
  2803. }
  2804. return true;
  2805. }
  2806. logStatus.error(`Error:${data?.response?.[0].errors?.[0]?.message || `${data?.statusText}(${data?.status})`}`);
  2807. return false;
  2808. }
  2809. logStatus.error(`${result}:${statusText}(${status})`);
  2810. return false;
  2811. } catch (error) {
  2812. throwError(error, 'Twitch.toggleChannel');
  2813. return false;
  2814. }
  2815. }
  2816. async #getChannelId(name) {
  2817. try {
  2818. const logStatus = scripts_echoLog({
  2819. type: 'gettingTwitchChannelId',
  2820. text: name
  2821. });
  2822. const channelId = this.#cache[name];
  2823. if (channelId) {
  2824. logStatus.success();
  2825. return channelId;
  2826. }
  2827. const {
  2828. result,
  2829. statusText,
  2830. status,
  2831. data
  2832. } = await tools_httpRequest({
  2833. url: 'https://gql.twitch.tv/gql',
  2834. method: 'POST',
  2835. headers: {
  2836. Authorization: `OAuth ${this.#auth.authToken}`,
  2837. 'Client-Id': this.#auth.clientId
  2838. },
  2839. responseType: 'json',
  2840. data: `[{"operationName":"ActiveWatchParty","variables":{"channelLogin":"${name}"},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"4a8156c97b19e3a36e081cf6d6ddb5dbf9f9b02ae60e4d2ff26ed70aebc80a30"}}}]'
  2841. });
  2842. if (result === 'Success') {
  2843. if (data?.status === 200) {
  2844. const channelId = data.response?.[0]?.data?.user?.id;
  2845. if (channelId) {
  2846. this.#setCache(name, String(channelId));
  2847. logStatus.success();
  2848. return channelId;
  2849. }
  2850. logStatus.error(`Error:${data.statusText}(${data.status})`);
  2851. return false;
  2852. }
  2853. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2854. return false;
  2855. }
  2856. logStatus.error(`${result}:${statusText}(${status})`);
  2857. return false;
  2858. } catch (error) {
  2859. throwError(error, 'Twitch.getChannelId');
  2860. return false;
  2861. }
  2862. }
  2863. async toggle({
  2864. doTask = true,
  2865. channelLinks = []
  2866. }) {
  2867. try {
  2868. if (!this.#initialized) {
  2869. scripts_echoLog({
  2870. text: i18n('needInit')
  2871. });
  2872. return false;
  2873. }
  2874. const prom = [];
  2875. if (doTask && !globalOptions.doTask.twitch.channels || !doTask && !globalOptions.undoTask.twitch.channels) {
  2876. scripts_echoLog({
  2877. type: 'globalOptionsSkip',
  2878. text: 'twitch.channels'
  2879. });
  2880. } else {
  2881. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2]);
  2882. if (realChannels.length > 0) {
  2883. for (const channel of realChannels) {
  2884. prom.push(this.#toggleChannel({
  2885. name: channel,
  2886. doTask: doTask
  2887. }));
  2888. await delay(1e3);
  2889. }
  2890. }
  2891. }
  2892. return Promise.all(prom).then(() => true);
  2893. } catch (error) {
  2894. throwError(error, 'Twitch.toggle');
  2895. return false;
  2896. }
  2897. }
  2898. #setCache(name, id) {
  2899. try {
  2900. this.#cache[name] = id;
  2901. GM_setValue('twitchCache', this.#cache);
  2902. } catch (error) {
  2903. throwError(error, 'Twitch.setCache');
  2904. }
  2905. }
  2906. }
  2907. const social_Twitch = Twitch;
  2908. class Twitter extends social_Social {
  2909. tasks;
  2910. whiteList;
  2911. #verifyId = globalOptions.other.twitterVerifyId;
  2912. #auth = GM_getValue('twitterAuth') || {};
  2913. #cache = GM_getValue('twitterCache') || {};
  2914. #initialized = false;
  2915. constructor() {
  2916. super();
  2917. const defaultTasksTemplate = {
  2918. users: [],
  2919. retweets: [],
  2920. likes: []
  2921. };
  2922. this.tasks = defaultTasksTemplate;
  2923. this.whiteList = {
  2924. ...defaultTasksTemplate,
  2925. ...GM_getValue('whiteList')?.twitter || {}
  2926. };
  2927. }
  2928. async init() {
  2929. try {
  2930. if (this.#initialized) {
  2931. return true;
  2932. }
  2933. if (!this.#auth.ct0) {
  2934. if (await this.#updateAuth()) {
  2935. this.#initialized = true;
  2936. return true;
  2937. }
  2938. return false;
  2939. }
  2940. const isVerified = await this.#verifyAuth();
  2941. if (isVerified) {
  2942. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  2943. this.#initialized = true;
  2944. return true;
  2945. }
  2946. GM_setValue('twitterAuth', null);
  2947. if (await this.#updateAuth()) {
  2948. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  2949. this.#initialized = true;
  2950. return true;
  2951. }
  2952. scripts_echoLog({}).error(i18n('initFailed', 'Twitter'));
  2953. return false;
  2954. } catch (error) {
  2955. throwError(error, 'Twitter.init');
  2956. return false;
  2957. }
  2958. }
  2959. async #verifyAuth() {
  2960. try {
  2961. return await this.#toggleUser({
  2962. name: 'verify',
  2963. doTask: true,
  2964. verify: true
  2965. });
  2966. } catch (error) {
  2967. throwError(error, 'Twitter.verifyAuth');
  2968. return false;
  2969. }
  2970. }
  2971. async #updateAuth() {
  2972. try {
  2973. const logStatus = scripts_echoLog({
  2974. text: i18n('updatingAuth', 'Twitter')
  2975. });
  2976. return await new Promise(resolve => {
  2977. GM_cookie.list({
  2978. url: 'https://x.com/settings/account'
  2979. }, async (cookies, error) => {
  2980. if (!error) {
  2981. const [ ct0, isLogin ] = cookies.map(cookie => [ 'ct0', 'twid' ].includes(cookie.name) ? cookie.value : null).filter(cookie => cookie);
  2982. if (isLogin && ct0) {
  2983. GM_setValue('twitterAuth', {
  2984. ct0: ct0
  2985. });
  2986. this.#auth = {
  2987. ct0: ct0
  2988. };
  2989. logStatus.success();
  2990. resolve(await this.#verifyAuth());
  2991. } else {
  2992. logStatus.error(i18n('needLogin'));
  2993. resolve(false);
  2994. }
  2995. } else {
  2996. logStatus.error('Error: Update twitter auth failed!');
  2997. resolve(false);
  2998. }
  2999. });
  3000. });
  3001. } catch (error) {
  3002. throwError(error, 'Twitter.updateToken');
  3003. return false;
  3004. }
  3005. }
  3006. async #toggleUser({
  3007. name,
  3008. doTask = true,
  3009. verify = false,
  3010. retry = false
  3011. }) {
  3012. try {
  3013. if (!doTask && !verify && this.whiteList.users.includes(name)) {
  3014. scripts_echoLog({
  3015. type: 'whiteList',
  3016. text: 'Twitter.unfollowUser',
  3017. id: name
  3018. });
  3019. return true;
  3020. }
  3021. const userId = verify ? this.#verifyId : await this.userName2id(name);
  3022. if (!userId) {
  3023. return false;
  3024. }
  3025. const logStatus = verify ? scripts_echoLog({
  3026. text: i18n('verifyingAuth', 'Twitter')
  3027. }) : scripts_echoLog({
  3028. type: `${doTask ? '' : 'un'}followingTwitterUser`,
  3029. text: name
  3030. });
  3031. const {
  3032. result,
  3033. statusText,
  3034. status,
  3035. data
  3036. } = await tools_httpRequest({
  3037. url: `https://x.com/i/api/1.1/friendships/${doTask ? 'create' : 'destroy'}.json`,
  3038. method: 'POST',
  3039. headers: {
  3040. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3041. 'Content-Type': 'application/x-www-form-urlencoded',
  3042. 'x-csrf-token': this.#auth.ct0,
  3043. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3044. 'X-Twitter-Active-User': 'yes'
  3045. },
  3046. responseType: 'json',
  3047. data: $.param({
  3048. include_profile_interstitial_type: 1,
  3049. include_blocking: 1,
  3050. include_blocked_by: 1,
  3051. include_followed_by: 1,
  3052. include_want_retweets: 1,
  3053. include_mute_edge: 1,
  3054. include_can_dm: 1,
  3055. include_can_media_tag: 1,
  3056. skip_status: 1,
  3057. id: userId
  3058. })
  3059. });
  3060. if (result === 'Success') {
  3061. if (data?.status === 200) {
  3062. logStatus.success();
  3063. if (doTask && !verify) {
  3064. this.tasks.users = unique([ ...this.tasks.users, name ]);
  3065. }
  3066. return true;
  3067. }
  3068. if (verify && data?.status === 403) {
  3069. if (data.response?.errors?.[0]?.code === 158) {
  3070. logStatus.success();
  3071. return true;
  3072. }
  3073. if (data.response?.errors?.[0]?.code === 353 && !retry && data.responseHeaders?.['set-cookie']) {
  3074. this.#auth.ct0 = data.responseHeaders['set-cookie']?.find(cookie => cookie.includes('ct0='))?.split(';')?.at(0)?.split('=')?.at(-1) || this.#auth.ct0;
  3075. logStatus.warning(i18n('retry'));
  3076. return this.#toggleUser({
  3077. name: name,
  3078. doTask: doTask,
  3079. verify: verify,
  3080. retry: true
  3081. });
  3082. }
  3083. }
  3084. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3085. return false;
  3086. }
  3087. logStatus.error(`${result}:${statusText}(${status})`);
  3088. return false;
  3089. } catch (error) {
  3090. throwError(error, 'Twitter.toggleUser');
  3091. return false;
  3092. }
  3093. }
  3094. async userName2id(name) {
  3095. try {
  3096. const logStatus = scripts_echoLog({
  3097. type: 'gettingTwitterUserId',
  3098. text: name
  3099. });
  3100. const userId = this.#cache[name];
  3101. if (userId) {
  3102. logStatus.success();
  3103. return userId;
  3104. }
  3105. const {
  3106. result,
  3107. statusText,
  3108. status,
  3109. data
  3110. } = await tools_httpRequest({
  3111. url: 'https://x.com/i/api/graphql/mCbpQvZAw6zu_4PvuAUVVQ/UserByScreenName' + `?variables=%7B%22screen_name%22%3A%22${name}%22%2C%22withSafetyModeUserFields%22%3Atrue%2C%22withSuperFollowsUserFields%22%3Atrue%7D`,
  3112. method: 'GET',
  3113. headers: {
  3114. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3115. 'content-type': 'application/json',
  3116. referer: `https://x.com/${name}`,
  3117. 'x-csrf-token': this.#auth.ct0,
  3118. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3119. 'X-Twitter-Active-User': 'yes'
  3120. },
  3121. responseType: 'json'
  3122. });
  3123. if (result === 'Success') {
  3124. if (data?.status === 200) {
  3125. let response = data.response || (typeof data.responseText === 'object' ? data.responseText : null);
  3126. if (!response) {
  3127. try {
  3128. response = JSON.parse(data.responseText);
  3129. } catch (error) {
  3130. response = null;
  3131. }
  3132. }
  3133. const userId = String(response?.data?.user?.result?.rest_id);
  3134. if (userId) {
  3135. this.#setCache(name, userId);
  3136. logStatus.success();
  3137. return userId;
  3138. }
  3139. logStatus.error(`Error:${data.statusText}(${data.status})`);
  3140. return false;
  3141. }
  3142. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3143. return false;
  3144. }
  3145. logStatus.error(`${result}:${statusText}(${status})`);
  3146. return false;
  3147. } catch (error) {
  3148. throwError(error, 'Twitter.getUserId');
  3149. return false;
  3150. }
  3151. }
  3152. async #toggleRetweet({
  3153. retweetId,
  3154. doTask = true
  3155. }) {
  3156. try {
  3157. if (!doTask && this.whiteList.retweets.includes(retweetId)) {
  3158. scripts_echoLog({
  3159. type: 'whiteList',
  3160. text: 'Twitter.unretweet',
  3161. id: retweetId
  3162. });
  3163. return true;
  3164. }
  3165. const logStatus = scripts_echoLog({
  3166. type: `${doTask ? '' : 'un'}retweetting`,
  3167. text: retweetId
  3168. });
  3169. const {
  3170. result,
  3171. statusText,
  3172. status,
  3173. data
  3174. } = await tools_httpRequest({
  3175. url: `https://x.com/i/api/graphql/${doTask ? 'ojPdsZsimiJrUGLR1sjUtA/CreateRetweet' : 'iQtK4dl5hBmXewYZuEOKVw/DeleteRetweet'}`,
  3176. method: 'POST',
  3177. headers: {
  3178. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3179. 'Content-Type': 'application/json',
  3180. 'x-csrf-token': this.#auth.ct0,
  3181. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3182. 'X-Twitter-Active-User': 'yes'
  3183. },
  3184. data: `{"variables":{"tweet_id":"${retweetId}","dark_request":false},"queryId":"${doTask ? 'ojPdsZsimiJrUGLR1sjUtA' : 'iQtK4dl5hBmXewYZuEOKVw'}"}`,
  3185. responseType: 'json'
  3186. });
  3187. if (result === 'Success') {
  3188. if (data?.status === 200 || data?.status === 403 && data.response?.errors?.[0]?.code === 327) {
  3189. logStatus.success();
  3190. if (doTask) {
  3191. this.tasks.retweets = unique([ ...this.tasks.retweets, retweetId ]);
  3192. }
  3193. return true;
  3194. }
  3195. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3196. return false;
  3197. }
  3198. logStatus.error(`${result}:${statusText}(${status})`);
  3199. return false;
  3200. } catch (error) {
  3201. throwError(error, 'Twitter.toggleRetweet');
  3202. return false;
  3203. }
  3204. }
  3205. async toggle({
  3206. doTask = true,
  3207. userLinks = [],
  3208. retweetLinks = []
  3209. }) {
  3210. try {
  3211. if (!this.#initialized) {
  3212. scripts_echoLog({
  3213. text: i18n('needInit')
  3214. });
  3215. return false;
  3216. }
  3217. const prom = [];
  3218. if (doTask && !globalOptions.doTask.twitter.users || !doTask && !globalOptions.undoTask.twitter.users) {
  3219. scripts_echoLog({
  3220. type: 'globalOptionsSkip',
  3221. text: 'twitter.users'
  3222. });
  3223. } else {
  3224. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/x\.com\/(.+)/)?.[1] || link.match(/https:\/\/twitter\.com\/(.+)/)?.[1]);
  3225. if (realUsers.length > 0) {
  3226. for (const user of realUsers) {
  3227. prom.push(this.#toggleUser({
  3228. name: user,
  3229. doTask: doTask
  3230. }));
  3231. await delay(1e3);
  3232. }
  3233. }
  3234. }
  3235. if (doTask && !globalOptions.doTask.twitter.retweets || !doTask && !globalOptions.undoTask.twitter.retweets) {
  3236. scripts_echoLog({
  3237. type: 'globalOptionsSkip',
  3238. text: 'twitter.retweets'
  3239. });
  3240. } else {
  3241. const realRetweets = this.getRealParams('retweets', retweetLinks, doTask, link => link.match(/https:\/\/x\.com\/.*?\/status\/([\d]+)/)?.[1] || link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1]);
  3242. if (realRetweets.length > 0) {
  3243. for (const retweet of realRetweets) {
  3244. prom.push(this.#toggleRetweet({
  3245. retweetId: retweet,
  3246. doTask: doTask
  3247. }));
  3248. await delay(1e3);
  3249. }
  3250. }
  3251. }
  3252. return Promise.all(prom).then(() => true);
  3253. } catch (error) {
  3254. throwError(error, 'Twitter.toggle');
  3255. return false;
  3256. }
  3257. }
  3258. #setCache(name, id) {
  3259. try {
  3260. this.#cache[name] = id;
  3261. GM_setValue('twitterCache', this.#cache);
  3262. } catch (error) {
  3263. throwError(error, 'Twitter.setCache');
  3264. }
  3265. }
  3266. }
  3267. const social_Twitter = Twitter;
  3268. class Vk extends social_Social {
  3269. tasks;
  3270. whiteList;
  3271. #username = '';
  3272. #cache = GM_getValue('vkCache') || {};
  3273. #initialized = false;
  3274. constructor() {
  3275. super();
  3276. const defaultTasksTemplate = {
  3277. names: []
  3278. };
  3279. this.tasks = defaultTasksTemplate;
  3280. this.whiteList = {
  3281. ...defaultTasksTemplate,
  3282. ...GM_getValue('whiteList')?.vk || {}
  3283. };
  3284. }
  3285. async init() {
  3286. try {
  3287. if (this.#initialized) {
  3288. return true;
  3289. }
  3290. const isVerified = await this.#verifyAuth();
  3291. if (isVerified) {
  3292. scripts_echoLog({}).success(i18n('initSuccess', 'Vk'));
  3293. this.#initialized = true;
  3294. return true;
  3295. }
  3296. scripts_echoLog({}).error(i18n('initFailed', 'Vk'));
  3297. return false;
  3298. } catch (error) {
  3299. throwError(error, 'Vk.init');
  3300. return false;
  3301. }
  3302. }
  3303. async #verifyAuth() {
  3304. try {
  3305. const logStatus = scripts_echoLog({
  3306. text: i18n('verifyAuth', 'Vk')
  3307. });
  3308. const {
  3309. result,
  3310. statusText,
  3311. status,
  3312. data
  3313. } = await tools_httpRequest({
  3314. url: 'https://vk.com/im',
  3315. method: 'GET'
  3316. });
  3317. if (result === 'Success') {
  3318. if (data?.finalUrl.includes('vk.com/login')) {
  3319. logStatus.error(`Error:${i18n('loginVk')}`, true);
  3320. return false;
  3321. }
  3322. if (data?.status === 200) {
  3323. this.#username = data.responseText.match(/TopNavBtn__profileLink" href="\/(.*?)"/)?.[1] || '';
  3324. logStatus.success();
  3325. return true;
  3326. }
  3327. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3328. return false;
  3329. }
  3330. logStatus.error(`${result}:${statusText}(${status})`);
  3331. return false;
  3332. } catch (error) {
  3333. throwError(error, 'Vk.verifyAuth');
  3334. return false;
  3335. }
  3336. }
  3337. async #toggleGroup(name, dataParam, doTask = true) {
  3338. try {
  3339. const logStatus = scripts_echoLog({
  3340. type: doTask ? 'joiningVkGroup' : 'leavingVkGroup',
  3341. text: name
  3342. });
  3343. if (dataParam.groupAct === 'enter' && !doTask || dataParam.groupAct === 'leave' && doTask) {
  3344. logStatus.success();
  3345. return true;
  3346. }
  3347. const reqData = {
  3348. act: doTask ? 'enter' : 'leave',
  3349. al: 1,
  3350. gid: dataParam.groupId,
  3351. hash: dataParam.groupHash
  3352. };
  3353. if (doTask) {
  3354. reqData.context = '_';
  3355. }
  3356. const {
  3357. result,
  3358. statusText,
  3359. status,
  3360. data
  3361. } = await tools_httpRequest({
  3362. url: 'https://vk.com/al_groups.php',
  3363. method: 'POST',
  3364. headers: {
  3365. origin: 'https://vk.com',
  3366. referer: `https://vk.com/${name}`,
  3367. 'content-type': 'application/x-www-form-urlencoded'
  3368. },
  3369. data: $.param(reqData)
  3370. });
  3371. if (result === 'Success') {
  3372. if (data?.status === 200) {
  3373. logStatus.success();
  3374. if (doTask) {
  3375. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3376. }
  3377. return true;
  3378. }
  3379. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3380. return false;
  3381. }
  3382. logStatus.error(`${result}:${statusText}(${status})`);
  3383. return false;
  3384. } catch (error) {
  3385. throwError(error, 'Vk.toggleGroup');
  3386. return false;
  3387. }
  3388. }
  3389. async #togglePublic(name, dataParam, doTask = true) {
  3390. try {
  3391. const logStatus = scripts_echoLog({
  3392. type: doTask ? 'joiningVkPublic' : 'leavingVkPublic',
  3393. text: name
  3394. });
  3395. if (dataParam.publicJoined && doTask || !dataParam.publicJoined && !doTask) {
  3396. logStatus.success();
  3397. return true;
  3398. }
  3399. const {
  3400. result,
  3401. statusText,
  3402. status,
  3403. data
  3404. } = await tools_httpRequest({
  3405. url: 'https://vk.com/al_public.php',
  3406. method: 'POST',
  3407. headers: {
  3408. origin: 'https://vk.com',
  3409. referer: `https://vk.com/${name}`,
  3410. 'content-type': 'application/x-www-form-urlencoded'
  3411. },
  3412. data: $.param({
  3413. act: doTask ? 'a_enter' : 'a_leave',
  3414. al: 1,
  3415. pid: dataParam.publicPid,
  3416. hash: dataParam.publicHash
  3417. })
  3418. });
  3419. if (result === 'Success') {
  3420. if (data?.status === 200) {
  3421. logStatus.success();
  3422. if (doTask) {
  3423. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3424. }
  3425. return true;
  3426. }
  3427. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3428. return false;
  3429. }
  3430. logStatus.error(`${result}:${statusText}(${status})`);
  3431. return false;
  3432. } catch (error) {
  3433. throwError(error, 'Vk.togglePublic');
  3434. return false;
  3435. }
  3436. }
  3437. async #sendWall(name) {
  3438. try {
  3439. const logStatus = scripts_echoLog({
  3440. type: 'sendingVkWall',
  3441. text: name
  3442. });
  3443. const {
  3444. result,
  3445. statusText,
  3446. status,
  3447. data
  3448. } = await tools_httpRequest({
  3449. url: 'https://vk.com/like.php',
  3450. method: 'POST',
  3451. headers: {
  3452. origin: 'https://vk.com',
  3453. referer: `https://vk.com/${name}`,
  3454. 'content-type': 'application/x-www-form-urlencoded'
  3455. },
  3456. data: $.param({
  3457. act: 'publish_box',
  3458. al: 1,
  3459. object: name
  3460. })
  3461. });
  3462. if (result === 'Success') {
  3463. if (data?.status === 200) {
  3464. const hash = data.responseText.match(/shHash:[\s]*'(.*?)'/)?.[1];
  3465. if (hash) {
  3466. const {
  3467. result: resultR,
  3468. statusText: statusTextR,
  3469. status: statusR,
  3470. data: dataR
  3471. } = await tools_httpRequest({
  3472. url: 'https://vk.com/like.php',
  3473. method: 'POST',
  3474. headers: {
  3475. origin: 'https://vk.com',
  3476. referer: `https://vk.com/${name}`,
  3477. 'content-type': 'application/x-www-form-urlencoded'
  3478. },
  3479. data: $.param({
  3480. Message: '',
  3481. act: 'a_do_publish',
  3482. al: 1,
  3483. close_comments: 0,
  3484. friends_only: 0,
  3485. from: 'box',
  3486. hash: hash,
  3487. list: '',
  3488. mark_as_ads: 0,
  3489. mute_notifications: 0,
  3490. object: name,
  3491. ret_data: 1,
  3492. to: 0
  3493. })
  3494. });
  3495. if (resultR === 'Success') {
  3496. if (dataR?.status === 200) {
  3497. const jsonData = JSON.parse(dataR.responseText?.replace('\x3c!--', '') || '{}');
  3498. if (jsonData?.payload?.[1]?.[1]?.share_my === true) {
  3499. logStatus.success();
  3500. const postId = String(jsonData?.payload?.[1]?.[1]?.post_id);
  3501. const ownerId = String(jsonData?.payload?.[1]?.[1]?.owner_id);
  3502. if (postId && ownerId) {
  3503. this.#setCache(name, `${ownerId}_${postId}`);
  3504. }
  3505. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3506. return true;
  3507. }
  3508. }
  3509. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  3510. return false;
  3511. }
  3512. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  3513. return false;
  3514. }
  3515. logStatus.error('Error: Get "hash" failed');
  3516. return false;
  3517. }
  3518. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3519. return false;
  3520. }
  3521. logStatus.error(`${result}:${statusText}(${status})`);
  3522. return false;
  3523. } catch (error) {
  3524. throwError(error, 'Vk.sendWall');
  3525. return false;
  3526. }
  3527. }
  3528. async #deleteWall(name, dataParams) {
  3529. try {
  3530. const logStatus = scripts_echoLog({
  3531. type: 'deletingVkWall',
  3532. text: name
  3533. });
  3534. const {
  3535. result,
  3536. statusText,
  3537. status,
  3538. data
  3539. } = await tools_httpRequest({
  3540. url: 'https://vk.com/al_wall.php?act=delete',
  3541. method: 'POST',
  3542. headers: {
  3543. origin: 'https://vk.com',
  3544. referer: `https://vk.com/${this.#username}?w=wall${this.#cache[name]}%2Fall`,
  3545. 'content-type': 'application/x-www-form-urlencoded'
  3546. },
  3547. data: $.param({
  3548. act: 'delete',
  3549. al: 1,
  3550. confirm: 0,
  3551. from: 'wkview',
  3552. hash: dataParams.wallHash,
  3553. post: this.#cache[name]
  3554. })
  3555. });
  3556. if (result === 'Success') {
  3557. if (data?.status === 200) {
  3558. const jsonData = JSON.parse(data.responseText?.replace('\x3c!--', '') || '{}');
  3559. if (jsonData?.payload?.[1]?.[1]) {
  3560. logStatus.success();
  3561. return true;
  3562. }
  3563. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3564. return false;
  3565. }
  3566. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3567. return false;
  3568. }
  3569. logStatus.error(`${result}:${statusText}(${status})`);
  3570. return false;
  3571. } catch (error) {
  3572. throwError(error, 'Vk.deleteWall');
  3573. return false;
  3574. }
  3575. }
  3576. async #getId(name, doTask) {
  3577. try {
  3578. let url = `https://vk.com/${name}`;
  3579. if (/^wall-/.test(name)) {
  3580. if (doTask) {
  3581. return {
  3582. type: 'sendWall'
  3583. };
  3584. }
  3585. if (!this.#cache[name]) {
  3586. return {
  3587. type: 'unSupport'
  3588. };
  3589. }
  3590. url = `https://vk.com/${this.#username}?w=wall${this.#cache[name]}`;
  3591. }
  3592. const logStatus = scripts_echoLog({
  3593. type: 'gettingVkId',
  3594. text: name
  3595. });
  3596. const {
  3597. result,
  3598. statusText,
  3599. status,
  3600. data
  3601. } = await tools_httpRequest({
  3602. url: url,
  3603. method: 'GET'
  3604. });
  3605. if (result === 'Success') {
  3606. if (data?.status === 200) {
  3607. const [ , groupAct, groupId, , groupHash ] = data.responseText.match(/Groups.(enter|leave)\(.*?,.*?([\d]+?), (&#39;|')(.*?)(&#39;|')/) || [];
  3608. const publicHash = data.responseText.match(/"enterHash":"(.*?)"/)?.[1];
  3609. const publicPid = data.responseText.match(/"public_id":([\d]+?),/)?.[1];
  3610. const publicJoined = !data.responseText.includes('Public.subscribe');
  3611. if (groupAct && groupId && groupHash) {
  3612. logStatus.success();
  3613. return {
  3614. groupAct: groupAct,
  3615. groupId: groupId,
  3616. groupHash: groupHash,
  3617. type: 'group'
  3618. };
  3619. } else if (publicHash && publicPid) {
  3620. logStatus.success();
  3621. return {
  3622. publicHash: publicHash,
  3623. publicPid: publicPid,
  3624. publicJoined: publicJoined,
  3625. type: 'public'
  3626. };
  3627. } else if (data.responseText.includes('wall.deletePost') && !doTask) {
  3628. const wallHash = data.responseText.match(/wall\.deletePost\(this, '.*?', '(.*?)'\)/)?.[1];
  3629. if (wallHash) {
  3630. logStatus.success();
  3631. return {
  3632. type: 'deleteWall',
  3633. wallHash: wallHash
  3634. };
  3635. }
  3636. } else if (name.includes('wall') && doTask) {
  3637. logStatus.success();
  3638. return {
  3639. type: 'sendWall'
  3640. };
  3641. }
  3642. logStatus.error('Error: Parameters not found!');
  3643. return false;
  3644. }
  3645. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3646. return false;
  3647. }
  3648. logStatus.error(`${result}:${statusText}(${status})`);
  3649. return false;
  3650. } catch (error) {
  3651. throwError(error, 'Vk.getId');
  3652. return false;
  3653. }
  3654. }
  3655. async #toggleVk({
  3656. name,
  3657. doTask = true
  3658. }) {
  3659. try {
  3660. if (!doTask && this.whiteList.names.includes(name)) {
  3661. scripts_echoLog({
  3662. type: 'whiteList',
  3663. text: 'Vk.undoTask',
  3664. id: name
  3665. });
  3666. return true;
  3667. }
  3668. const formatName = name.replace(/\/$/, '');
  3669. const data = await this.#getId(formatName, doTask);
  3670. if (!data) {
  3671. return false;
  3672. }
  3673. switch (data.type) {
  3674. case 'group':
  3675. return await this.#toggleGroup(formatName, data, doTask);
  3676.  
  3677. case 'public':
  3678. return await this.#togglePublic(formatName, data, doTask);
  3679.  
  3680. case 'sendWall':
  3681. return doTask ? await this.#sendWall(formatName) : true;
  3682.  
  3683. case 'deleteWall':
  3684. return doTask ? true : await this.#deleteWall(formatName, data);
  3685.  
  3686. default:
  3687. return false;
  3688. }
  3689. } catch (error) {
  3690. throwError(error, 'Vk.toggleVk');
  3691. return false;
  3692. }
  3693. }
  3694. async toggle({
  3695. doTask = true,
  3696. nameLinks = []
  3697. }) {
  3698. try {
  3699. if (!this.#initialized) {
  3700. scripts_echoLog({
  3701. text: i18n('needInit')
  3702. });
  3703. return false;
  3704. }
  3705. const prom = [];
  3706. if (doTask && !globalOptions.doTask.vk.names || !doTask && !globalOptions.undoTask.vk.names) {
  3707. scripts_echoLog({
  3708. type: 'globalOptionsSkip',
  3709. text: 'vk.names'
  3710. });
  3711. } else {
  3712. const realNames = this.getRealParams('names', nameLinks, doTask, link => link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1]);
  3713. if (realNames.length > 0) {
  3714. for (const name of realNames) {
  3715. prom.push(this.#toggleVk({
  3716. name: name,
  3717. doTask: doTask
  3718. }));
  3719. await delay(1e3);
  3720. }
  3721. }
  3722. }
  3723. return Promise.all(prom).then(() => true);
  3724. } catch (error) {
  3725. throwError(error, 'Vk.toggle');
  3726. return false;
  3727. }
  3728. }
  3729. #setCache(name, postId) {
  3730. try {
  3731. this.#cache[name] = postId;
  3732. GM_setValue('vkCache', this.#cache);
  3733. } catch (error) {
  3734. throwError(error, 'Vk.setCache');
  3735. }
  3736. }
  3737. }
  3738. const social_Vk = Vk;
  3739. const getInfo = async function(link, type) {
  3740. try {
  3741. const logStatus = scripts_echoLog({
  3742. text: i18n('gettingYtbToken')
  3743. });
  3744. const {
  3745. result,
  3746. statusText,
  3747. status,
  3748. data
  3749. } = await tools_httpRequest({
  3750. url: link,
  3751. method: 'GET'
  3752. });
  3753. if (result === 'Success') {
  3754. if (data?.status === 200) {
  3755. if (data.responseText.includes('accounts.google.com/ServiceLogin?service=youtube')) {
  3756. logStatus.error(`Error:${i18n('loginYtb')}`, true);
  3757. return {
  3758. needLogin: true
  3759. };
  3760. }
  3761. const apiKey = data.responseText.match(/"INNERTUBE_API_KEY":"(.*?)"/)?.[1];
  3762. const context = (data.responseText.match(/\(\{"INNERTUBE_CONTEXT":([\w\W]*?)\}\)/) || data.responseText.match(/"INNERTUBE_CONTEXT":([\w\W]*?\}),"INNERTUBE/))?.[1] || '{}';
  3763. const {
  3764. client,
  3765. request
  3766. } = JSON.parse(context);
  3767. if (apiKey && client && request) {
  3768. client.hl = 'en';
  3769. if (type === 'channel') {
  3770. const channelId = data.responseText.match(/"channelId":"(.+?)"/)?.[1];
  3771. if (channelId) {
  3772. logStatus.success();
  3773. return {
  3774. params: {
  3775. apiKey: apiKey,
  3776. client: client,
  3777. request: request,
  3778. channelId: channelId
  3779. }
  3780. };
  3781. }
  3782. logStatus.error('Error: Get "channelId" failed!');
  3783. return {};
  3784. } else if (type === 'likeVideo') {
  3785. const videoId = data.responseText.match(/<link rel="shortlinkUrl" href="https:\/\/youtu\.be\/(.*?)">/)?.[1];
  3786. const likeParams = data.responseText.match(/"likeParams":"(.*?)"/)?.[1];
  3787. if (videoId) {
  3788. logStatus.success();
  3789. return {
  3790. params: {
  3791. apiKey: apiKey,
  3792. client: client,
  3793. request: request,
  3794. videoId: videoId,
  3795. likeParams: likeParams
  3796. }
  3797. };
  3798. }
  3799. logStatus.error('Error: Get "videoId" failed!');
  3800. return {};
  3801. }
  3802. logStatus.error('Error: Unknown type');
  3803. return {};
  3804. }
  3805. logStatus.error('Error: Parameter "apiKey" not found!');
  3806. return {};
  3807. }
  3808. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3809. return {};
  3810. }
  3811. logStatus.error(`${result}:${statusText}(${status})`);
  3812. return {};
  3813. } catch (error) {
  3814. throwError(error, 'Youtube.getInfo');
  3815. return {};
  3816. }
  3817. };
  3818. class Youtube extends social_Social {
  3819. tasks;
  3820. whiteList;
  3821. #auth = GM_getValue('youtubeAuth') || {};
  3822. #initialized = false;
  3823. #verifyChannel = `https://www.youtube.com/channel/${globalOptions.other.youtubeVerifyChannel}`;
  3824. constructor() {
  3825. super();
  3826. const defaultTasksTemplate = {
  3827. channels: [],
  3828. likes: []
  3829. };
  3830. this.tasks = defaultTasksTemplate;
  3831. this.whiteList = {
  3832. ...defaultTasksTemplate,
  3833. ...GM_getValue('whiteList')?.youtube || {}
  3834. };
  3835. }
  3836. async init() {
  3837. try {
  3838. if (this.#initialized) {
  3839. return true;
  3840. }
  3841. if (!this.#auth.PAPISID) {
  3842. if (await this.#updateAuth()) {
  3843. this.#initialized = true;
  3844. return true;
  3845. }
  3846. return false;
  3847. }
  3848. const isVerified = await this.#verifyAuth();
  3849. if (isVerified) {
  3850. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  3851. this.#initialized = true;
  3852. return true;
  3853. }
  3854. GM_setValue('youtubeAuth', null);
  3855. if (await this.#updateAuth()) {
  3856. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  3857. this.#initialized = true;
  3858. return true;
  3859. }
  3860. scripts_echoLog({}).error(i18n('initFailed', 'Youtube'));
  3861. return false;
  3862. } catch (error) {
  3863. throwError(error, 'Youtube.init');
  3864. return false;
  3865. }
  3866. }
  3867. async #verifyAuth() {
  3868. try {
  3869. return await this.#toggleChannel({
  3870. link: this.#verifyChannel,
  3871. doTask: true,
  3872. verify: true
  3873. });
  3874. } catch (error) {
  3875. throwError(error, 'Youtube.verifyAuth');
  3876. return false;
  3877. }
  3878. }
  3879. async #updateAuth() {
  3880. try {
  3881. const logStatus = scripts_echoLog({
  3882. text: i18n('updatingAuth', 'Youtube')
  3883. });
  3884. return await new Promise(resolve => {
  3885. GM_cookie.list({
  3886. url: 'https://www.youtube.com/@YouTube'
  3887. }, async (cookies, error) => {
  3888. if (!error) {
  3889. const PAPISID = cookies.find(cookie => cookie.name === '__Secure-3PAPISID')?.value;
  3890. if (PAPISID) {
  3891. GM_setValue('youtubeAuth', {
  3892. PAPISID: PAPISID
  3893. });
  3894. this.#auth = {
  3895. PAPISID: PAPISID
  3896. };
  3897. logStatus.success();
  3898. resolve(await this.#verifyAuth());
  3899. } else {
  3900. logStatus.error(i18n('needLogin'));
  3901. resolve(false);
  3902. }
  3903. } else {
  3904. logStatus.error('Error: Update youtube auth failed!');
  3905. resolve(false);
  3906. }
  3907. });
  3908. });
  3909. } catch (error) {
  3910. throwError(error, 'Youtube.updateAuth');
  3911. return false;
  3912. }
  3913. }
  3914. #getInfo(link, type) {
  3915. return getInfo(link, type);
  3916. }
  3917. async #toggleChannel({
  3918. link,
  3919. doTask = true,
  3920. verify = false
  3921. }) {
  3922. try {
  3923. const {
  3924. params,
  3925. needLogin
  3926. } = await this.#getInfo(link, 'channel');
  3927. const {
  3928. apiKey,
  3929. client,
  3930. request,
  3931. channelId
  3932. } = params || {};
  3933. if (needLogin) {
  3934. scripts_echoLog({
  3935. html: i18n('loginYtb')
  3936. });
  3937. return false;
  3938. }
  3939. if (!(apiKey && client && request && channelId)) {
  3940. scripts_echoLog({
  3941. text: '"getYtbToken" failed'
  3942. });
  3943. return false;
  3944. }
  3945. if (!doTask && !verify && this.whiteList.channels.includes(channelId)) {
  3946. scripts_echoLog({
  3947. type: 'whiteList',
  3948. text: 'Youtube.unfollowChannel',
  3949. id: channelId
  3950. });
  3951. return true;
  3952. }
  3953. const logStatus = verify ? scripts_echoLog({
  3954. text: i18n('verifyingAuth', 'Youtube')
  3955. }) : scripts_echoLog({
  3956. type: doTask ? 'followingYtbChannel' : 'unfollowingYtbChannel',
  3957. text: channelId
  3958. });
  3959. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  3960. const {
  3961. result,
  3962. statusText,
  3963. status,
  3964. data
  3965. } = await tools_httpRequest({
  3966. url: `https://www.youtube.com/youtubei/v1/subscription/${doTask ? '' : 'un'}subscribe?key=${apiKey}&prettyPrint=false`,
  3967. method: 'POST',
  3968. headers: {
  3969. origin: 'https://www.youtube.com',
  3970. referer: `https://www.youtube.com/channel/${channelId}`,
  3971. 'content-type': 'application/json',
  3972. 'x-goog-authuser': '0',
  3973. 'x-goog-visitor-id': client?.visitorData,
  3974. 'x-origin': 'https://www.youtube.com',
  3975. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  3976. },
  3977. data: JSON.stringify({
  3978. context: {
  3979. client: client,
  3980. request: {
  3981. sessionId: request?.sessionId,
  3982. internalExperimentFlags: [],
  3983. consistencyTokenJars: []
  3984. },
  3985. user: {}
  3986. },
  3987. channelIds: [ channelId ],
  3988. params: doTask ? 'EgIIAhgA' : 'CgIIAhgA'
  3989. })
  3990. });
  3991. if (result === 'Success') {
  3992. if (data?.status === 200) {
  3993. if (doTask && (/"subscribed":true/.test(data.responseText) || data.responseText.includes('The subscription already exists')) || !doTask && /"subscribed":false/.test(data.responseText)) {
  3994. logStatus.success();
  3995. if (doTask && !verify) {
  3996. this.tasks.channels = unique([ ...this.tasks.channels, link ]);
  3997. }
  3998. return true;
  3999. }
  4000. if (verify && data.responseText.includes('You may not subscribe to yourself')) {
  4001. logStatus.success();
  4002. return true;
  4003. }
  4004. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4005. return false;
  4006. }
  4007. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4008. return false;
  4009. }
  4010. logStatus.error(`${result}:${statusText}(${status})`);
  4011. return false;
  4012. } catch (error) {
  4013. throwError(error, 'Youtube.toggleChannel');
  4014. return false;
  4015. }
  4016. }
  4017. async #toggleLikeVideo({
  4018. link,
  4019. doTask = true
  4020. }) {
  4021. try {
  4022. const {
  4023. params,
  4024. needLogin
  4025. } = await this.#getInfo(link, 'likeVideo');
  4026. const {
  4027. apiKey,
  4028. client,
  4029. request,
  4030. videoId,
  4031. likeParams
  4032. } = params || {};
  4033. if (needLogin) {
  4034. scripts_echoLog({
  4035. html: `${i18n('loginYtb')}`
  4036. });
  4037. return false;
  4038. }
  4039. if (!(apiKey && client && request && videoId && likeParams)) {
  4040. scripts_echoLog({
  4041. text: '"getYtbToken" failed'
  4042. });
  4043. return false;
  4044. }
  4045. if (!doTask && this.whiteList.likes.includes(videoId)) {
  4046. scripts_echoLog({
  4047. type: 'whiteList',
  4048. text: 'Youtube.unlikeVideo',
  4049. id: videoId
  4050. });
  4051. return true;
  4052. }
  4053. const logStatus = scripts_echoLog({
  4054. type: doTask ? 'likingYtbVideo' : 'unlikingYtbVideo',
  4055. text: videoId
  4056. });
  4057. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  4058. const likeVideoData = {
  4059. context: {
  4060. client: client,
  4061. request: {
  4062. sessionId: request.sessionId,
  4063. internalExperimentFlags: [],
  4064. consistencyTokenJars: []
  4065. },
  4066. user: {}
  4067. },
  4068. target: {
  4069. videoId: videoId
  4070. }
  4071. };
  4072. if (doTask) {
  4073. if (likeParams) {
  4074. likeVideoData.params = likeParams;
  4075. } else {
  4076. logStatus.error('Empty likeParams');
  4077. return false;
  4078. }
  4079. }
  4080. const {
  4081. result,
  4082. statusText,
  4083. status,
  4084. data
  4085. } = await tools_httpRequest({
  4086. url: `https://www.youtube.com/youtubei/v1/like/${doTask ? '' : 'remove'}like?key=${apiKey}`,
  4087. method: 'POST',
  4088. headers: {
  4089. origin: 'https://www.youtube.com',
  4090. referer: `https://www.youtube.com/watch?v=${videoId}`,
  4091. 'content-type': 'application/json',
  4092. 'x-goog-authuser': '0',
  4093. 'x-goog-visitor-id': client.visitorData,
  4094. 'x-origin': 'https://www.youtube.com',
  4095. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  4096. },
  4097. data: JSON.stringify(likeVideoData)
  4098. });
  4099. if (result === 'Success') {
  4100. if (data?.status === 200) {
  4101. if (doTask && data.responseText.includes('Added to Liked videos') || !doTask && (data.responseText.includes('Removed from Liked videos') || data.responseText.includes('Dislike removed'))) {
  4102. logStatus.success();
  4103. if (doTask) {
  4104. this.tasks.likes = unique([ ...this.tasks.likes, link ]);
  4105. }
  4106. return true;
  4107. }
  4108. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4109. return false;
  4110. }
  4111. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4112. return false;
  4113. }
  4114. logStatus.error(`${result}:${statusText}(${status})`);
  4115. return false;
  4116. } catch (error) {
  4117. throwError(error, 'Youtube.toggleLikeVideo');
  4118. return false;
  4119. }
  4120. }
  4121. async toggle({
  4122. doTask = true,
  4123. channelLinks = [],
  4124. videoLinks = []
  4125. }) {
  4126. try {
  4127. if (!this.#initialized) {
  4128. scripts_echoLog({
  4129. text: i18n('needInit')
  4130. });
  4131. return false;
  4132. }
  4133. const prom = [];
  4134. if (doTask && !globalOptions.doTask.youtube.channels || !doTask && !globalOptions.undoTask.youtube.channels) {
  4135. scripts_echoLog({
  4136. type: 'globalOptionsSkip',
  4137. text: 'youtube.channels'
  4138. });
  4139. } else {
  4140. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => {
  4141. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4142. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4143. }
  4144. return link;
  4145. });
  4146. if (realChannels.length > 0) {
  4147. for (const channel of realChannels) {
  4148. prom.push(this.#toggleChannel({
  4149. link: channel,
  4150. doTask: doTask
  4151. }));
  4152. await delay(1e3);
  4153. }
  4154. }
  4155. }
  4156. if (doTask && !globalOptions.doTask.youtube.likes || !doTask && !globalOptions.undoTask.youtube.likes) {
  4157. scripts_echoLog({
  4158. type: 'globalOptionsSkip',
  4159. text: 'youtube.likes'
  4160. });
  4161. } else {
  4162. const realLikes = this.getRealParams('likes', videoLinks, doTask, link => {
  4163. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4164. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4165. }
  4166. return link;
  4167. });
  4168. if (realLikes.length > 0) {
  4169. for (const video of realLikes) {
  4170. prom.push(this.#toggleLikeVideo({
  4171. link: video,
  4172. doTask: doTask
  4173. }));
  4174. await delay(1e3);
  4175. }
  4176. }
  4177. }
  4178. return Promise.all(prom).then(() => true);
  4179. } catch (error) {
  4180. throwError(error, 'Youtube.toggle');
  4181. return false;
  4182. }
  4183. }
  4184. }
  4185. class SteamASF {
  4186. #asfOptions;
  4187. #botName = 'asf';
  4188. #groupInfo;
  4189. async init() {
  4190. try {
  4191. const asfCommandsUrl = new URL('/Api/Command/', globalOptions.ASF.AsfIpcUrl);
  4192. this.#asfOptions = {
  4193. url: asfCommandsUrl.href,
  4194. method: 'POST',
  4195. responseType: 'json',
  4196. headers: {
  4197. accept: 'application/json',
  4198. 'Content-Type': 'application/json',
  4199. Host: asfCommandsUrl.host,
  4200. Origin: asfCommandsUrl.origin,
  4201. Referer: asfCommandsUrl.href,
  4202. Authentication: globalOptions.ASF.AsfIpcPassword
  4203. }
  4204. };
  4205. if (globalOptions.ASF.AsfBotname) {
  4206. this.#botName = globalOptions.ASF.AsfBotname;
  4207. }
  4208. const logStatus = scripts_echoLog({
  4209. text: i18n('initingASF')
  4210. });
  4211. const {
  4212. result,
  4213. statusText,
  4214. status,
  4215. data
  4216. } = await tools_httpRequest({
  4217. ...this.#asfOptions,
  4218. data: '{"Command":"!stats"}'
  4219. });
  4220. if (result === 'Success') {
  4221. if (data?.response?.Success === true && data.response.Message === 'OK' && data.response.Result) {
  4222. logStatus.success();
  4223. return true;
  4224. }
  4225. if (data?.response?.Result || data?.response?.Message) {
  4226. logStatus.error(data?.response?.Result || data.response.Message);
  4227. return false;
  4228. }
  4229. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4230. return false;
  4231. }
  4232. logStatus.error(`${result}:${statusText}(${status})`);
  4233. return false;
  4234. } catch (error) {
  4235. throwError(error, 'SteamASF.init');
  4236. return false;
  4237. }
  4238. }
  4239. async joinGroup(groupName) {
  4240. try {
  4241. const logStatus = scripts_echoLog({
  4242. type: 'joiningSteamGroup',
  4243. text: groupName
  4244. });
  4245. const {
  4246. result,
  4247. statusText,
  4248. status,
  4249. data
  4250. } = await tools_httpRequest({
  4251. ...this.#asfOptions,
  4252. data: JSON.stringify({
  4253. Command: `!JOINGROUP ${this.#botName} ${groupName}`
  4254. })
  4255. });
  4256. if (result === 'Success') {
  4257. if (data?.status === 200 && [ '已加入', '已申请', 'Joined', 'Applied', 'Присоединился', 'costs' ].find(text => data.response?.Result?.includes(text))) {
  4258. logStatus.success();
  4259. return true;
  4260. }
  4261. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4262. return false;
  4263. }
  4264. logStatus.error(`${result}:${statusText}(${status})`);
  4265. return false;
  4266. } catch (error) {
  4267. throwError(error, 'SteamASF.joinGroup');
  4268. return false;
  4269. }
  4270. }
  4271. async leaveGroup(groupName) {
  4272. try {
  4273. if (!this.#groupInfo) {
  4274. if (!await this.#getGroupId()) {
  4275. return false;
  4276. }
  4277. }
  4278. const groupId = await this.#groupInfo[groupName];
  4279. if (!groupId) {
  4280. return false;
  4281. }
  4282. const logStatus = scripts_echoLog({
  4283. type: 'leavingSteamGroup',
  4284. text: groupName
  4285. });
  4286. const {
  4287. result,
  4288. statusText,
  4289. status,
  4290. data
  4291. } = await tools_httpRequest({
  4292. ...this.#asfOptions,
  4293. data: JSON.stringify({
  4294. Command: `!LEAVEGROUP ${this.#botName} ${groupId}`
  4295. })
  4296. });
  4297. if (result === 'Success') {
  4298. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4299. logStatus.success();
  4300. return true;
  4301. }
  4302. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4303. return false;
  4304. }
  4305. logStatus.error(`${result}:${statusText}(${status})`);
  4306. return false;
  4307. } catch (error) {
  4308. throwError(error, 'SteamASF.leaveGroup');
  4309. return false;
  4310. }
  4311. }
  4312. async #getGroupId() {
  4313. try {
  4314. const logStatus = scripts_echoLog({
  4315. type: 'gettingSteamGroupId',
  4316. text: 'All'
  4317. });
  4318. const {
  4319. result,
  4320. statusText,
  4321. status,
  4322. data
  4323. } = await tools_httpRequest({
  4324. ...this.#asfOptions,
  4325. data: JSON.stringify({
  4326. Command: `!GROUPLIST ${this.#botName}`
  4327. })
  4328. });
  4329. if (result === 'Success') {
  4330. if (data?.status === 200 && data.response?.Result?.includes('|')) {
  4331. this.#groupInfo = Object.fromEntries(data.response.Result.split('\n').map(line => {
  4332. const [ , name, id ] = line.trim().split('|');
  4333. if (name && id) {
  4334. return [ name, id ];
  4335. }
  4336. return null;
  4337. }).filter(ele => ele));
  4338. logStatus.success();
  4339. return true;
  4340. }
  4341. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4342. return false;
  4343. }
  4344. logStatus.error(`${result}:${statusText}(${status})`);
  4345. return false;
  4346. } catch (error) {
  4347. throwError(error, 'SteamASF.getGroupID');
  4348. return false;
  4349. }
  4350. }
  4351. async addToWishlist(gameId) {
  4352. try {
  4353. const logStatus = scripts_echoLog({
  4354. type: 'addingToWishlist',
  4355. text: gameId
  4356. });
  4357. if ((await this.#checkGame(gameId)).wishlist === true) {
  4358. logStatus.success();
  4359. return true;
  4360. }
  4361. const {
  4362. result,
  4363. statusText,
  4364. status,
  4365. data
  4366. } = await tools_httpRequest({
  4367. ...this.#asfOptions,
  4368. data: JSON.stringify({
  4369. Command: `!ADDWISHLIST ${this.#botName} ${gameId}`
  4370. })
  4371. });
  4372. if (result === 'Success') {
  4373. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4374. logStatus.success();
  4375. return true;
  4376. }
  4377. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4378. return false;
  4379. }
  4380. logStatus.error(`${result}:${statusText}(${status})`);
  4381. return false;
  4382. } catch (error) {
  4383. throwError(error, 'SteamASF.addToWishlist');
  4384. return false;
  4385. }
  4386. }
  4387. async removeFromWishlist(gameId) {
  4388. try {
  4389. const logStatus = scripts_echoLog({
  4390. type: 'removingFromWishlist',
  4391. text: gameId
  4392. });
  4393. if ((await this.#checkGame(gameId)).wishlist === false) {
  4394. logStatus.success();
  4395. return true;
  4396. }
  4397. const {
  4398. result,
  4399. statusText,
  4400. status,
  4401. data
  4402. } = await tools_httpRequest({
  4403. ...this.#asfOptions,
  4404. data: JSON.stringify({
  4405. Command: `!REMOVEWISHLIST ${this.#botName} ${gameId}`
  4406. })
  4407. });
  4408. if (result === 'Success') {
  4409. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4410. logStatus.success();
  4411. return true;
  4412. }
  4413. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4414. return false;
  4415. }
  4416. logStatus.error(`${result}:${statusText}(${status})`);
  4417. return false;
  4418. } catch (error) {
  4419. throwError(error, 'SteamASF.removeFromWishlist');
  4420. return false;
  4421. }
  4422. }
  4423. async toggleFollowGame(gameId, doTask) {
  4424. try {
  4425. const logStatus = scripts_echoLog({
  4426. type: `${doTask ? '' : 'un'}followingGame`,
  4427. text: gameId
  4428. });
  4429. if (doTask && (await this.#checkGame(gameId)).followed === true || !doTask && (await this.#checkGame(gameId)).followed === false) {
  4430. logStatus.success();
  4431. return true;
  4432. }
  4433. const {
  4434. result,
  4435. statusText,
  4436. status,
  4437. data
  4438. } = await tools_httpRequest({
  4439. ...this.#asfOptions,
  4440. data: JSON.stringify({
  4441. Command: `!${doTask ? '' : 'UN'}FOLLOWGAME ${this.#botName} ${gameId}`
  4442. })
  4443. });
  4444. if (result === 'Success') {
  4445. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4446. logStatus.success();
  4447. return true;
  4448. }
  4449. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4450. return false;
  4451. }
  4452. logStatus.error(`${result}:${statusText}(${status})`);
  4453. return false;
  4454. } catch (error) {
  4455. throwError(error, 'SteamASF.toggleFollowGame');
  4456. return false;
  4457. }
  4458. }
  4459. async #checkGame(gameId) {
  4460. try {
  4461. const {
  4462. result,
  4463. data
  4464. } = await tools_httpRequest({
  4465. ...this.#asfOptions,
  4466. data: JSON.stringify({
  4467. Command: `!CHECK ${this.#botName} ${gameId}`
  4468. })
  4469. });
  4470. if (result === 'Success') {
  4471. if (data?.status === 200 && data.response?.Result?.includes(gameId)) {
  4472. const matchedResult = data.response.Result.split('\n').find(result => result.includes(gameId))?.split('|');
  4473. if (matchedResult?.length > 3) {
  4474. return {
  4475. wishlist: matchedResult.at(-3).trim() === '√' || matchedResult.at(-2).trim() === '√',
  4476. followed: matchedResult.at(-1).trim() === '√'
  4477. };
  4478. }
  4479. return {};
  4480. }
  4481. return {};
  4482. }
  4483. return {};
  4484. } catch (error) {
  4485. throwError(error, 'SteamASF.checkGame');
  4486. return {};
  4487. }
  4488. }
  4489. async toggleCurator(curatorId, doTask = true) {
  4490. try {
  4491. const logStatus = scripts_echoLog({
  4492. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  4493. text: curatorId
  4494. });
  4495. const {
  4496. result,
  4497. statusText,
  4498. status,
  4499. data
  4500. } = await tools_httpRequest({
  4501. ...this.#asfOptions,
  4502. data: JSON.stringify({
  4503. Command: `!${doTask ? '' : 'UN'}FOLLOWCURATOR ${this.#botName} ${curatorId}`
  4504. })
  4505. });
  4506. if (result === 'Success') {
  4507. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4508. logStatus.success();
  4509. return true;
  4510. }
  4511. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4512. return false;
  4513. }
  4514. logStatus.error(`${result}:${statusText}(${status})`);
  4515. return false;
  4516. } catch (error) {
  4517. throwError(error, 'Steam.toggleCurator');
  4518. return false;
  4519. }
  4520. }
  4521. async addLicense(id) {
  4522. try {
  4523. const [ type, ids ] = id.split('-');
  4524. if (type === 'appid') {
  4525. const logStatus = scripts_echoLog({
  4526. type: 'addingFreeLicense',
  4527. text: ids
  4528. });
  4529. const {
  4530. result,
  4531. statusText,
  4532. status,
  4533. data
  4534. } = await tools_httpRequest({
  4535. ...this.#asfOptions,
  4536. data: JSON.stringify({
  4537. Command: `!addlicense ${this.#botName} app/${ids}`
  4538. })
  4539. });
  4540. if (result === 'Success') {
  4541. if (data?.status === 200 && [ 'AlreadyPurchased', 'OK' ].find(text => data.response?.Result?.includes(text))) {
  4542. logStatus.success();
  4543. return true;
  4544. }
  4545. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4546. return false;
  4547. }
  4548. logStatus.error(`${result}:${statusText}(${status})`);
  4549. return false;
  4550. } else if (type === 'subid') {
  4551. const idsArr = ids.split(',');
  4552. const logStatus = scripts_echoLog({
  4553. type: 'addingFreeLicenseSubid',
  4554. text: ids
  4555. });
  4556. const {
  4557. result,
  4558. statusText,
  4559. status,
  4560. data
  4561. } = await tools_httpRequest({
  4562. ...this.#asfOptions,
  4563. data: JSON.stringify({
  4564. Command: `!addlicense ${this.#botName} ${idsArr.map(id => `sub/${id}`).join(',')}`
  4565. })
  4566. });
  4567. if (result === 'Success') {
  4568. if (data?.status === 200 && data.response?.Result) {
  4569. const resultLines = data.response.Result.split('\n');
  4570. idsArr.forEach(subid => {
  4571. const targetLine = resultLines.find(text => text.includes(subid));
  4572. if (targetLine && [ '成功', 'Success', 'Успех' ].find(text => targetLine.includes(text))) {
  4573. scripts_echoLog({}).success(targetLine);
  4574. } else {
  4575. scripts_echoLog({}).error(targetLine);
  4576. }
  4577. });
  4578. return true;
  4579. }
  4580. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4581. return false;
  4582. }
  4583. logStatus.error(`${result}:${statusText}(${status})`);
  4584. return false;
  4585. }
  4586. return false;
  4587. } catch (error) {
  4588. throwError(error, 'SteamASF.addLicense');
  4589. return false;
  4590. }
  4591. }
  4592. async requestPlayTestAccess(id) {
  4593. try {
  4594. const logStatus = scripts_echoLog({
  4595. type: 'requestingPlayTestAccess',
  4596. text: id
  4597. });
  4598. const {
  4599. result,
  4600. statusText,
  4601. status,
  4602. data
  4603. } = await tools_httpRequest({
  4604. ...this.#asfOptions,
  4605. data: JSON.stringify({
  4606. Command: `!REQUESTACCESS ${this.#botName} ${id}`
  4607. })
  4608. });
  4609. if (result === 'Success') {
  4610. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4611. logStatus.success();
  4612. return true;
  4613. }
  4614. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4615. return false;
  4616. }
  4617. logStatus.error(`${result}:${statusText}(${status})`);
  4618. return false;
  4619. } catch (error) {
  4620. throwError(error, 'Steam.requestPlayTestAccess');
  4621. return false;
  4622. }
  4623. }
  4624. }
  4625. const social_SteamASF = SteamASF;
  4626. class Steam extends social_Social {
  4627. tasks;
  4628. whiteList;
  4629. #cache = {
  4630. ...{
  4631. group: {},
  4632. officialGroup: {},
  4633. forum: {},
  4634. workshop: {},
  4635. curator: {}
  4636. },
  4637. ...GM_getValue('steamCache')
  4638. };
  4639. #auth = {};
  4640. #storeInitialized = false;
  4641. #communityInitialized = false;
  4642. #area = 'CN';
  4643. #oldArea;
  4644. #areaStatus = 'end';
  4645. #ASF;
  4646. constructor() {
  4647. super();
  4648. const defaultTasksTemplate = {
  4649. groups: [],
  4650. officialGroups: [],
  4651. wishlists: [],
  4652. follows: [],
  4653. forums: [],
  4654. workshops: [],
  4655. workshopVotes: [],
  4656. curators: [],
  4657. curatorLikes: [],
  4658. announcements: [],
  4659. licenses: [],
  4660. playtests: []
  4661. };
  4662. this.tasks = defaultTasksTemplate;
  4663. this.whiteList = {
  4664. ...defaultTasksTemplate,
  4665. ...GM_getValue('whiteList')?.steam || {}
  4666. };
  4667. }
  4668. async init(type = 'all') {
  4669. try {
  4670. if (globalOptions.ASF.AsfEnabled && globalOptions.ASF.AsfIpcUrl && globalOptions.ASF.AsfIpcPassword) {
  4671. this.#ASF = new social_SteamASF();
  4672. if (await this.#ASF.init()) {
  4673. this.#storeInitialized = true;
  4674. this.#communityInitialized = true;
  4675. return true;
  4676. }
  4677. return false;
  4678. }
  4679. if (type === 'store') {
  4680. if (this.#storeInitialized) {
  4681. return true;
  4682. }
  4683. let storeInitialized = await this.#updateStoreAuth();
  4684. if (!storeInitialized) {
  4685. storeInitialized = await this.#updateStoreAuthTab();
  4686. }
  4687. this.#storeInitialized = storeInitialized;
  4688. if (!this.#storeInitialized) {
  4689. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4690. return false;
  4691. }
  4692. scripts_echoLog({}).success(i18n('initSuccess', 'SteamStore'));
  4693. return true;
  4694. }
  4695. if (type === 'community') {
  4696. if (this.#communityInitialized) {
  4697. return true;
  4698. }
  4699. let communityInitialized = await this.#updateCommunityAuth();
  4700. if (!communityInitialized) {
  4701. communityInitialized = await this.#updateCommunityAuthTab();
  4702. GM_setValue('steamCommunityAuth', null);
  4703. }
  4704. this.#communityInitialized = communityInitialized;
  4705. if (!this.#communityInitialized) {
  4706. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4707. return false;
  4708. }
  4709. scripts_echoLog({}).success(i18n('initSuccess', 'SteamCommunity'));
  4710. return true;
  4711. }
  4712. if (this.#storeInitialized && this.#communityInitialized) {
  4713. scripts_echoLog({}).success(i18n('initSuccess', 'Steam'));
  4714. return true;
  4715. }
  4716. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4717. return false;
  4718. } catch (error) {
  4719. throwError(error, 'Steam.init');
  4720. return false;
  4721. }
  4722. }
  4723. async #refreshToken(type = 'steamStore') {
  4724. try {
  4725. const host = {
  4726. steamStore: 'store.steampowered.com',
  4727. steamCommunity: 'steamcommunity.com'
  4728. };
  4729. const logStatus = scripts_echoLog({
  4730. text: i18n('refreshingToken', i18n(type))
  4731. });
  4732. const formData = new FormData();
  4733. formData.append('redir', `https://${host[type]}/`);
  4734. const {
  4735. result,
  4736. statusText,
  4737. status,
  4738. data
  4739. } = await tools_httpRequest({
  4740. url: 'https://login.steampowered.com/jwt/ajaxrefresh',
  4741. method: 'POST',
  4742. responseType: 'json',
  4743. headers: {
  4744. Host: 'login.steampowered.com',
  4745. Origin: `https://${host[type]}`,
  4746. Referer: `https://${host[type]}/`
  4747. },
  4748. data: formData
  4749. });
  4750. if (result === 'Success') {
  4751. if (data?.response?.success) {
  4752. if (await this.#setStoreToken(data.response, type)) {
  4753. logStatus.success();
  4754. return true;
  4755. }
  4756. logStatus.error('Error');
  4757. return false;
  4758. }
  4759. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4760. return false;
  4761. }
  4762. logStatus.error(`${result}:${statusText}(${status})`);
  4763. return false;
  4764. } catch (error) {
  4765. throwError(error, 'Steam.refreshToken');
  4766. return false;
  4767. }
  4768. }
  4769. async #setStoreToken(param, type) {
  4770. try {
  4771. const host = {
  4772. steamStore: 'store.steampowered.com',
  4773. steamCommunity: 'steamcommunity.com'
  4774. };
  4775. const logStatus = scripts_echoLog({
  4776. text: i18n('settingToken', i18n(type))
  4777. });
  4778. const formData = new FormData();
  4779. formData.append('steamID', param.steamID);
  4780. formData.append('nonce', param.nonce);
  4781. formData.append('redir', param.redir);
  4782. formData.append('auth', param.auth);
  4783. const {
  4784. result,
  4785. statusText,
  4786. status,
  4787. data
  4788. } = await tools_httpRequest({
  4789. url: `https://${host[type]}/login/settoken`,
  4790. method: 'POST',
  4791. headers: {
  4792. Accept: 'application/json, text/plain, */*',
  4793. Host: host[type],
  4794. Origin: `https://${host[type]}`
  4795. },
  4796. data: formData
  4797. });
  4798. if (result === 'Success') {
  4799. if (data?.status === 200) {
  4800. logStatus.success();
  4801. return true;
  4802. }
  4803. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4804. return false;
  4805. }
  4806. logStatus.error(`${result}:${statusText}(${status})`);
  4807. return false;
  4808. } catch (error) {
  4809. throwError(error, 'Steam.setStoreToken');
  4810. return false;
  4811. }
  4812. }
  4813. async #updateStoreAuth(retry = false) {
  4814. try {
  4815. const logStatus = scripts_echoLog({
  4816. text: i18n('updatingAuth', i18n('steamStore'))
  4817. });
  4818. const {
  4819. result,
  4820. statusText,
  4821. status,
  4822. data
  4823. } = await tools_httpRequest({
  4824. url: 'https://store.steampowered.com/',
  4825. method: 'GET',
  4826. headers: {
  4827. Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  4828. 'Sec-Fetch-Dest': 'document',
  4829. 'Sec-Fetch-Mode': 'navigate',
  4830. 'Upgrade-Insecure-Requests': '1'
  4831. },
  4832. fetch: false,
  4833. redirect: 'manual'
  4834. });
  4835. if (data?.status === 200) {
  4836. if (!data.responseText.includes('data-miniprofile=')) {
  4837. if (await this.#refreshToken('steamStore')) {
  4838. logStatus.warning(i18n('retry'));
  4839. if (retry) {
  4840. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4841. return false;
  4842. }
  4843. return this.#updateStoreAuth(true);
  4844. }
  4845. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4846. return false;
  4847. }
  4848. const storeSessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  4849. if (storeSessionID) {
  4850. this.#auth.storeSessionID = storeSessionID;
  4851. logStatus.success();
  4852. return true;
  4853. }
  4854. logStatus.error('Error: Get "sessionID" failed');
  4855. return false;
  4856. }
  4857. if ([ 301, 302 ].includes(data?.status)) {
  4858. if (await this.#refreshToken('steamStore')) {
  4859. logStatus.warning(i18n('retry'));
  4860. if (retry) {
  4861. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4862. return false;
  4863. }
  4864. return this.#updateStoreAuth(true);
  4865. }
  4866. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4867. return false;
  4868. }
  4869. logStatus.error(`${result}:${statusText}(${status})`);
  4870. return false;
  4871. } catch (error) {
  4872. throwError(error, 'Steam.updateStoreAuth');
  4873. return false;
  4874. }
  4875. }
  4876. async #updateStoreAuthTab() {
  4877. try {
  4878. const logStatus = scripts_echoLog({
  4879. text: i18n('updatingAuth', i18n('steamStoreTab'))
  4880. });
  4881. return await new Promise(resolve => {
  4882. GM_deleteValue('steamStoreAuth');
  4883. GM_setValue('ATv4_updateStoreAuth', true);
  4884. const newTab = GM_openInTab('https://store.steampowered.com/', {
  4885. active: true,
  4886. setParent: true
  4887. });
  4888. newTab.name = 'ATv4_updateStoreAuth';
  4889. const listenerId = GM_addValueChangeListener('steamStoreAuth', (key, oldValue, newValue) => {
  4890. GM_removeValueChangeListener(listenerId);
  4891. GM_deleteValue('ATv4_updateStoreAuth');
  4892. newTab?.close();
  4893. window.focus();
  4894. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  4895. this.#auth.storeSessionID = newValue.storeSessionID;
  4896. logStatus.success();
  4897. resolve(true);
  4898. return;
  4899. }
  4900. logStatus.error('Failed');
  4901. resolve(false);
  4902. });
  4903. newTab.onclose = () => {
  4904. GM_deleteValue('ATv4_updateStoreAuth');
  4905. };
  4906. });
  4907. } catch (error) {
  4908. throwError(error, 'Steam.updateStoreAuthTab');
  4909. return false;
  4910. }
  4911. }
  4912. async #updateCommunityAuthTab() {
  4913. try {
  4914. const logStatus = scripts_echoLog({
  4915. text: i18n('updatingAuth', i18n('steamCommunityTab'))
  4916. });
  4917. return await new Promise(resolve => {
  4918. GM_deleteValue('steamCommunityAuth');
  4919. GM_setValue('ATv4_updateCommunityAuth', true);
  4920. const newTab = GM_openInTab('https://steamcommunity.com/my', {
  4921. active: true,
  4922. setParent: true
  4923. });
  4924. newTab.name = 'ATv4_updateCommunityAuth';
  4925. const listenerId = GM_addValueChangeListener('steamCommunityAuth', (key, oldValue, newValue) => {
  4926. GM_removeValueChangeListener(listenerId);
  4927. GM_deleteValue('ATv4_updateCommunityAuth');
  4928. newTab?.close();
  4929. window.focus();
  4930. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  4931. this.#auth.steam64Id = newValue.steam64Id;
  4932. this.#auth.communitySessionID = newValue.communitySessionID;
  4933. logStatus.success();
  4934. resolve(true);
  4935. return;
  4936. }
  4937. logStatus.error('Failed');
  4938. resolve(false);
  4939. });
  4940. newTab.onclose = () => {
  4941. GM_deleteValue('ATv4_updateCommunityAuth');
  4942. };
  4943. });
  4944. } catch (error) {
  4945. throwError(error, 'Steam.updateCommunityAuthTab');
  4946. return false;
  4947. }
  4948. }
  4949. async #updateCommunityAuth() {
  4950. try {
  4951. const logStatus = scripts_echoLog({
  4952. text: i18n('gettingUserLink')
  4953. });
  4954. const {
  4955. result,
  4956. statusText,
  4957. status,
  4958. data
  4959. } = await tools_httpRequest({
  4960. url: 'https://steamcommunity.com/my',
  4961. method: 'GET',
  4962. headers: {
  4963. Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
  4964. Host: 'steamcommunity.com',
  4965. 'Sec-Fetch-Dest': 'document',
  4966. 'Sec-Fetch-Mode': 'navigate'
  4967. },
  4968. fetch: false
  4969. });
  4970. if (data?.status === 200) {
  4971. if (data.finalUrl.includes('https://steamcommunity.com/login/home')) {
  4972. logStatus.error(`Error:${i18n('needLoginSteamCommunity')}`, true);
  4973. return false;
  4974. }
  4975. const steam64Id = data.responseText.match(/g_steamID = "(.+?)";/)?.[1];
  4976. const communitySessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  4977. if (steam64Id && communitySessionID) {
  4978. this.#auth.steam64Id = steam64Id;
  4979. this.#auth.communitySessionID = communitySessionID;
  4980. logStatus.success();
  4981. return true;
  4982. }
  4983. logStatus.error('Error: Get "sessionID" failed');
  4984. return false;
  4985. }
  4986. logStatus.error(`${result}:${statusText}(${status})`);
  4987. return false;
  4988. } catch (error) {
  4989. throwError(error, 'Steam.updateCommunityAuth');
  4990. return false;
  4991. }
  4992. }
  4993. async #getAreaInfo() {
  4994. try {
  4995. const logStatus = scripts_echoLog({
  4996. text: i18n('gettingAreaInfo')
  4997. });
  4998. const {
  4999. result,
  5000. statusText,
  5001. status,
  5002. data
  5003. } = await tools_httpRequest({
  5004. url: 'https://store.steampowered.com/cart/',
  5005. method: 'GET'
  5006. });
  5007. if (result === 'Success') {
  5008. if (data?.status === 200) {
  5009. const cartConfigRaw = data.responseText.match(/data-cart_config="(.*?)"/)?.[1];
  5010. const temp = document.createElement('div');
  5011. temp.innerHTML = cartConfigRaw || '{}';
  5012. const cartConfigStr = temp.textContent || temp.innerText;
  5013. let cartConfig;
  5014. try {
  5015. cartConfig = JSON.parse(cartConfigStr);
  5016. } catch (error) {
  5017. logStatus.error('Error: get country info filed');
  5018. console.error(error);
  5019. return {};
  5020. }
  5021. if (!cartConfig.rgUserCountryOptions) {
  5022. logStatus.warning('Warning: Area cannot be changed');
  5023. return {};
  5024. }
  5025. const userInfoRaw = data.responseText.match(/data-userinfo="(.*?)"/)?.[1];
  5026. const temp1 = document.createElement('div');
  5027. temp1.innerHTML = userInfoRaw || '{}';
  5028. const userInfoStr = temp1.textContent || temp1.innerText;
  5029. let userInfo;
  5030. try {
  5031. userInfo = JSON.parse(userInfoStr);
  5032. } catch (error) {
  5033. logStatus.error('Error: get country info filed');
  5034. console.error(error);
  5035. return {};
  5036. }
  5037. const currentArea = userInfo.country_code;
  5038. const areas = Object.keys(cartConfig.rgUserCountryOptions).filter(area => area !== 'help');
  5039. if (currentArea && areas.length > 0) {
  5040. this.#area = currentArea;
  5041. logStatus.success();
  5042. return {
  5043. currentArea: currentArea,
  5044. areas: areas
  5045. };
  5046. }
  5047. logStatus.error('Error: get country info filed');
  5048. return {};
  5049. }
  5050. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5051. return {};
  5052. }
  5053. logStatus.error(`${result}:${statusText}(${status})`);
  5054. return {};
  5055. } catch (error) {
  5056. throwError(error, 'Steam.getAreaInfo');
  5057. return {};
  5058. }
  5059. }
  5060. async #changeArea(area) {
  5061. try {
  5062. if (this.#areaStatus === 'waiting') {
  5063. await new Promise(resolve => {
  5064. const checker = setInterval(() => {
  5065. if (this.#areaStatus !== 'waiting') {
  5066. clearInterval(checker);
  5067. resolve(true);
  5068. }
  5069. });
  5070. });
  5071. }
  5072. if (this.#area === area || !area && this.#area !== 'CN') {
  5073. return true;
  5074. }
  5075. this.#areaStatus = 'waiting';
  5076. let aimedArea = area;
  5077. if (!aimedArea) {
  5078. const {
  5079. currentArea,
  5080. areas
  5081. } = await this.#getAreaInfo();
  5082. if (!currentArea || !areas) {
  5083. this.#areaStatus = 'error';
  5084. return false;
  5085. }
  5086. if (currentArea !== 'CN') {
  5087. this.#areaStatus = 'skip';
  5088. scripts_echoLog({
  5089. text: 'notNeededChangeArea'
  5090. });
  5091. return 'skip';
  5092. }
  5093. const anotherArea = areas.filter(area => area && area !== 'CN');
  5094. if (!anotherArea || anotherArea.length === 0) {
  5095. this.#areaStatus = 'noAnotherArea';
  5096. scripts_echoLog({
  5097. text: 'noAnotherArea'
  5098. });
  5099. return false;
  5100. }
  5101. [ aimedArea ] = anotherArea;
  5102. }
  5103. const logStatus = scripts_echoLog({
  5104. text: i18n('changingArea', aimedArea)
  5105. });
  5106. const {
  5107. result,
  5108. statusText,
  5109. status,
  5110. data
  5111. } = await tools_httpRequest({
  5112. url: 'https://store.steampowered.com/country/setcountry',
  5113. method: 'POST',
  5114. headers: {
  5115. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5116. },
  5117. data: $.param({
  5118. cc: aimedArea,
  5119. sessionid: this.#auth.storeSessionID
  5120. })
  5121. });
  5122. if (result === 'Success') {
  5123. if (data?.status === 200 && data.responseText === 'true') {
  5124. const {
  5125. currentArea
  5126. } = await this.#getAreaInfo();
  5127. if (currentArea) {
  5128. this.#area = currentArea;
  5129. if (!this.#oldArea) {
  5130. this.#oldArea = currentArea;
  5131. }
  5132. }
  5133. if (currentArea === aimedArea) {
  5134. this.#areaStatus = 'success';
  5135. logStatus.success();
  5136. return currentArea;
  5137. }
  5138. this.#areaStatus = 'error';
  5139. logStatus.error('Error: change country filed');
  5140. return 'CN';
  5141. }
  5142. this.#areaStatus = 'error';
  5143. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5144. return 'CN';
  5145. }
  5146. this.#areaStatus = 'error';
  5147. logStatus.error(`${result}:${statusText}(${status})`);
  5148. return 'CN';
  5149. } catch (error) {
  5150. this.#areaStatus = 'error';
  5151. throwError(error, 'Steam.changeArea');
  5152. return false;
  5153. }
  5154. }
  5155. async #joinGroup(groupName) {
  5156. try {
  5157. if (this.#ASF) {
  5158. if (await this.#ASF.joinGroup(groupName)) {
  5159. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5160. return true;
  5161. }
  5162. return false;
  5163. }
  5164. const logStatus = scripts_echoLog({
  5165. type: 'joiningSteamGroup',
  5166. text: groupName
  5167. });
  5168. const {
  5169. result,
  5170. statusText,
  5171. status,
  5172. data
  5173. } = await tools_httpRequest({
  5174. url: `https://steamcommunity.com/groups/${groupName}`,
  5175. method: 'POST',
  5176. headers: {
  5177. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5178. },
  5179. data: $.param({
  5180. action: 'join',
  5181. sessionID: this.#auth.communitySessionID
  5182. })
  5183. });
  5184. if (result === 'Success') {
  5185. if (data?.status === 200 && !data.responseText.includes('grouppage_join_area')) {
  5186. logStatus.success();
  5187. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5188. return true;
  5189. }
  5190. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5191. return false;
  5192. }
  5193. logStatus.error(`${result}:${statusText}(${status})`);
  5194. return false;
  5195. } catch (error) {
  5196. throwError(error, 'Steam.joinGroup');
  5197. return false;
  5198. }
  5199. }
  5200. async #leaveGroup(groupName) {
  5201. try {
  5202. if (this.whiteList.groups.includes(groupName)) {
  5203. scripts_echoLog({
  5204. type: 'whiteList',
  5205. text: 'Steam.leaveGroup',
  5206. id: groupName
  5207. });
  5208. return true;
  5209. }
  5210. if (this.#ASF) {
  5211. return await this.#ASF.leaveGroup(groupName);
  5212. }
  5213. const groupId = await this.#getGroupId(groupName);
  5214. if (!groupId) {
  5215. return false;
  5216. }
  5217. const logStatus = scripts_echoLog({
  5218. type: 'leavingSteamGroup',
  5219. text: groupName
  5220. });
  5221. const {
  5222. result,
  5223. statusText,
  5224. status,
  5225. data
  5226. } = await tools_httpRequest({
  5227. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5228. method: 'POST',
  5229. headers: {
  5230. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5231. },
  5232. data: $.param({
  5233. sessionID: this.#auth.communitySessionID,
  5234. action: 'leaveGroup',
  5235. groupId: groupId
  5236. })
  5237. });
  5238. if (result === 'Success') {
  5239. if (data?.status === 200 && data.finalUrl.includes('groups') && $(data.responseText.replace(/<img.*?>/g, '').toLowerCase()).find(`a[href='https://steamcommunity.com/groups/${groupName.toLowerCase()}']`).length === 0) {
  5240. logStatus.success();
  5241. return true;
  5242. }
  5243. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5244. return false;
  5245. }
  5246. logStatus.error(`${result}:${statusText}(${status})`);
  5247. return false;
  5248. } catch (error) {
  5249. throwError(error, 'Steam.leaveGroup');
  5250. return false;
  5251. }
  5252. }
  5253. async #getGroupId(groupName) {
  5254. try {
  5255. const logStatus = scripts_echoLog({
  5256. type: 'gettingSteamGroupId',
  5257. text: groupName
  5258. });
  5259. const groupId = this.#cache.group[groupName];
  5260. if (groupId) {
  5261. logStatus.success();
  5262. return groupId;
  5263. }
  5264. const {
  5265. result,
  5266. statusText,
  5267. status,
  5268. data
  5269. } = await tools_httpRequest({
  5270. url: `https://steamcommunity.com/groups/${groupName}`,
  5271. method: 'GET',
  5272. headers: {
  5273. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5274. }
  5275. });
  5276. if (result === 'Success') {
  5277. if (data?.status === 200) {
  5278. const groupId = data.responseText.match(/OpenGroupChat\( '([0-9]+)'/)?.[1];
  5279. if (groupId) {
  5280. this.#setCache('group', groupName, groupId);
  5281. logStatus.success();
  5282. return groupId;
  5283. }
  5284. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5285. return false;
  5286. }
  5287. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5288. return false;
  5289. }
  5290. logStatus.error(`${result}:${statusText}(${status})`);
  5291. return false;
  5292. } catch (error) {
  5293. throwError(error, 'Steam.getGroupID');
  5294. return false;
  5295. }
  5296. }
  5297. async #joinOfficialGroup(gameId) {
  5298. try {
  5299. if (this.#ASF) {
  5300. if (await this.#ASF.joinGroup(gameId)) {
  5301. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5302. return true;
  5303. }
  5304. return false;
  5305. }
  5306. const logStatus = scripts_echoLog({
  5307. type: 'joiningSteamOfficialGroup',
  5308. text: gameId
  5309. });
  5310. const {
  5311. result,
  5312. statusText,
  5313. status,
  5314. data
  5315. } = await tools_httpRequest({
  5316. url: `https://steamcommunity.com/games/${gameId}?action=join&sessionID=${this.#auth.communitySessionID}`,
  5317. method: 'GET',
  5318. headers: {
  5319. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5320. }
  5321. });
  5322. if (result === 'Success') {
  5323. if (data?.status === 200 && !data.responseText.includes('id="publicGroupJoin"')) {
  5324. logStatus.success();
  5325. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5326. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5327. if (groupId) {
  5328. this.#setCache('officialGroup', gameId, groupId);
  5329. }
  5330. return true;
  5331. }
  5332. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5333. return false;
  5334. }
  5335. logStatus.error(`${result}:${statusText}(${status})`);
  5336. return false;
  5337. } catch (error) {
  5338. throwError(error, 'Steam.joinOfficialGroup');
  5339. return false;
  5340. }
  5341. }
  5342. async #leaveOfficialGroup(gameId) {
  5343. try {
  5344. if (this.whiteList.officialGroups.includes(gameId)) {
  5345. scripts_echoLog({
  5346. type: 'whiteList',
  5347. text: 'Steam.leaveOfficialGroup',
  5348. id: gameId
  5349. });
  5350. return true;
  5351. }
  5352. if (this.#ASF) {
  5353. return await this.#ASF.leaveGroup(gameId);
  5354. }
  5355. const groupId = await this.#getOfficialGroupId(gameId);
  5356. if (!groupId) {
  5357. return false;
  5358. }
  5359. const logStatus = scripts_echoLog({
  5360. type: 'leavingSteamOfficialGroup',
  5361. text: gameId
  5362. });
  5363. const {
  5364. result,
  5365. statusText,
  5366. status,
  5367. data
  5368. } = await tools_httpRequest({
  5369. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5370. method: 'POST',
  5371. headers: {
  5372. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5373. },
  5374. data: $.param({
  5375. sessionID: this.#auth.communitySessionID,
  5376. action: 'leaveGroup',
  5377. groupId: groupId
  5378. })
  5379. });
  5380. if (result === 'Success') {
  5381. if (data?.status === 200) {
  5382. const {
  5383. result: resultR,
  5384. statusText: statusTextR,
  5385. status: statusR,
  5386. data: dataR
  5387. } = await tools_httpRequest({
  5388. url: `https://steamcommunity.com/games/${gameId}`,
  5389. method: 'GET',
  5390. headers: {
  5391. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5392. }
  5393. });
  5394. if (resultR === 'Success') {
  5395. if (dataR?.status === 200 && dataR.responseText.includes('id="publicGroupJoin"')) {
  5396. logStatus.success();
  5397. return true;
  5398. }
  5399. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5400. return false;
  5401. }
  5402. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5403. return false;
  5404. }
  5405. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5406. return false;
  5407. }
  5408. logStatus.error(`${result}:${statusText}(${status})`);
  5409. return false;
  5410. } catch (error) {
  5411. throwError(error, 'Steam.leaveOfficialGroup');
  5412. return false;
  5413. }
  5414. }
  5415. async #getOfficialGroupId(gameId) {
  5416. try {
  5417. const logStatus = scripts_echoLog({
  5418. type: 'gettingSteamOfficialGroupId',
  5419. text: gameId
  5420. });
  5421. const groupId = this.#cache.officialGroup[gameId];
  5422. if (groupId) {
  5423. logStatus.success();
  5424. return groupId;
  5425. }
  5426. const {
  5427. result,
  5428. statusText,
  5429. status,
  5430. data
  5431. } = await tools_httpRequest({
  5432. url: `https://steamcommunity.com/games/${gameId}`,
  5433. method: 'GET',
  5434. headers: {
  5435. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5436. }
  5437. });
  5438. if (result === 'Success') {
  5439. if (data?.status === 200) {
  5440. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5441. if (groupId) {
  5442. this.#setCache('officialGroup', gameId, groupId);
  5443. logStatus.success();
  5444. return groupId;
  5445. }
  5446. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5447. return false;
  5448. }
  5449. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5450. return false;
  5451. }
  5452. logStatus.error(`${result}:${statusText}(${status})`);
  5453. return false;
  5454. } catch (error) {
  5455. throwError(error, 'Steam.getGroupID');
  5456. return false;
  5457. }
  5458. }
  5459. async #addToWishlist(gameId) {
  5460. try {
  5461. if (this.#ASF) {
  5462. if (await this.#ASF.addToWishlist(gameId)) {
  5463. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5464. return true;
  5465. }
  5466. return false;
  5467. }
  5468. const logStatus = scripts_echoLog({
  5469. type: 'addingToWishlist',
  5470. text: gameId
  5471. });
  5472. const {
  5473. result,
  5474. data
  5475. } = await tools_httpRequest({
  5476. url: 'https://store.steampowered.com/api/addtowishlist',
  5477. method: 'POST',
  5478. headers: {
  5479. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5480. },
  5481. data: $.param({
  5482. sessionid: this.#auth.storeSessionID,
  5483. appid: gameId
  5484. }),
  5485. dataType: 'json'
  5486. });
  5487. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  5488. logStatus.success();
  5489. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5490. return true;
  5491. }
  5492. const {
  5493. result: resultR,
  5494. statusText: statusTextR,
  5495. status: statusR,
  5496. data: dataR
  5497. } = await tools_httpRequest({
  5498. url: `https://store.steampowered.com/app/${gameId}`,
  5499. method: 'GET'
  5500. });
  5501. if (resultR === 'Success') {
  5502. if (dataR?.status === 200) {
  5503. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  5504. logStatus.warning(i18n('changeAreaNotice'));
  5505. if (!await this.#changeArea()) {
  5506. return false;
  5507. }
  5508. return await this.#addToWishlist(gameId);
  5509. }
  5510. if (dataR.responseText.includes('class="queue_actions_ctn"') && dataR.responseText.includes('class="already_in_library"')) {
  5511. logStatus.success();
  5512. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5513. return true;
  5514. } else if (dataR.responseText.includes('class="queue_actions_ctn"') && dataR.responseText.includes('id="add_to_wishlist_area_success" style="display: none;') || !dataR.responseText.includes('class="queue_actions_ctn"')) {
  5515. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  5516. return false;
  5517. }
  5518. logStatus.success();
  5519. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5520. return true;
  5521. }
  5522. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5523. return false;
  5524. }
  5525. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5526. return false;
  5527. } catch (error) {
  5528. throwError(error, 'Steam.addToWishlist');
  5529. return false;
  5530. }
  5531. }
  5532. async #removeFromWishlist(gameId) {
  5533. try {
  5534. if (this.whiteList.wishlists.includes(gameId)) {
  5535. scripts_echoLog({
  5536. type: 'whiteList',
  5537. text: 'Steam.removeFromWishlist',
  5538. id: gameId
  5539. });
  5540. return true;
  5541. }
  5542. if (this.#ASF) {
  5543. return await this.#ASF.removeFromWishlist(gameId);
  5544. }
  5545. const logStatus = scripts_echoLog({
  5546. type: 'removingFromWishlist',
  5547. text: gameId
  5548. });
  5549. const {
  5550. result,
  5551. data
  5552. } = await tools_httpRequest({
  5553. url: 'https://store.steampowered.com/api/removefromwishlist',
  5554. method: 'POST',
  5555. headers: {
  5556. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5557. },
  5558. data: $.param({
  5559. sessionid: this.#auth.storeSessionID,
  5560. appid: gameId
  5561. }),
  5562. dataType: 'json'
  5563. });
  5564. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  5565. logStatus.success();
  5566. return true;
  5567. }
  5568. const {
  5569. result: resultR,
  5570. statusText: statusTextR,
  5571. status: statusR,
  5572. data: dataR
  5573. } = await tools_httpRequest({
  5574. url: `https://store.steampowered.com/app/${gameId}`,
  5575. method: 'GET'
  5576. });
  5577. if (resultR === 'Success') {
  5578. if (dataR?.status === 200) {
  5579. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  5580. logStatus.warning(i18n('changeAreaNotice'));
  5581. const result = await this.#changeArea();
  5582. if (!result || result === 'CN' || result === 'skip') {
  5583. return false;
  5584. }
  5585. return await this.#removeFromWishlist(gameId);
  5586. }
  5587. if (dataR.responseText.includes('class="queue_actions_ctn"') && (dataR.responseText.includes('ds_owned_flag ds_flag') || dataR.responseText.includes('add_to_wishlist_area'))) {
  5588. logStatus.success();
  5589. return true;
  5590. }
  5591. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  5592. return false;
  5593. }
  5594. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5595. return false;
  5596. }
  5597. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5598. return false;
  5599. } catch (error) {
  5600. throwError(error, 'Steam.removeFromWishlist');
  5601. return false;
  5602. }
  5603. }
  5604. async #toggleFollowGame(gameId, doTask) {
  5605. try {
  5606. if (!doTask && this.whiteList.follows.includes(gameId)) {
  5607. scripts_echoLog({
  5608. type: 'whiteList',
  5609. text: 'Steam.unfollowGame',
  5610. id: gameId
  5611. });
  5612. return true;
  5613. }
  5614. if (this.#ASF) {
  5615. if (await this.#ASF.toggleFollowGame(gameId, doTask)) {
  5616. if (doTask) {
  5617. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  5618. }
  5619. return true;
  5620. }
  5621. return false;
  5622. }
  5623. const logStatus = scripts_echoLog({
  5624. type: `${doTask ? '' : 'un'}followingGame`,
  5625. text: gameId
  5626. });
  5627. const requestData = {
  5628. sessionid: this.#auth.storeSessionID,
  5629. appid: gameId
  5630. };
  5631. if (!doTask) {
  5632. requestData.unfollow = '1';
  5633. }
  5634. const {
  5635. result,
  5636. data
  5637. } = await tools_httpRequest({
  5638. url: 'https://store.steampowered.com/explore/followgame/',
  5639. method: 'POST',
  5640. headers: {
  5641. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5642. },
  5643. data: $.param(requestData)
  5644. });
  5645. if (result === 'Success' && data?.status === 200 && data.responseText === 'true') {
  5646. logStatus.success();
  5647. return true;
  5648. }
  5649. const followed = await this.#isFollowedGame(gameId);
  5650. if (this.#area === 'CN' && followed === 'areaLocked') {
  5651. logStatus.warning(i18n('changeAreaNotice'));
  5652. if (!await this.#changeArea()) {
  5653. return false;
  5654. }
  5655. return await this.#toggleFollowGame(gameId, doTask);
  5656. }
  5657. if (doTask === followed) {
  5658. logStatus.success();
  5659. if (doTask) {
  5660. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  5661. }
  5662. return true;
  5663. }
  5664. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5665. return false;
  5666. } catch (error) {
  5667. throwError(error, 'Steam.toggleFollowGame');
  5668. return false;
  5669. }
  5670. }
  5671. async #isFollowedGame(gameId) {
  5672. try {
  5673. const {
  5674. result,
  5675. data
  5676. } = await tools_httpRequest({
  5677. url: `https://store.steampowered.com/app/${gameId}`,
  5678. method: 'GET'
  5679. });
  5680. if (result === 'Success') {
  5681. if (data?.status === 200) {
  5682. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  5683. return 'areaLocked';
  5684. }
  5685. if ($(data.responseText.replace(/<img.*?>/g, '')).find('.queue_control_button.queue_btn_follow>.btnv6_blue_hoverfade.btn_medium.queue_btn_active').css('display') !== 'none') {
  5686. return true;
  5687. }
  5688. return false;
  5689. }
  5690. return false;
  5691. }
  5692. return false;
  5693. } catch (error) {
  5694. throwError(error, 'Steam.isFollowedGame');
  5695. return false;
  5696. }
  5697. }
  5698. async #toggleForum(gameId, doTask = true) {
  5699. try {
  5700. if (!doTask && this.whiteList.forums.includes(gameId)) {
  5701. scripts_echoLog({
  5702. type: 'whiteList',
  5703. text: 'Steam.unsubscribeForum',
  5704. id: gameId
  5705. });
  5706. return true;
  5707. }
  5708. const forumId = await this.#getForumId(gameId);
  5709. if (!forumId) {
  5710. return false;
  5711. }
  5712. const logStatus = scripts_echoLog({
  5713. type: `${doTask ? '' : 'un'}subscribingForum`,
  5714. text: gameId
  5715. });
  5716. const [ id, feature ] = forumId.split('_');
  5717. const {
  5718. result,
  5719. statusText,
  5720. status,
  5721. data
  5722. } = await tools_httpRequest({
  5723. url: `https://steamcommunity.com/forum/${id}/General/${doTask ? '' : 'un'}subscribe/${feature || '0'}/`,
  5724. method: 'POST',
  5725. responseType: 'json',
  5726. headers: {
  5727. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5728. },
  5729. data: $.param({
  5730. sessionid: this.#auth.communitySessionID
  5731. })
  5732. });
  5733. if (result === 'Success') {
  5734. if (data?.status === 200 && (data.response?.success === 1 || data.response?.success === 29)) {
  5735. if (doTask) {
  5736. this.tasks.forums = unique([ ...this.tasks.forums, gameId ]);
  5737. }
  5738. logStatus.success();
  5739. return true;
  5740. }
  5741. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5742. return true;
  5743. }
  5744. logStatus.error(`${result}:${statusText}(${status})`);
  5745. return true;
  5746. } catch (error) {
  5747. throwError(error, 'Steam.toggleForum');
  5748. return true;
  5749. }
  5750. }
  5751. async #getForumId(gameId) {
  5752. try {
  5753. const logStatus = scripts_echoLog({
  5754. type: 'gettingForumId',
  5755. text: gameId
  5756. });
  5757. const forumId = this.#cache.forum[gameId];
  5758. if (forumId) {
  5759. logStatus.success();
  5760. return forumId;
  5761. }
  5762. const {
  5763. result,
  5764. statusText,
  5765. status,
  5766. data
  5767. } = await tools_httpRequest({
  5768. url: `https://steamcommunity.com/app/${gameId}/discussions/`,
  5769. method: 'GET'
  5770. });
  5771. if (result === 'Success') {
  5772. if (data?.status === 200) {
  5773. const forumId = data.responseText?.match(/General_([\d]+(_[\d]+)?)/)?.[1];
  5774. if (forumId) {
  5775. this.#setCache('forum', gameId, forumId);
  5776. logStatus.success();
  5777. return forumId;
  5778. }
  5779. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5780. return false;
  5781. }
  5782. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5783. return false;
  5784. }
  5785. logStatus.error(`${result}:${statusText}(${status})`);
  5786. return false;
  5787. } catch (error) {
  5788. throwError(error, 'Steam.getForumId');
  5789. return false;
  5790. }
  5791. }
  5792. async #toggleFavoriteWorkshop(id, doTask = true) {
  5793. try {
  5794. if (!doTask && this.whiteList.workshops.includes(id)) {
  5795. scripts_echoLog({
  5796. type: 'whiteList',
  5797. text: 'Steam.unfavoriteWorkshop',
  5798. id: id
  5799. });
  5800. return true;
  5801. }
  5802. const appid = await this.#getWorkshopAppId(id);
  5803. if (!appid) {
  5804. return false;
  5805. }
  5806. const logStatus = scripts_echoLog({
  5807. type: doTask ? 'favoritingWorkshop' : 'unfavoritingWorkshop',
  5808. text: id
  5809. });
  5810. const {
  5811. result,
  5812. statusText,
  5813. status,
  5814. data
  5815. } = await tools_httpRequest({
  5816. url: `https://steamcommunity.com/sharedfiles/${doTask ? '' : 'un'}favorite`,
  5817. method: 'POST',
  5818. headers: {
  5819. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5820. },
  5821. data: $.param({
  5822. id: id,
  5823. appid: appid,
  5824. sessionid: this.#auth.communitySessionID
  5825. })
  5826. });
  5827. if (result === 'Success') {
  5828. if (data?.status === 200 && !data.responseText) {
  5829. if (doTask) {
  5830. this.tasks.workshops = unique([ ...this.tasks.workshops, id ]);
  5831. }
  5832. logStatus.success();
  5833. return true;
  5834. }
  5835. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5836. return false;
  5837. }
  5838. logStatus.error(`${result}:${statusText}(${status})`);
  5839. return false;
  5840. } catch (error) {
  5841. throwError(error, 'Steam.toggleFavoriteWorkshop');
  5842. return false;
  5843. }
  5844. }
  5845. async #getWorkshopAppId(id) {
  5846. try {
  5847. const logStatus = scripts_echoLog({
  5848. type: 'gettingWorkshopAppId',
  5849. text: id
  5850. });
  5851. const appId = this.#cache.workshop[id];
  5852. if (appId) {
  5853. logStatus.success();
  5854. return appId;
  5855. }
  5856. const {
  5857. result,
  5858. statusText,
  5859. status,
  5860. data
  5861. } = await tools_httpRequest({
  5862. url: `https://steamcommunity.com/sharedfiles/filedetails/?id=${id}`,
  5863. method: 'GET'
  5864. });
  5865. if (result === 'Success') {
  5866. if (data?.status === 200) {
  5867. const appId = data.responseText.match(/<input type="hidden" name="appid" value="([\d]+?)" \/>/)?.[1];
  5868. if (appId) {
  5869. this.#setCache('workshop', id, appId);
  5870. logStatus.success();
  5871. return appId;
  5872. }
  5873. logStatus.error('Error: getWorkshopAppId failed');
  5874. return false;
  5875. }
  5876. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5877. return false;
  5878. }
  5879. logStatus.error(`${result}:${statusText}(${status})`);
  5880. return false;
  5881. } catch (error) {
  5882. throwError(error, 'Steam.getWorkshopAppId');
  5883. return false;
  5884. }
  5885. }
  5886. async #voteUpWorkshop(id) {
  5887. try {
  5888. const logStatus = scripts_echoLog({
  5889. type: 'votingUpWorkshop',
  5890. text: id
  5891. });
  5892. const {
  5893. result,
  5894. statusText,
  5895. status,
  5896. data
  5897. } = await tools_httpRequest({
  5898. url: 'https://steamcommunity.com/sharedfiles/voteup',
  5899. method: 'POST',
  5900. responseType: 'json',
  5901. headers: {
  5902. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5903. },
  5904. data: $.param({
  5905. id: id,
  5906. sessionid: this.#auth.communitySessionID
  5907. })
  5908. });
  5909. if (result === 'Success') {
  5910. if (data?.status === 200 && data.response?.success === 1) {
  5911. logStatus.success();
  5912. return true;
  5913. }
  5914. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5915. return true;
  5916. }
  5917. logStatus.error(`${result}:${statusText}(${status})`);
  5918. return true;
  5919. } catch (error) {
  5920. throwError(error, 'Steam.voteupWorkshop');
  5921. return true;
  5922. }
  5923. }
  5924. async #toggleCurator(curatorId, doTask = true) {
  5925. try {
  5926. if (!doTask && this.whiteList.curators.includes(curatorId)) {
  5927. scripts_echoLog({
  5928. type: 'whiteList',
  5929. text: 'Steam.unfollowCurator',
  5930. id: curatorId
  5931. });
  5932. return true;
  5933. }
  5934. if (this.#ASF) {
  5935. return await this.#ASF.toggleCurator(curatorId, doTask);
  5936. }
  5937. const logStatus = scripts_echoLog({
  5938. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  5939. text: curatorId
  5940. });
  5941. const {
  5942. result,
  5943. statusText,
  5944. status,
  5945. data
  5946. } = await tools_httpRequest({
  5947. url: 'https://store.steampowered.com/curators/ajaxfollow',
  5948. method: 'POST',
  5949. headers: {
  5950. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5951. },
  5952. data: $.param({
  5953. clanid: curatorId,
  5954. sessionid: this.#auth.storeSessionID,
  5955. follow: doTask
  5956. }),
  5957. dataType: 'json'
  5958. });
  5959. if (result === 'Success') {
  5960. if (data?.status === 200 && data.response?.success?.success === 1) {
  5961. logStatus.success();
  5962. return true;
  5963. }
  5964. logStatus.error(`Error:${data?.statusText}(${data?.response?.success}` || `${data?.status})`);
  5965. return false;
  5966. }
  5967. logStatus.error(`${result}:${statusText}(${status})`);
  5968. return false;
  5969. } catch (error) {
  5970. throwError(error, 'Steam.toggleCurator');
  5971. return false;
  5972. }
  5973. }
  5974. async getCuratorId(path, name) {
  5975. try {
  5976. const logStatus = scripts_echoLog({
  5977. type: 'gettingCuratorId',
  5978. text: `${path}/${name}`
  5979. });
  5980. const curatorId = this.#cache.curator[`${path}/${name}`];
  5981. if (curatorId) {
  5982. logStatus.success();
  5983. return curatorId;
  5984. }
  5985. const {
  5986. result,
  5987. statusText,
  5988. status,
  5989. data
  5990. } = await tools_httpRequest({
  5991. url: `https://store.steampowered.com/${path}/${name}`,
  5992. method: 'GET',
  5993. headers: {
  5994. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5995. }
  5996. });
  5997. if (result === 'Success') {
  5998. if (data?.status === 200) {
  5999. const curatorId = data.responseText.match(/g_pagingData.*?"clanid":([\d]+)/)?.[1];
  6000. if (curatorId) {
  6001. this.#setCache('curator', `${path}/${name}`, curatorId);
  6002. logStatus.success();
  6003. return curatorId;
  6004. }
  6005. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6006. return false;
  6007. }
  6008. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6009. return false;
  6010. }
  6011. logStatus.error(`${result}:${statusText}(${status})`);
  6012. return false;
  6013. } catch (error) {
  6014. throwError(error, 'Steam.getCuratorID');
  6015. return false;
  6016. }
  6017. }
  6018. async #toggleCuratorLike(link, doTask = true) {
  6019. try {
  6020. const [ path, name ] = link.split('/');
  6021. if (!(path && name)) {
  6022. scripts_echoLog({
  6023. text: i18n('errorLink', link)
  6024. });
  6025. return false;
  6026. }
  6027. const curatorId = await this.getCuratorId(path, name);
  6028. if (curatorId) {
  6029. return await this.#toggleCurator(curatorId, doTask);
  6030. }
  6031. return false;
  6032. } catch (error) {
  6033. throwError(error, 'Steam.toggleCuratorLike');
  6034. return false;
  6035. }
  6036. }
  6037. async #getAnnouncementParams(appId, viewId) {
  6038. try {
  6039. const logStatus = scripts_echoLog({
  6040. type: 'gettingAnnouncementParams',
  6041. text: appId,
  6042. id: viewId
  6043. });
  6044. const {
  6045. result,
  6046. statusText,
  6047. status,
  6048. data
  6049. } = await tools_httpRequest({
  6050. url: `https://store.steampowered.com/events/ajaxgetpartnerevent?appid=${appId}&announcement_gid=${viewId}&lang_list=6_0&last_modified_time=0&origin=https:%2F%2Fstore.steampowered.com&for_edit=false`,
  6051. method: 'GET',
  6052. responseType: 'json',
  6053. headers: {
  6054. Host: 'store.steampowered.com',
  6055. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6056. }
  6057. });
  6058. if (result === 'Success') {
  6059. if (data?.status === 200 && data?.response?.success === 1) {
  6060. const {
  6061. clanid,
  6062. gid
  6063. } = data.response.event?.announcement_body || {};
  6064. if (clanid) {
  6065. logStatus.success();
  6066. return {
  6067. clanId: clanid,
  6068. gid: gid
  6069. };
  6070. }
  6071. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6072. return {};
  6073. }
  6074. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6075. return {};
  6076. }
  6077. logStatus.error(`${result}:${statusText}(${status})`);
  6078. return {};
  6079. } catch (error) {
  6080. throwError(error, 'Steam.likeAnnouncement');
  6081. return {};
  6082. }
  6083. }
  6084. async #likeAnnouncement(id) {
  6085. try {
  6086. const [ appId, viewId ] = id.split('/');
  6087. if (!(appId && viewId)) {
  6088. scripts_echoLog({}).error(`${i18n('missParams')}(id)`);
  6089. return false;
  6090. }
  6091. const {
  6092. clanId,
  6093. gid
  6094. } = await this.#getAnnouncementParams(appId, viewId);
  6095. if (!clanId) {
  6096. return false;
  6097. }
  6098. const logStatus = scripts_echoLog({
  6099. type: 'likingAnnouncement',
  6100. text: appId,
  6101. id: viewId
  6102. });
  6103. const {
  6104. result,
  6105. statusText,
  6106. status,
  6107. data
  6108. } = await tools_httpRequest({
  6109. url: `https://store.steampowered.com/updated/ajaxrateupdate/${gid || viewId}`,
  6110. method: 'POST',
  6111. headers: {
  6112. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6113. Host: 'store.steampowered.com',
  6114. Origin: 'https://store.steampowered.com',
  6115. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6116. },
  6117. data: $.param({
  6118. sessionid: this.#auth.storeSessionID,
  6119. voteup: 1,
  6120. clanid: clanId,
  6121. ajax: 1
  6122. }),
  6123. dataType: 'json'
  6124. });
  6125. if (result === 'Success') {
  6126. if (data?.status === 200 && data.response.success === 1) {
  6127. logStatus.success();
  6128. return true;
  6129. }
  6130. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6131. return false;
  6132. }
  6133. logStatus.error(`${result}:${statusText}(${status})`);
  6134. return false;
  6135. } catch (error) {
  6136. throwError(error, 'Steam.likeAnnouncement');
  6137. return false;
  6138. }
  6139. }
  6140. async #appid2subid(id) {
  6141. try {
  6142. const logStatus = scripts_echoLog({
  6143. type: 'gettingSubid',
  6144. text: id
  6145. });
  6146. const {
  6147. result,
  6148. statusText,
  6149. status,
  6150. data
  6151. } = await tools_httpRequest({
  6152. url: `https://store.steampowered.com/app/${id}`,
  6153. method: 'GET',
  6154. headers: {
  6155. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6156. }
  6157. });
  6158. if (result === 'Success') {
  6159. if (data?.status === 200) {
  6160. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6161. logStatus.success(i18n('owned'));
  6162. return false;
  6163. }
  6164. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6165. logStatus.warning(i18n('changeAreaNotice'));
  6166. const result = await this.#changeArea();
  6167. if (!result || result === 'CN' || result === 'skip') {
  6168. return false;
  6169. }
  6170. return await this.#appid2subid(id);
  6171. }
  6172. let subid = data.responseText.match(/name="subid" value="([\d]+?)"/)?.[1];
  6173. if (subid) {
  6174. logStatus.success();
  6175. return subid;
  6176. }
  6177. subid = data.responseText.match(/AddFreeLicense\(\s*(\d+)/)?.[1];
  6178. if (subid) {
  6179. logStatus.success();
  6180. return subid;
  6181. }
  6182. logStatus.error(`Error:${i18n('noSubid')}`);
  6183. return false;
  6184. }
  6185. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6186. return false;
  6187. }
  6188. logStatus.error(`${result}:${statusText}(${status})`);
  6189. return false;
  6190. } catch (error) {
  6191. throwError(error, 'Steam.appid2subid');
  6192. return false;
  6193. }
  6194. }
  6195. async #getLicenses() {
  6196. try {
  6197. const logStatus = scripts_echoLog({
  6198. text: i18n('gettingLicenses')
  6199. });
  6200. const {
  6201. result,
  6202. statusText,
  6203. status,
  6204. data
  6205. } = await tools_httpRequest({
  6206. url: `https://store.steampowered.com/dynamicstore/userdata/?t=${new Date().getTime()}`,
  6207. method: 'GET',
  6208. responseType: 'json'
  6209. });
  6210. if (result === 'Success') {
  6211. if (data?.status === 200) {
  6212. logStatus.success();
  6213. return data.response?.rgOwnedPackages;
  6214. }
  6215. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6216. return false;
  6217. }
  6218. logStatus.error(`${result}:${statusText}(${status})`);
  6219. return false;
  6220. } catch (error) {
  6221. throwError(error, 'Steam.getLicenses');
  6222. return false;
  6223. }
  6224. }
  6225. async #addLicense(id) {
  6226. try {
  6227. if (this.#ASF) {
  6228. return await this.#ASF.addLicense(id);
  6229. }
  6230. const [ type, ids ] = id.split('-');
  6231. if (type === 'appid') {
  6232. const subid = await this.#appid2subid(ids);
  6233. if (!subid) {
  6234. return false;
  6235. }
  6236. const logStatus = scripts_echoLog({
  6237. type: 'addingFreeLicense',
  6238. text: ids
  6239. });
  6240. if (!await this.#addFreeLicense(subid, logStatus)) {
  6241. return false;
  6242. }
  6243. const {
  6244. result,
  6245. statusText,
  6246. status,
  6247. data
  6248. } = await tools_httpRequest({
  6249. url: `https://store.steampowered.com/app/${ids}`,
  6250. method: 'GET'
  6251. });
  6252. if (result === 'Success') {
  6253. if (data?.status === 200) {
  6254. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6255. logStatus.success();
  6256. return true;
  6257. }
  6258. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6259. return false;
  6260. }
  6261. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6262. return false;
  6263. }
  6264. logStatus.error(`${result}:${statusText}(${status})`);
  6265. return false;
  6266. } else if (type === 'subid') {
  6267. if (this.#area === 'CN') {
  6268. scripts_echoLog({}).success(i18n('tryChangeAreaNotice'));
  6269. await this.#changeArea();
  6270. }
  6271. const logStatusArr = {};
  6272. const idsArr = ids.split(',');
  6273. for (const subid of idsArr) {
  6274. const logStatus = scripts_echoLog({
  6275. type: 'addingFreeLicenseSubid',
  6276. text: subid
  6277. });
  6278. if (!await this.#addFreeLicense(subid, logStatus)) {
  6279. return false;
  6280. }
  6281. logStatusArr[subid] = logStatus;
  6282. }
  6283. const licenses = await this.#getLicenses();
  6284. if (!licenses) {
  6285. return false;
  6286. }
  6287. for (const subid of idsArr) {
  6288. if (licenses.includes(parseInt(subid, 10))) {
  6289. logStatusArr[subid].success();
  6290. } else {
  6291. logStatusArr[subid].error();
  6292. }
  6293. }
  6294. return true;
  6295. }
  6296. return false;
  6297. } catch (error) {
  6298. throwError(error, 'Steam.addLicense');
  6299. return false;
  6300. }
  6301. }
  6302. async #addFreeLicense(id, logStatusPre) {
  6303. try {
  6304. const logStatus = logStatusPre || scripts_echoLog({
  6305. type: 'addingFreeLicenseSubid',
  6306. text: id
  6307. });
  6308. const {
  6309. result,
  6310. statusText,
  6311. status,
  6312. data
  6313. } = await tools_httpRequest({
  6314. url: `https://store.steampowered.com/freelicense/addfreelicense/${id}`,
  6315. method: 'POST',
  6316. headers: {
  6317. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6318. Host: 'store.steampowered.com',
  6319. Origin: 'https://store.steampowered.com',
  6320. Referer: 'https://store.steampowered.com/account/licenses/'
  6321. },
  6322. data: $.param({
  6323. ajax: true,
  6324. sessionid: this.#auth.storeSessionID
  6325. }),
  6326. dataType: 'json'
  6327. });
  6328. if (result === 'Success') {
  6329. if (data?.status === 200) {
  6330. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6331. logStatus.warning(i18n('changeAreaNotice'));
  6332. const result = await this.#changeArea();
  6333. if (!result || [ 'CN', 'skip' ].includes(result)) {
  6334. return false;
  6335. }
  6336. return await this.#addFreeLicense(id);
  6337. }
  6338. logStatus.success();
  6339. return true;
  6340. }
  6341. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6342. return false;
  6343. }
  6344. logStatus.error(`${result}:${statusText}(${status})`);
  6345. return false;
  6346. } catch (error) {
  6347. throwError(error, 'Steam.addFreeLicense');
  6348. return false;
  6349. }
  6350. }
  6351. async #requestPlayTestAccess(id) {
  6352. try {
  6353. if (this.#ASF) {
  6354. return await this.#ASF.requestPlayTestAccess(id);
  6355. }
  6356. const logStatus = scripts_echoLog({
  6357. type: 'requestingPlayTestAccess',
  6358. text: id
  6359. });
  6360. const {
  6361. result,
  6362. statusText,
  6363. status,
  6364. data
  6365. } = await tools_httpRequest({
  6366. url: `https://store.steampowered.com/ajaxrequestplaytestaccess/${id}`,
  6367. method: 'POST',
  6368. headers: {
  6369. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6370. Host: 'store.steampowered.com',
  6371. Origin: 'https://store.steampowered.com',
  6372. Referer: `https://store.steampowered.com/app/${id}`
  6373. },
  6374. data: $.param({
  6375. sessionid: this.#auth.storeSessionID
  6376. }),
  6377. dataType: 'json'
  6378. });
  6379. if (result === 'Success') {
  6380. if (data?.status === 200 && data?.response?.success === 1) {
  6381. logStatus.success();
  6382. return true;
  6383. }
  6384. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6385. return false;
  6386. }
  6387. logStatus.error(`${result}:${statusText}(${status})`);
  6388. return false;
  6389. } catch (error) {
  6390. throwError(error, 'Steam.requestPlayTestAccess');
  6391. return false;
  6392. }
  6393. }
  6394. async toggle({
  6395. doTask = true,
  6396. groupLinks = [],
  6397. officialGroupLinks = [],
  6398. wishlistLinks = [],
  6399. followLinks = [],
  6400. forumLinks = [],
  6401. workshopLinks = [],
  6402. workshopVoteLinks = [],
  6403. curatorLinks = [],
  6404. curatorLikeLinks = [],
  6405. announcementLinks = [],
  6406. licenseLinks = [],
  6407. playtestLinks = []
  6408. }) {
  6409. try {
  6410. if ([ ...groupLinks, ...officialGroupLinks, ...forumLinks, ...workshopLinks, ...workshopVoteLinks ].length > 0 && !this.#communityInitialized) {
  6411. scripts_echoLog({
  6412. text: i18n('needInit')
  6413. });
  6414. return false;
  6415. }
  6416. if ([ ...wishlistLinks, ...followLinks, ...curatorLinks, ...curatorLikeLinks, ...announcementLinks, ...licenseLinks, ...playtestLinks ].length > 0 && !this.#storeInitialized) {
  6417. scripts_echoLog({
  6418. text: i18n('needInit')
  6419. });
  6420. return false;
  6421. }
  6422. const prom = [];
  6423. if (doTask && !globalOptions.doTask.steam.groups || !doTask && !globalOptions.undoTask.steam.groups) {
  6424. scripts_echoLog({
  6425. type: 'globalOptionsSkip',
  6426. text: 'steam.groups'
  6427. });
  6428. } else {
  6429. const realGroups = this.getRealParams('groups', groupLinks, doTask, link => link.match(/groups\/(.+)\/?/)?.[1]);
  6430. if (realGroups.length > 0) {
  6431. for (const group of realGroups) {
  6432. if (doTask) {
  6433. prom.push(this.#joinGroup(group));
  6434. } else {
  6435. prom.push(this.#leaveGroup(group));
  6436. }
  6437. await delay(1e3);
  6438. }
  6439. }
  6440. }
  6441. if (doTask && !globalOptions.doTask.steam.officialGroups || !doTask && !globalOptions.undoTask.steam.officialGroups) {
  6442. scripts_echoLog({
  6443. type: 'globalOptionsSkip',
  6444. text: 'steam.officialGroups'
  6445. });
  6446. } else {
  6447. const realOfficialGroups = this.getRealParams('officialGroups', officialGroupLinks, doTask, link => link.match(/games\/(.+)\/?/)?.[1]);
  6448. if (realOfficialGroups.length > 0) {
  6449. for (const officialGroup of realOfficialGroups) {
  6450. if (doTask) {
  6451. prom.push(this.#joinOfficialGroup(officialGroup));
  6452. } else {
  6453. prom.push(this.#leaveOfficialGroup(officialGroup));
  6454. }
  6455. await delay(1e3);
  6456. }
  6457. }
  6458. }
  6459. if (doTask && !globalOptions.doTask.steam.wishlists || !doTask && !globalOptions.undoTask.steam.wishlists) {
  6460. scripts_echoLog({
  6461. type: 'globalOptionsSkip',
  6462. text: 'steam.wishlists'
  6463. });
  6464. } else {
  6465. const realWishlists = this.getRealParams('wishlists', wishlistLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6466. if (realWishlists.length > 0) {
  6467. for (const game of realWishlists) {
  6468. if (doTask) {
  6469. prom.push(this.#addToWishlist(game));
  6470. } else {
  6471. prom.push(this.#removeFromWishlist(game));
  6472. }
  6473. await delay(1e3);
  6474. }
  6475. }
  6476. }
  6477. if (doTask && !globalOptions.doTask.steam.follows || !doTask && !globalOptions.undoTask.steam.follows) {
  6478. scripts_echoLog({
  6479. type: 'globalOptionsSkip',
  6480. text: 'steam.follows'
  6481. });
  6482. } else {
  6483. const realFollows = this.getRealParams('follows', followLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6484. if (realFollows.length > 0) {
  6485. for (const game of realFollows) {
  6486. prom.push(this.#toggleFollowGame(game, doTask));
  6487. await delay(1e3);
  6488. }
  6489. }
  6490. }
  6491. if (doTask && !globalOptions.doTask.steam.forums || !doTask && !globalOptions.undoTask.steam.forums) {
  6492. scripts_echoLog({
  6493. type: 'globalOptionsSkip',
  6494. text: 'steam.forums'
  6495. });
  6496. } else {
  6497. const realForums = this.getRealParams('forums', forumLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6498. if (realForums.length > 0) {
  6499. for (const forum of realForums) {
  6500. prom.push(this.#toggleForum(forum, doTask));
  6501. await delay(1e3);
  6502. }
  6503. }
  6504. }
  6505. if (doTask && !globalOptions.doTask.steam.workshops || !doTask && !globalOptions.undoTask.steam.workshops) {
  6506. scripts_echoLog({
  6507. type: 'globalOptionsSkip',
  6508. text: 'steam.workshops'
  6509. });
  6510. } else {
  6511. const realWorkshops = this.getRealParams('workshops', workshopLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  6512. if (realWorkshops.length > 0) {
  6513. for (const workshop of realWorkshops) {
  6514. prom.push(this.#toggleFavoriteWorkshop(workshop, doTask));
  6515. await delay(1e3);
  6516. }
  6517. }
  6518. }
  6519. if (doTask && !globalOptions.doTask.steam.workshopVotes) {
  6520. scripts_echoLog({
  6521. type: 'globalOptionsSkip',
  6522. text: 'steam.workshopVotes'
  6523. });
  6524. } else {
  6525. const realworkshopVotes = this.getRealParams('workshopVotes', workshopVoteLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  6526. if (doTask && realworkshopVotes.length > 0) {
  6527. for (const workshop of realworkshopVotes) {
  6528. prom.push(this.#voteUpWorkshop(workshop));
  6529. await delay(1e3);
  6530. }
  6531. }
  6532. }
  6533. if (doTask && !globalOptions.doTask.steam.curators || !doTask && !globalOptions.undoTask.steam.curators) {
  6534. scripts_echoLog({
  6535. type: 'globalOptionsSkip',
  6536. text: 'steam.curators'
  6537. });
  6538. } else {
  6539. const realCurators = this.getRealParams('curators', curatorLinks, doTask, link => link.match(/curator\/([\d]+)/)?.[1]);
  6540. const realCuratorLikes = this.getRealParams('curatorLikes', curatorLikeLinks, doTask, link => link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3).join('/'));
  6541. if (realCurators.length > 0) {
  6542. for (const curator of realCurators) {
  6543. prom.push(this.#toggleCurator(curator, doTask));
  6544. await delay(1e3);
  6545. }
  6546. }
  6547. if (realCuratorLikes.length > 0) {
  6548. for (const curatorLike of realCuratorLikes) {
  6549. prom.push(this.#toggleCuratorLike(curatorLike, doTask));
  6550. await delay(1e3);
  6551. }
  6552. }
  6553. }
  6554. if (doTask && !globalOptions.doTask.steam.announcements) {
  6555. scripts_echoLog({
  6556. type: 'globalOptionsSkip',
  6557. text: 'steam.announcements'
  6558. });
  6559. } else {
  6560. const realAnnouncements = this.getRealParams('announcements', announcementLinks, doTask, link => {
  6561. if (link.includes('store.steampowered.com')) {
  6562. return link.match(/store\.steampowered\.com\/news\/app\/([\d]+)\/view\/([\d]+)/)?.slice(1, 3).join('/');
  6563. }
  6564. return link.match(/steamcommunity\.com\/games\/([\d]+)\/announcements\/detail\/([\d]+)/)?.slice(1, 3).join('/');
  6565. });
  6566. if (doTask && realAnnouncements.length > 0) {
  6567. for (const id of realAnnouncements) {
  6568. prom.push(this.#likeAnnouncement(id));
  6569. await delay(1e3);
  6570. }
  6571. }
  6572. }
  6573. if (doTask && !globalOptions.doTask.steam.licenses) {
  6574. scripts_echoLog({
  6575. type: 'globalOptionsSkip',
  6576. text: 'steam.licenses'
  6577. });
  6578. } else if (doTask && globalOptions.doTask.steam.licenses && licenseLinks.length > 0) {
  6579. for (const ids of licenseLinks) {
  6580. const [ type, idsStr ] = ids.split('-');
  6581. const idsArr = idsStr.split(',');
  6582. for (const id of idsArr) {
  6583. prom.push(this.#addLicense(`${type}-${id}`));
  6584. await delay(1e3);
  6585. }
  6586. }
  6587. }
  6588. if (doTask && !globalOptions.doTask.steam.playtests) {
  6589. scripts_echoLog({
  6590. type: 'globalOptionsSkip',
  6591. text: 'steam.playtests'
  6592. });
  6593. } else {
  6594. const realPlaytests = this.getRealParams('playtests', playtestLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6595. if (doTask && globalOptions.doTask.steam.playtests && realPlaytests.length > 0) {
  6596. for (const id of realPlaytests) {
  6597. prom.push(this.#requestPlayTestAccess(id));
  6598. await delay(1e3);
  6599. }
  6600. }
  6601. }
  6602. return Promise.all(prom).then(async () => {
  6603. if (this.#oldArea && this.#area !== this.#oldArea) {
  6604. scripts_echoLog({}).warning(i18n('steamFinishNotice') + this.#oldArea);
  6605. await this.#changeArea(this.#oldArea);
  6606. }
  6607. return true;
  6608. });
  6609. } catch (error) {
  6610. throwError(error, 'Steam.toggle');
  6611. return false;
  6612. }
  6613. }
  6614. #setCache(type, name, id) {
  6615. try {
  6616. this.#cache[type][name] = id;
  6617. GM_setValue('steamCache', this.#cache);
  6618. } catch (error) {
  6619. throwError(error, 'Steam.setCache');
  6620. }
  6621. }
  6622. }
  6623. const social_Steam = Steam;
  6624. class Website {
  6625. undoneTasks;
  6626. socialTasks;
  6627. giveawayId;
  6628. socialInitialized = {
  6629. discord: false,
  6630. instagram: false,
  6631. reddit: false,
  6632. twitch: false,
  6633. twitter: false,
  6634. vk: false,
  6635. youtube: false,
  6636. steamStore: false,
  6637. steamCommunity: false
  6638. };
  6639. initialized = false;
  6640. steamTaskType = {
  6641. steamStore: false,
  6642. steamCommunity: false
  6643. };
  6644. social = {};
  6645. async #bind(name, init) {
  6646. try {
  6647. return {
  6648. name: name,
  6649. result: await init
  6650. };
  6651. } catch (error) {
  6652. throwError(error, 'Website.bind');
  6653. return {
  6654. name: name,
  6655. result: false
  6656. };
  6657. }
  6658. }
  6659. async initSocial(action) {
  6660. try {
  6661. const pro = [];
  6662. const tasks = action === 'do' ? this.undoneTasks : this.socialTasks;
  6663. if (tasks.discord) {
  6664. const hasDiscord = Object.values(tasks.discord).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6665. if (hasDiscord && (!this.socialInitialized.discord || !this.social.discord)) {
  6666. this.social.discord = new social_Discord();
  6667. pro.push(this.#bind('discord', this.social.discord.init(action)));
  6668. }
  6669. }
  6670. if (tasks.instagram) {
  6671. const hasInstagram = Object.values(tasks.instagram).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6672. if (hasInstagram && (!this.socialInitialized.instagram || !this.social.instagram)) {
  6673. this.social.instagram = new social_Instagram();
  6674. pro.push(this.#bind('instagram', this.social.instagram.init()));
  6675. }
  6676. }
  6677. if (tasks.reddit) {
  6678. const hasReddit = Object.values(tasks.reddit).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6679. if (hasReddit && (!this.socialInitialized.reddit || !this.social.reddit)) {
  6680. this.social.reddit = new social_Reddit();
  6681. pro.push(this.#bind('reddit', this.social.reddit.init()));
  6682. }
  6683. }
  6684. if (tasks.twitch) {
  6685. const hasTwitch = Object.values(tasks.twitch).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6686. if (hasTwitch && (!this.socialInitialized.twitch || !this.social.twitch)) {
  6687. this.social.twitch = new social_Twitch();
  6688. pro.push(this.#bind('twitch', this.social.twitch.init()));
  6689. }
  6690. }
  6691. if (tasks.twitter) {
  6692. const hasTwitter = Object.values(tasks.twitter).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6693. if (hasTwitter && (!this.socialInitialized.twitter || !this.social.twitter)) {
  6694. this.social.twitter = new social_Twitter();
  6695. pro.push(this.#bind('twitter', this.social.twitter.init()));
  6696. }
  6697. }
  6698. if (tasks.vk) {
  6699. const hasVk = Object.values(tasks.vk).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6700. if (hasVk && (!this.socialInitialized.vk || !this.social.vk)) {
  6701. this.social.vk = new social_Vk();
  6702. pro.push(this.#bind('vk', this.social.vk.init()));
  6703. }
  6704. }
  6705. if (tasks.youtube) {
  6706. const hasYoutube = Object.values(tasks.youtube).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6707. if (hasYoutube && (!this.socialInitialized.youtube || !this.social.youtube)) {
  6708. this.social.youtube = new Youtube();
  6709. pro.push(this.#bind('youtube', this.social.youtube.init()));
  6710. }
  6711. }
  6712. if (tasks.steam) {
  6713. const steamLength = Object.values(tasks.steam).reduce((total, arr) => [ ...total, ...arr ]).length;
  6714. if (steamLength > 0) {
  6715. if (!this.social.steam) {
  6716. this.social.steam = new social_Steam();
  6717. }
  6718. const steamCommunityLength = Object.keys(tasks.steam).map(type => [ 'groupLinks', 'officialGroupLinks', 'forumLinks', 'workshopLinks', 'workshopVoteLinks' ].includes(type) ? tasks.steam?.[type]?.length || 0 : 0).reduce((total, number) => total + number, 0);
  6719. if (steamLength - steamCommunityLength > 0) {
  6720. this.steamTaskType.steamStore = true;
  6721. if (!this.socialInitialized.steamStore) {
  6722. pro.push(this.#bind('steamStore', this.social.steam.init('store')));
  6723. }
  6724. }
  6725. if (steamCommunityLength > 0) {
  6726. if (!this.socialInitialized.steamCommunity) {
  6727. this.steamTaskType.steamCommunity = true;
  6728. pro.push(this.#bind('steamCommunity', this.social.steam.init('community')));
  6729. }
  6730. }
  6731. }
  6732. }
  6733. if (tasks.links && tasks.links.length > 0) {
  6734. this.social.visitLink = visitLink;
  6735. }
  6736. return await Promise.all(pro).then(result => {
  6737. let checked = true;
  6738. for (const data of result) {
  6739. if (data.result) {
  6740. this.socialInitialized[data.name] = data.result;
  6741. } else {
  6742. checked = false;
  6743. }
  6744. }
  6745. return checked;
  6746. });
  6747. } catch (error) {
  6748. throwError(error, 'Website.initSocial');
  6749. return false;
  6750. }
  6751. }
  6752. uniqueTasks(allTasks) {
  6753. try {
  6754. const result = {};
  6755. for (const [ social, types ] of Object.entries(allTasks)) {
  6756. result[social] = {};
  6757. for (const [ type, tasks ] of Object.entries(types)) {
  6758. result[social][type] = unique(tasks);
  6759. }
  6760. }
  6761. return result;
  6762. } catch (error) {
  6763. throwError(error, 'Website.uniqueTasks');
  6764. return allTasks;
  6765. }
  6766. }
  6767. async toggleTask(action) {
  6768. try {
  6769. if (!this.initialized && !this.init()) {
  6770. return false;
  6771. }
  6772. if (!await this.classifyTask(action)) {
  6773. return false;
  6774. }
  6775. await this.initSocial(action);
  6776. const pro = [];
  6777. const doTask = action === 'do';
  6778. const tasks = doTask ? this.undoneTasks : this.socialTasks;
  6779. if (this.socialInitialized.discord === true && this.social.discord) {
  6780. pro.push(this.social.discord.toggle({
  6781. doTask: doTask,
  6782. ...tasks.discord
  6783. }));
  6784. }
  6785. if (this.socialInitialized.instagram === true && this.social.instagram) {
  6786. pro.push(this.social.instagram.toggle({
  6787. doTask: doTask,
  6788. ...tasks.instagram
  6789. }));
  6790. }
  6791. if (this.socialInitialized.reddit === true && this.social.reddit) {
  6792. pro.push(this.social.reddit.toggle({
  6793. doTask: doTask,
  6794. ...tasks.reddit
  6795. }));
  6796. }
  6797. if (this.socialInitialized.twitch === true && this.social.twitch) {
  6798. pro.push(this.social.twitch.toggle({
  6799. doTask: doTask,
  6800. ...tasks.twitch
  6801. }));
  6802. }
  6803. if (this.socialInitialized.twitter === true && this.social.twitter) {
  6804. pro.push(this.social.twitter.toggle({
  6805. doTask: doTask,
  6806. ...tasks.twitter
  6807. }));
  6808. }
  6809. if (this.socialInitialized.vk === true && this.social.vk) {
  6810. pro.push(this.social.vk.toggle({
  6811. doTask: doTask,
  6812. ...tasks.vk
  6813. }));
  6814. }
  6815. if (this.socialInitialized.youtube === true && this.social.youtube) {
  6816. pro.push(this.social.youtube.toggle({
  6817. doTask: doTask,
  6818. ...tasks.youtube
  6819. }));
  6820. }
  6821. if ((this.steamTaskType.steamCommunity ? this.socialInitialized.steamCommunity === true : true) && (this.steamTaskType.steamStore ? this.socialInitialized.steamStore === true : true) && this.social.steam) {
  6822. pro.push(this.social.steam.toggle({
  6823. doTask: doTask,
  6824. ...tasks.steam
  6825. }));
  6826. }
  6827. if (this.social.visitLink && tasks.links && doTask) {
  6828. for (const link of tasks.links) {
  6829. pro.push(this.social.visitLink(link));
  6830. }
  6831. }
  6832. if (doTask && tasks.extra && this.extraDoTask) {
  6833. const hasExtra = Object.values(tasks.extra).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6834. if (hasExtra) {
  6835. pro.push(this.extraDoTask(tasks.extra));
  6836. }
  6837. }
  6838. await Promise.all(pro);
  6839. scripts_echoLog({}).success(i18n('allTasksComplete'));
  6840. return true;
  6841. } catch (error) {
  6842. throwError(error, 'Website.toggleTask');
  6843. return false;
  6844. }
  6845. }
  6846. async doTask() {
  6847. try {
  6848. return await this.toggleTask('do');
  6849. } catch (error) {
  6850. throwError(error, 'Website.doTask');
  6851. return false;
  6852. }
  6853. }
  6854. async undoTask() {
  6855. try {
  6856. return await this.toggleTask('undo');
  6857. } catch (error) {
  6858. throwError(error, 'Website.undoTask');
  6859. return false;
  6860. }
  6861. }
  6862. }
  6863. const website_Website = Website;
  6864. const defaultTasksTemplate = {
  6865. steam: {
  6866. groupLinks: [],
  6867. wishlistLinks: [],
  6868. curatorLinks: [],
  6869. followLinks: []
  6870. },
  6871. vk: {
  6872. nameLinks: []
  6873. }
  6874. };
  6875. const defaultTasks = JSON.stringify(defaultTasksTemplate);
  6876. class FreeAnyWhere extends website_Website {
  6877. name = 'FreeAnyWhere';
  6878. tasks = [];
  6879. socialTasks = JSON.parse(defaultTasks);
  6880. undoneTasks = JSON.parse(defaultTasks);
  6881. buttons = [ 'doTask', 'undoTask', 'verifyTask', 'getKey' ];
  6882. static test() {
  6883. return window.location.host === 'freeanywhere.net';
  6884. }
  6885. async init() {
  6886. try {
  6887. const logStatus = scripts_echoLog({
  6888. text: i18n('initing')
  6889. });
  6890. debug('检测登录按钮');
  6891. if ($('a[href="#/login"]').length > 0) {
  6892. window.open('/#/login', '_self');
  6893. logStatus.warning(i18n('needLogin'));
  6894. return false;
  6895. }
  6896. debug('检测是否为登录页面');
  6897. if (window.location.href.includes('/login')) {
  6898. logStatus.warning(i18n('needLogin'));
  6899. return false;
  6900. }
  6901. debug('检测url是否包含额外参数');
  6902. if (!/^https?:\/\/freeanywhere\.net\/#\/giveaway\/[\d]+/.test(window.location.href)) {
  6903. const id = window.location.href.match(/https?:\/\/freeanywhere\.net\/.*?#\/giveaway\/([\d]+)/)?.[1];
  6904. if (!id) {
  6905. logStatus.error(i18n('getFailed', 'Id'));
  6906. return false;
  6907. }
  6908. debug('重定向到不包含额外参数的url');
  6909. window.location.href = `https://freeanywhere.net/#/giveaway/${id}`;
  6910. }
  6911. if (!this.#getGiveawayId()) {
  6912. return false;
  6913. }
  6914. if (!await this.#checkLeftKey()) {
  6915. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  6916. }
  6917. this.initialized = true;
  6918. logStatus.success();
  6919. return true;
  6920. } catch (error) {
  6921. throwError(error, 'Freeanywhere.init');
  6922. return false;
  6923. }
  6924. }
  6925. async classifyTask(action) {
  6926. try {
  6927. const logStatus = scripts_echoLog({
  6928. text: i18n('getTasksInfo')
  6929. });
  6930. if (action === 'undo') {
  6931. this.socialTasks = GM_getValue(`fawTasks-${this.giveawayId}`)?.tasks || JSON.parse(defaultTasks);
  6932. }
  6933. const {
  6934. result,
  6935. statusText,
  6936. status,
  6937. data
  6938. } = await tools_httpRequest({
  6939. url: `https://freeanywhere.net/api/v1/giveaway/${this.giveawayId}/?format=json`,
  6940. method: 'GET',
  6941. headers: {
  6942. authorization: `Token ${window.localStorage.getItem('token')}`,
  6943. 'x-csrftoken': external_Cookies_default().get('csrftoken')
  6944. },
  6945. responseType: 'json'
  6946. });
  6947. if (result === 'Success') {
  6948. const tasks = data?.response?.challenges;
  6949. if (tasks) {
  6950. if (action === 'verify') {
  6951. this.tasks = [];
  6952. }
  6953. for (const task of tasks) {
  6954. debug('任务分类', task);
  6955. const type = task.challenge;
  6956. const social = task.challenge_provider;
  6957. const taskInfo = {
  6958. id: task.id,
  6959. title: task.title
  6960. };
  6961. if (action === 'verify' && !task.is_success) {
  6962. this.tasks.push(taskInfo);
  6963. continue;
  6964. }
  6965. switch (social) {
  6966. case 'steam':
  6967. taskInfo.social = 'steam';
  6968. switch (type) {
  6969. case 'WL':
  6970. if (action === 'undo') {
  6971. this.socialTasks.steam.wishlistLinks.push(task.link);
  6972. }
  6973. if (action === 'do' && !task.is_success) {
  6974. this.undoneTasks.steam.wishlistLinks.push(task.link);
  6975. }
  6976. break;
  6977.  
  6978. case 'JTG':
  6979. if (action === 'undo') {
  6980. this.socialTasks.steam.groupLinks.push(task.link);
  6981. }
  6982. if (action === 'do' && !task.is_success) {
  6983. this.undoneTasks.steam.groupLinks.push(task.link);
  6984. }
  6985. break;
  6986.  
  6987. case 'STC':
  6988. if (action === 'undo') {
  6989. this.socialTasks.steam.curatorLinks.push(task.link);
  6990. }
  6991. if (action === 'do' && !task.is_success) {
  6992. this.undoneTasks.steam.curatorLinks.push(task.link);
  6993. }
  6994. break;
  6995.  
  6996. case 'GF':
  6997. if (action === 'undo') {
  6998. this.socialTasks.steam.followLinks.push(task.link);
  6999. }
  7000. if (action === 'do' && !task.is_success) {
  7001. this.undoneTasks.steam.followLinks.push(task.link);
  7002. }
  7003. break;
  7004. }
  7005. break;
  7006.  
  7007. case 'vk-oauth2':
  7008. if (action === 'undo') {
  7009. this.socialTasks.vk.nameLinks.push(task.link);
  7010. }
  7011. if (action === 'do' && !task.is_success) {
  7012. this.undoneTasks.vk.nameLinks.push(task.link);
  7013. }
  7014. break;
  7015.  
  7016. case 'website':
  7017. break;
  7018.  
  7019. default:
  7020. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${social}`);
  7021. break;
  7022. }
  7023. }
  7024. logStatus.success();
  7025. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7026. this.socialTasks = this.uniqueTasks(this.socialTasks);
  7027. if (window.DEBUG) {
  7028. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7029. }
  7030. GM_setValue(`fawTasks-${this.giveawayId}`, {
  7031. tasks: this.socialTasks,
  7032. time: new Date().getTime()
  7033. });
  7034. return true;
  7035. }
  7036. debug('返回的数据中不包含任务信息', data?.response);
  7037. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7038. return false;
  7039. }
  7040. logStatus.error(`${result}:${statusText}(${status})`);
  7041. return false;
  7042. } catch (error) {
  7043. throwError(error, 'Freeanywhere.classifyTask');
  7044. return false;
  7045. }
  7046. }
  7047. async verifyTask() {
  7048. try {
  7049. if (!this.initialized && !this.init()) {
  7050. debug('未初始化');
  7051. return false;
  7052. }
  7053. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  7054. debug('任务列表为空', this.tasks);
  7055. return false;
  7056. }
  7057. const pro = [];
  7058. for (const task of this.tasks) {
  7059. pro.push(this.#verify(task));
  7060. await delay(1e3);
  7061. }
  7062. await Promise.all(pro);
  7063. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7064. return !!await this.getKey(true);
  7065. } catch (error) {
  7066. throwError(error, 'Freeanywhere.verifyTask');
  7067. return false;
  7068. }
  7069. }
  7070. async getKey(initialized) {
  7071. try {
  7072. if (!initialized && !this.initialized && !this.init()) {
  7073. debug('未初始化');
  7074. return false;
  7075. }
  7076. const logStatus = scripts_echoLog({
  7077. text: i18n('gettingKey')
  7078. });
  7079. const {
  7080. result,
  7081. statusText,
  7082. status,
  7083. data
  7084. } = await tools_httpRequest({
  7085. url: `https://freeanywhere.net/api/v1/giveaway/${this.giveawayId}/reward/?format=json`,
  7086. method: 'GET',
  7087. dataType: 'json',
  7088. headers: {
  7089. authorization: `Token ${window.localStorage.getItem('token')}`
  7090. }
  7091. });
  7092. if (result === 'Success') {
  7093. if (data?.response?.reward) {
  7094. logStatus.success();
  7095. scripts_echoLog({}).success(data.response.reward);
  7096. return data.response.reward;
  7097. }
  7098. if (data?.response?.completed === false) {
  7099. logStatus.error(i18n('tasksNotCompleted'));
  7100. return false;
  7101. }
  7102. if (data?.response?.completed === true) {
  7103. await this.#checkLeftKey();
  7104. }
  7105. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7106. return false;
  7107. }
  7108. logStatus.error(`${result}:${statusText}(${status})`);
  7109. return false;
  7110. } catch (error) {
  7111. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7112. return false;
  7113. }
  7114. }
  7115. #getGiveawayId() {
  7116. try {
  7117. const giveawayId = window.location.href.match(/\/giveaway\/([\d]+)/)?.[1];
  7118. if (giveawayId) {
  7119. this.giveawayId = giveawayId;
  7120. return true;
  7121. }
  7122. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  7123. return false;
  7124. } catch (error) {
  7125. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7126. return false;
  7127. }
  7128. }
  7129. async #verify(task) {
  7130. try {
  7131. const logStatus = scripts_echoLog({
  7132. html: `<li>${i18n('verifyingTask')}${task.title.trim()}...<font></font></li>`
  7133. });
  7134. const {
  7135. result,
  7136. statusText,
  7137. status,
  7138. data
  7139. } = await tools_httpRequest({
  7140. url: `https://freeanywhere.net/api/v1/giveaway/${this.giveawayId}/challenge-status/${task.id}/?format=json`,
  7141. method: 'GET',
  7142. dataType: 'json',
  7143. headers: {
  7144. authorization: `Token ${window.localStorage.getItem('token')}`,
  7145. 'x-csrftoken': external_Cookies_default().get('csrftoken')
  7146. }
  7147. });
  7148. if (result === 'Success') {
  7149. if (data?.response?.status) {
  7150. logStatus.success();
  7151. return true;
  7152. }
  7153. debug('任务验证结果', data?.response);
  7154. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7155. return false;
  7156. }
  7157. logStatus.error(`${result}:${statusText}(${status})`);
  7158. return false;
  7159. } catch (error) {
  7160. throwError(error, 'Freeanywhere.verify');
  7161. return false;
  7162. }
  7163. }
  7164. async #checkLeftKey() {
  7165. try {
  7166. if (!globalOptions.other.checkLeftKey) {
  7167. return true;
  7168. }
  7169. debug('检测剩余Key');
  7170. const {
  7171. data
  7172. } = await tools_httpRequest({
  7173. url: 'https://freeanywhere.net/api/v1/widget/?format=json',
  7174. method: 'GET',
  7175. dataType: 'json',
  7176. headers: {
  7177. authorization: `Token ${window.localStorage.getItem('token')}`
  7178. }
  7179. });
  7180. if (data?.response?.giveaways.find(giveaway => `${giveaway?.id}` === this.giveawayId)) {
  7181. return true;
  7182. }
  7183. await external_Swal_default().fire({
  7184. icon: 'warning',
  7185. title: i18n('notice'),
  7186. text: i18n('noKeysLeft'),
  7187. confirmButtonText: i18n('confirm'),
  7188. cancelButtonText: i18n('cancel'),
  7189. showCancelButton: true
  7190. }).then(({
  7191. value
  7192. }) => {
  7193. if (value) {
  7194. window.close();
  7195. }
  7196. });
  7197. return true;
  7198. } catch (error) {
  7199. throwError(error, 'Giveawaysu.checkLeftKey');
  7200. return false;
  7201. }
  7202. }
  7203. }
  7204. const Freeanywhere = FreeAnyWhere;
  7205. const Giveawaysu_defaultTasks = {
  7206. steam: {
  7207. groupLinks: [],
  7208. wishlistLinks: [],
  7209. curatorLinks: [],
  7210. curatorLikeLinks: [],
  7211. followLinks: [],
  7212. forumLinks: [],
  7213. announcementLinks: [],
  7214. workshopVoteLinks: [],
  7215. playtestLinks: []
  7216. },
  7217. discord: {
  7218. serverLinks: []
  7219. },
  7220. instagram: {
  7221. userLinks: []
  7222. },
  7223. vk: {
  7224. nameLinks: []
  7225. },
  7226. twitch: {
  7227. channelLinks: []
  7228. },
  7229. reddit: {
  7230. redditLinks: []
  7231. },
  7232. youtube: {
  7233. channelLinks: [],
  7234. likeLinks: []
  7235. },
  7236. twitter: {
  7237. userLinks: [],
  7238. retweetLinks: []
  7239. }
  7240. };
  7241. class GiveawaySu extends website_Website {
  7242. name = 'GiveawaySu';
  7243. socialTasks = Giveawaysu_defaultTasks;
  7244. undoneTasks = Giveawaysu_defaultTasks;
  7245. buttons = [ 'doTask', 'undoTask' ];
  7246. static test() {
  7247. return /^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(window.location.href);
  7248. }
  7249. async after() {
  7250. try {
  7251. if (!this.#checkLogin()) {
  7252. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7253. }
  7254. if (!await this.#checkLeftKey()) {
  7255. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7256. }
  7257. scripts_echoLog({}).warning(i18n('gsNotice'));
  7258. } catch (error) {
  7259. throwError(error, 'Giveawaysu.after');
  7260. }
  7261. }
  7262. init() {
  7263. try {
  7264. const logStatus = scripts_echoLog({
  7265. text: i18n('initing')
  7266. });
  7267. if ($('a.steam-login').length > 0) {
  7268. window.open('/steam/redirect', '_self');
  7269. logStatus.warning(i18n('needLogin'));
  7270. return false;
  7271. }
  7272. if (!this.#getGiveawayId()) {
  7273. return false;
  7274. }
  7275. this.initialized = true;
  7276. logStatus.success();
  7277. return true;
  7278. } catch (error) {
  7279. throwError(error, 'Giveawaysu.init');
  7280. return false;
  7281. }
  7282. }
  7283. async classifyTask(action) {
  7284. try {
  7285. const logStatus = scripts_echoLog({
  7286. text: i18n('getTasksInfo')
  7287. });
  7288. if (action === 'undo') {
  7289. this.socialTasks = GM_getValue(`gasTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  7290. return true;
  7291. }
  7292. const pro = [];
  7293. const tasks = $('#actions tr');
  7294. if ($('div.bind-discord').is(':visible')) {
  7295. $('div.bind-discord a')[0].click();
  7296. }
  7297. if ($('div.bind-twitch').is(':visible')) {
  7298. $('div.bind-twitch a')[0].click();
  7299. }
  7300. for (const task of tasks) {
  7301. pro.push(new Promise(resolve => {
  7302. const td = $(task).find('td:not(".hidden")');
  7303. const colorfulTask = td.eq(1).find('a:not([data-trigger="link"])');
  7304. const colorlessTask = td.eq(2).find('a:not([data-trigger="link"])');
  7305. const taskDes = colorfulTask.length > 0 ? colorfulTask : colorlessTask;
  7306. const taskIcon = td.eq(0).find('i').attr('class') || '';
  7307. const taskName = taskDes.text().trim();
  7308. if (taskIcon.includes('ban') || /disable adblock/gi.test(taskName)) {
  7309. return resolve(true);
  7310. }
  7311. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  7312. if (!taskLink) {
  7313. return resolve(false);
  7314. }
  7315. if (taskIcon.includes('steam') && /join/gi.test(taskName)) {
  7316. this.undoneTasks.steam.groupLinks.push(taskLink);
  7317. } else if (/like.*announcement/gi.test(taskName)) {
  7318. this.undoneTasks.steam.announcementLinks.push(taskLink);
  7319. } else if (/(follow|subscribe).*curator/gim.test(taskName) && /^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  7320. this.undoneTasks.steam.curatorLinks.push(taskLink);
  7321. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  7322. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  7323. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  7324. this.undoneTasks.steam.forumLinks.push(taskLink);
  7325. } else if (taskIcon.includes('thumbs-up') && /^https?:\/\/steamcommunity\.com\/sharedfiles\/filedetails\/\?id=[\d]+/.test(taskLink)) {
  7326. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7327. } else if (taskIcon.includes('plus') && /request.*playtest/gim.test(taskName)) {
  7328. this.undoneTasks.steam.playtestLinks.push(taskLink);
  7329. } else if (taskIcon.includes('discord') || /join.*discord/gim.test(taskName)) {
  7330. this.undoneTasks.discord.serverLinks.push(taskLink);
  7331. } else if (taskIcon.includes('instagram') || /follow.*instagram/gim.test(taskName)) {
  7332. this.undoneTasks.instagram.userLinks.push(taskLink);
  7333. } else if (taskIcon.includes('twitch') || /follow.*twitch.*channel/gim.test(taskName)) {
  7334. this.undoneTasks.twitch.channelLinks.push(taskLink);
  7335. } else if (taskIcon.includes('reddit') || /subscribe.*subreddit/gim.test(taskName) || /follow.*reddit/gim.test(taskName)) {
  7336. this.undoneTasks.reddit.redditLinks.push(taskLink);
  7337. } else if (/watch.*art/gim.test(taskName)) {
  7338. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7339. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  7340. this.undoneTasks.youtube.channelLinks.push(taskLink);
  7341. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  7342. this.undoneTasks.youtube.likeLinks.push(taskLink);
  7343. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  7344. this.undoneTasks.vk.nameLinks.push(taskLink);
  7345. } else {
  7346. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  7347. if (/wishlist.*game|add.*wishlist/gim.test(taskName)) {
  7348. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  7349. }
  7350. if (/follow.*button/gim.test(taskName)) {
  7351. this.undoneTasks.steam.followLinks.push(taskLink);
  7352. }
  7353. }
  7354. }
  7355. resolve(true);
  7356. }).catch(error => {
  7357. throwError(error, 'Giveawaysu.classifyTask->getRedirectLink');
  7358. return false;
  7359. });
  7360. }));
  7361. }
  7362. await Promise.all(pro);
  7363. logStatus.success();
  7364. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7365. this.socialTasks = this.undoneTasks;
  7366. if (window.DEBUG) {
  7367. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7368. }
  7369. GM_setValue(`gasTasks-${this.giveawayId}`, {
  7370. tasks: this.socialTasks,
  7371. time: new Date().getTime()
  7372. });
  7373. return true;
  7374. } catch (error) {
  7375. throwError(error, 'Giveawaysu.classifyTask');
  7376. return false;
  7377. }
  7378. }
  7379. #checkLogin() {
  7380. try {
  7381. if (!globalOptions.other.checkLogin) {
  7382. return true;
  7383. }
  7384. if ($('a.steam-login').length > 0) {
  7385. window.open('/steam/redirect', '_self');
  7386. }
  7387. return true;
  7388. } catch (error) {
  7389. throwError(error, 'Giveawaysu.checkLogin');
  7390. return false;
  7391. }
  7392. }
  7393. async #checkLeftKey() {
  7394. try {
  7395. if (!globalOptions.other.checkLeftKey) {
  7396. return true;
  7397. }
  7398. if ($('.giveaway-ended').length > 0 && $('.giveaway-key').length === 0) {
  7399. await external_Swal_default().fire({
  7400. icon: 'warning',
  7401. title: i18n('notice'),
  7402. text: i18n('noKeysLeft'),
  7403. confirmButtonText: i18n('confirm'),
  7404. cancelButtonText: i18n('cancel'),
  7405. showCancelButton: true
  7406. }).then(({
  7407. value
  7408. }) => {
  7409. if (value) {
  7410. window.close();
  7411. }
  7412. });
  7413. }
  7414. return true;
  7415. } catch (error) {
  7416. throwError(error, 'Giveawaysu.checkLeftKey');
  7417. return false;
  7418. }
  7419. }
  7420. #getGiveawayId() {
  7421. try {
  7422. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  7423. if (giveawayId) {
  7424. this.giveawayId = giveawayId;
  7425. return true;
  7426. }
  7427. scripts_echoLog({
  7428. text: i18n('getFailed', 'GiveawayId')
  7429. });
  7430. return false;
  7431. } catch (error) {
  7432. throwError(error, 'Giveawaysu.getGiveawayId');
  7433. return false;
  7434. }
  7435. }
  7436. }
  7437. class Indiedb {
  7438. name = 'Indiedb';
  7439. buttons = [ 'doTask' ];
  7440. static test() {
  7441. return window.location.host === 'www.indiedb.com';
  7442. }
  7443. async after() {
  7444. try {
  7445. if (!this.#checkLogin()) {
  7446. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7447. }
  7448. if (!await this.#checkLeftKey()) {
  7449. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7450. }
  7451. } catch (error) {
  7452. throwError(error, 'Indiedb.after');
  7453. }
  7454. }
  7455. async doTask() {
  7456. try {
  7457. if (!await this.#join()) {
  7458. return false;
  7459. }
  7460. return await this.#do();
  7461. } catch (error) {
  7462. throwError(error, 'Indiedb.doTask');
  7463. return false;
  7464. }
  7465. }
  7466. async #join() {
  7467. try {
  7468. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7469. scripts_echoLog({}).error(i18n('needLogin'));
  7470. return false;
  7471. }
  7472. const currentoption = $('a.buttonenter.buttongiveaway');
  7473. if (/join giveaway/gim.test(currentoption.text())) {
  7474. const logStatus = scripts_echoLog({
  7475. text: `${i18n('joiningGiveaway')}...`
  7476. });
  7477. const {
  7478. result,
  7479. statusText,
  7480. status,
  7481. data
  7482. } = await tools_httpRequest({
  7483. url: currentoption.attr('href'),
  7484. method: 'POST',
  7485. data: 'ajax=t',
  7486. dataType: 'json',
  7487. headers: {
  7488. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  7489. Accept: 'application/json, text/javascript, */*; q=0.01',
  7490. Origin: window.location.origin,
  7491. referer: window.location.href
  7492. }
  7493. });
  7494. if (result === 'Success') {
  7495. if (data?.status === 200) {
  7496. if (data.response?.success) {
  7497. currentoption.addClass('buttonentered').text('Success - Giveaway joined');
  7498. $('#giveawaysjoined').slideDown();
  7499. $('#giveawaysrecommend').slideDown();
  7500. logStatus.success(`Success${data.response?.text ? `:${data.response?.text}` : ''}`);
  7501. return true;
  7502. }
  7503. logStatus.error(`Error${data.response?.text ? `:${data.response?.text}` : ''}`);
  7504. return false;
  7505. }
  7506. if (await this.#join2()) {
  7507. logStatus.success('Success');
  7508. return true;
  7509. }
  7510. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7511. return false;
  7512. }
  7513. logStatus.error(`${result}:${statusText}(${status})`);
  7514. return false;
  7515. } else if (/success/gim.test($('a.buttonenter.buttongiveaway').text())) {
  7516. return true;
  7517. }
  7518. scripts_echoLog({}).warning(i18n('needJoinGiveaway'));
  7519. return false;
  7520. } catch (error) {
  7521. throwError(error, 'Indiedb.join');
  7522. return false;
  7523. }
  7524. }
  7525. async #join2() {
  7526. try {
  7527. return await new Promise(resolve => {
  7528. const targetNode = document.getElementById('giveawaysjoined');
  7529. const config = {
  7530. attributes: true
  7531. };
  7532. const observer = new MutationObserver(() => {
  7533. if ($('#giveawaysjoined').is(':visible')) {
  7534. resolve(true);
  7535. observer.disconnect();
  7536. }
  7537. });
  7538. observer.observe(targetNode, config);
  7539. $('a.buttonenter.buttongiveaway')[0]?.click();
  7540. setTimeout(() => {
  7541. resolve(false);
  7542. observer.disconnect();
  7543. }, 3e4);
  7544. });
  7545. } catch (error) {
  7546. throwError(error, 'Indiedb.join2');
  7547. return false;
  7548. }
  7549. }
  7550. async #do() {
  7551. try {
  7552. const id = $('script').map((index, script) => {
  7553. if (/\$\(document\)/gim.test(script.innerHTML)) {
  7554. return [ script.innerHTML.match(/"\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0], script.innerHTML.match(/"\/newsletter\/ajax\/subscribeprofile\/optin\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0] ];
  7555. }
  7556. return null;
  7557. });
  7558. if (id.length === 2) {
  7559. const pro = [];
  7560. const tasks = $('#giveawaysjoined a[class*=promo]');
  7561. for (const task of tasks) {
  7562. const promo = $(task);
  7563. if (!promo.hasClass('buttonentered')) {
  7564. const status = scripts_echoLog({
  7565. text: `${i18n('doing')}:${promo.parents('p').text()}...`
  7566. });
  7567. if (/facebookpromo|twitterpromo|visitpromo/gim.test(task.className)) {
  7568. let text = '';
  7569. if (promo.hasClass('facebookpromo')) {
  7570. text = 'facebookpromo';
  7571. } else if (promo.hasClass('twitterpromo')) {
  7572. text = 'twitterpromo';
  7573. } else {
  7574. text = 'visitpromo';
  7575. }
  7576. pro.push(new Promise(resolve => {
  7577. $.ajax({
  7578. type: 'POST',
  7579. url: urlPath(`/giveaways/ajax/${text}/${id[0]}`),
  7580. timeout: 6e4,
  7581. dataType: 'json',
  7582. data: {
  7583. ajax: 't'
  7584. },
  7585. error(response, error, exception) {
  7586. if (window.DEBUG) {
  7587. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7588. response: response,
  7589. error: error,
  7590. exception: exception
  7591. });
  7592. }
  7593. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7594. resolve(true);
  7595. },
  7596. success(response) {
  7597. if (response.success) {
  7598. status.success(`Success:${response.text}`);
  7599. promo.addClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7600. resolve(true);
  7601. } else {
  7602. status.error(`Error:${response.text}`);
  7603. resolve(true);
  7604. }
  7605. }
  7606. });
  7607. }));
  7608. } else if (promo.hasClass('emailoptinpromo')) {
  7609. pro.push(new Promise(resolve => {
  7610. $.ajax({
  7611. type: 'POST',
  7612. url: urlPath(`/newsletter/ajax/subscribeprofile/optin/${id[1]}`),
  7613. timeout: 6e4,
  7614. dataType: 'json',
  7615. data: {
  7616. ajax: 't',
  7617. emailsystoggle: 4
  7618. },
  7619. error(response, error, exception) {
  7620. if (window.DEBUG) {
  7621. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7622. response: response,
  7623. error: error,
  7624. exception: exception
  7625. });
  7626. }
  7627. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7628. resolve(true);
  7629. },
  7630. success(response) {
  7631. if (response.success) {
  7632. status.success(`Success:${response.text}`);
  7633. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7634. resolve(true);
  7635. } else {
  7636. status.error(`Error:${response.text}`);
  7637. resolve(true);
  7638. }
  7639. }
  7640. });
  7641. }));
  7642. } else if (promo.hasClass('watchingpromo')) {
  7643. pro.push(new Promise(resolve => {
  7644. const data = getUrlQuery(promo.attr('href'));
  7645. data.ajax = 't';
  7646. $.ajax({
  7647. type: 'POST',
  7648. url: urlPath(promo.attr('href')?.split(/[?#]/)[0]),
  7649. timeout: 6e4,
  7650. dataType: 'json',
  7651. data: data,
  7652. error(response, error, exception) {
  7653. if (window.DEBUG) {
  7654. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7655. response: response,
  7656. error: error,
  7657. exception: exception
  7658. });
  7659. }
  7660. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7661. resolve(true);
  7662. },
  7663. success(response) {
  7664. if (response.success) {
  7665. status.success(`Success:${response.text}`);
  7666. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7667. resolve(true);
  7668. } else {
  7669. status.error(`Error:${response.text}`);
  7670. resolve(true);
  7671. }
  7672. }
  7673. });
  7674. }));
  7675. } else if (!/the-challenge-of-adblock/gim.test(promo.attr('href'))) {
  7676. pro.push(new Promise(resolve => {
  7677. $.ajax({
  7678. type: 'POST',
  7679. url: urlPath(promo.attr('href')),
  7680. timeout: 6e4,
  7681. dataType: 'json',
  7682. data: {
  7683. ajax: 't'
  7684. },
  7685. error(response, error, exception) {
  7686. if (window.DEBUG) {
  7687. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7688. response: response,
  7689. error: error,
  7690. exception: exception
  7691. });
  7692. }
  7693. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7694. resolve(true);
  7695. },
  7696. success(response) {
  7697. if (response.success) {
  7698. status.success(`Success:${response.text}`);
  7699. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7700. resolve(true);
  7701. } else {
  7702. status.error(`Error:${response.text}`);
  7703. resolve(true);
  7704. }
  7705. }
  7706. });
  7707. }));
  7708. } else {
  7709. status.error(`Error:${i18n('unKnownTaskType')}`);
  7710. }
  7711. }
  7712. }
  7713. await Promise.all(pro);
  7714. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7715. return true;
  7716. }
  7717. scripts_echoLog({}).error(i18n('getFailed', 'TaskId'));
  7718. return false;
  7719. } catch (error) {
  7720. throwError(error, 'Indiedb.classifyTask');
  7721. return false;
  7722. }
  7723. }
  7724. #checkLogin() {
  7725. try {
  7726. if (!globalOptions.other.checkLogin) {
  7727. return true;
  7728. }
  7729. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7730. window.open('/members/login', '_self');
  7731. }
  7732. return true;
  7733. } catch (error) {
  7734. throwError(error, 'Indiedb.checkLogin');
  7735. return false;
  7736. }
  7737. }
  7738. async #checkLeftKey() {
  7739. try {
  7740. if (!globalOptions.other.checkLeftKey) {
  7741. return true;
  7742. }
  7743. if ($('a.buttonenter:contains("next time"), a.buttonenter:contains("Giveaway is closed")').length > 0) {
  7744. await external_Swal_default().fire({
  7745. icon: 'warning',
  7746. title: i18n('notice'),
  7747. text: i18n('giveawayEnded'),
  7748. confirmButtonText: i18n('confirm'),
  7749. cancelButtonText: i18n('cancel'),
  7750. showCancelButton: true
  7751. }).then(({
  7752. value
  7753. }) => {
  7754. if (value) {
  7755. window.close();
  7756. }
  7757. });
  7758. }
  7759. return true;
  7760. } catch (error) {
  7761. throwError(error, 'Indiedb.checkLeftKey');
  7762. return false;
  7763. }
  7764. }
  7765. }
  7766. const website_Indiedb = Indiedb;
  7767. const Keyhub_defaultTasksTemplate = {
  7768. steam: {
  7769. groupLinks: [],
  7770. officialGroupLinks: [],
  7771. wishlistLinks: [],
  7772. curatorLinks: []
  7773. },
  7774. discord: {
  7775. serverLinks: []
  7776. },
  7777. extra: {
  7778. videoTasks: []
  7779. },
  7780. links: []
  7781. };
  7782. const Keyhub_defaultTasks = JSON.stringify(Keyhub_defaultTasksTemplate);
  7783. class Keyhub extends website_Website {
  7784. name = 'Keyhub';
  7785. socialTasks = JSON.parse(Keyhub_defaultTasks);
  7786. undoneTasks = JSON.parse(Keyhub_defaultTasks);
  7787. buttons = [ 'doTask', 'undoTask' ];
  7788. static test() {
  7789. return window.location.host === 'key-hub.eu';
  7790. }
  7791. async after() {
  7792. try {
  7793. if (!this.#checkLogin()) {
  7794. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7795. }
  7796. if (!await this.#checkLeftKey()) {
  7797. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7798. }
  7799. $('.NSFW').hide();
  7800. } catch (error) {
  7801. throwError(error, 'Keyhub.after');
  7802. }
  7803. }
  7804. init() {
  7805. try {
  7806. const logStatus = scripts_echoLog({
  7807. text: i18n('initing')
  7808. });
  7809. if ($('a[href*="/connect/steam"]').length > 0) {
  7810. window.open('/connect/steam', '_self');
  7811. logStatus.warning(i18n('needLogin'));
  7812. return false;
  7813. }
  7814. if (!this.#getGiveawayId()) {
  7815. return false;
  7816. }
  7817. $('#VPNoverlay').hide();
  7818. $('#mainArticleSection').show();
  7819. this.initialized = true;
  7820. logStatus.success();
  7821. return true;
  7822. } catch (error) {
  7823. throwError(error, 'Keyhub.init');
  7824. return false;
  7825. }
  7826. }
  7827. async classifyTask(action) {
  7828. try {
  7829. const logStatus = scripts_echoLog({
  7830. text: i18n('getTasksInfo')
  7831. });
  7832. if (action === 'undo') {
  7833. this.socialTasks = GM_getValue(`khTasks-${this.giveawayId}`)?.tasks || JSON.parse(Keyhub_defaultTasks);
  7834. }
  7835. const tasks = $('.task:not(".googleads")').filter((index, element) => action === 'do' ? $(element).find('i.fa-check-circle:visible').length === 0 : true).find('a');
  7836. for (const task of tasks) {
  7837. let link = $(task).attr('href');
  7838. const taskDes = $(task).text().trim();
  7839. if (!link) {
  7840. continue;
  7841. }
  7842. if (/\/away\?data=/.test(link) || /steamcommunity\.com\/gid\//.test(link)) {
  7843. link = await getRedirectLink(link) || link;
  7844. }
  7845. if (/https?:\/\/key-hub\.eu\/connect\/discord/.test(link)) {
  7846. GM_openInTab(link, {
  7847. active: true
  7848. });
  7849. } else if (/steamcommunity\.com\/groups\//.test(link)) {
  7850. if (action === 'undo') {
  7851. this.socialTasks.steam.groupLinks.push(link);
  7852. }
  7853. if (action === 'do') {
  7854. this.undoneTasks.steam.groupLinks.push(link);
  7855. }
  7856. } else if (/steamcommunity\.com\/games\/[\d]+/.test(link)) {
  7857. if (action === 'undo') {
  7858. this.socialTasks.steam.officialGroupLinks.push(link);
  7859. }
  7860. if (action === 'do') {
  7861. this.undoneTasks.steam.officialGroupLinks.push(link);
  7862. }
  7863. } else if (/store\.steampowered\.com\/app\//.test(link) && /wishlist/gim.test(taskDes)) {
  7864. if (action === 'undo') {
  7865. this.socialTasks.steam.wishlistLinks.push(link);
  7866. }
  7867. if (action === 'do') {
  7868. this.undoneTasks.steam.wishlistLinks.push(link);
  7869. }
  7870. } else if (/store\.steampowered\.com\/curator\//.test(link)) {
  7871. if (action === 'undo') {
  7872. this.socialTasks.steam.curatorLinks.push(link);
  7873. }
  7874. if (action === 'do') {
  7875. this.undoneTasks.steam.curatorLinks.push(link);
  7876. }
  7877. } else if (/^https?:\/\/discord\.com\/invite\//.test(link)) {
  7878. if (action === 'undo') {
  7879. this.socialTasks.discord.serverLinks.push(link);
  7880. }
  7881. if (action === 'do') {
  7882. this.undoneTasks.discord.serverLinks.push(link);
  7883. }
  7884. } else if (/^javascript:videoTask.+/.test(link)) {
  7885. if (action === 'do') {
  7886. const taskData = link.match(/javascript:videoTask\('.+?','(.+?)'/)?.[1];
  7887. if (taskData) {
  7888. this.undoneTasks.extra.videoTasks.push(taskData);
  7889. }
  7890. }
  7891. } else if (/^https?:\/\/www\.instagram\.com\/.*/.test(link) || /^https?:\/\/twitter\.com\/.*/.test(link) || /^https?:\/\/www\.twitch\.tv\/.*/.test(link) || /^https?:\/\/www\.facebook\.com\/.*/.test(link) || /^https?:\/\/www\.youtube\.com\/.*/.test(link) || /^https?:\/\/store\.steampowered\.com\/developer\//.test(link) || /^https?:\/\/.*?\.itch\.io\/.*/.test(link) || /^https?:\/\/key-hub\.eu.*/.test(link) || /^https?:\/\/store\.steampowered\.com\/app\/.*/.test(link) || /^https?:\/\/qr\.streamelements\.com\/.*/.test(link) || /^https?:\/\/store\.steampowered\.com\/news\/app\/.*/.test(link)) {} else {
  7892. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  7893. }
  7894. }
  7895. logStatus.success();
  7896. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7897. this.socialTasks = this.uniqueTasks(this.socialTasks);
  7898. if (window.DEBUG) {
  7899. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7900. }
  7901. GM_setValue(`khTasks-${this.giveawayId}`, {
  7902. tasks: this.socialTasks,
  7903. time: new Date().getTime()
  7904. });
  7905. return true;
  7906. } catch (error) {
  7907. throwError(error, 'Keyhub.classifyTask');
  7908. return false;
  7909. }
  7910. }
  7911. async #doScriptTask(data) {
  7912. try {
  7913. const logStatus = scripts_echoLog({
  7914. text: i18n('doingKeyhubTask')
  7915. });
  7916. const {
  7917. result,
  7918. statusText,
  7919. status,
  7920. data: response
  7921. } = await tools_httpRequest({
  7922. url: `/away?data=${data}`,
  7923. method: 'GET',
  7924. headers: {
  7925. origin: 'https://key-hub.eu',
  7926. referer: 'https://key-hub.eu/'
  7927. }
  7928. });
  7929. if (result === 'Success') {
  7930. if (response?.status === 200) {
  7931. logStatus.success();
  7932. return true;
  7933. }
  7934. logStatus.error(`Error:${response?.statusText}(${response?.status})`);
  7935. return false;
  7936. }
  7937. logStatus.error(`${result}:${statusText}(${status})`);
  7938. return false;
  7939. } catch (error) {
  7940. throwError(error, 'Keyhub.doScriptTask');
  7941. return false;
  7942. }
  7943. }
  7944. async extraDoTask({
  7945. videoTasks
  7946. }) {
  7947. try {
  7948. const pro = [];
  7949. for (const data of videoTasks) {
  7950. pro.push(this.#doScriptTask(data));
  7951. }
  7952. return Promise.all(pro).then(() => true);
  7953. } catch (error) {
  7954. throwError(error, 'Keyhub.extraDoTask');
  7955. return false;
  7956. }
  7957. }
  7958. #getGiveawayId() {
  7959. try {
  7960. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  7961. if (giveawayId) {
  7962. this.giveawayId = giveawayId;
  7963. return true;
  7964. }
  7965. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  7966. return false;
  7967. } catch (error) {
  7968. throwError(error, 'Keyhub.getGiveawayId');
  7969. return false;
  7970. }
  7971. }
  7972. async #checkLeftKey() {
  7973. try {
  7974. if (!globalOptions.other.checkLeftKey) {
  7975. return true;
  7976. }
  7977. const leftKey = $('#keysleft').text().trim();
  7978. if (leftKey === '0') {
  7979. await external_Swal_default().fire({
  7980. icon: 'warning',
  7981. title: i18n('notice'),
  7982. text: i18n('noKeysLeft'),
  7983. confirmButtonText: i18n('confirm'),
  7984. cancelButtonText: i18n('cancel'),
  7985. showCancelButton: true
  7986. }).then(({
  7987. value
  7988. }) => {
  7989. if (value) {
  7990. window.close();
  7991. }
  7992. });
  7993. }
  7994. return true;
  7995. } catch (error) {
  7996. throwError(error, 'Keyhub.checkLeftKey');
  7997. return false;
  7998. }
  7999. }
  8000. #checkLogin() {
  8001. try {
  8002. if (!globalOptions.other.checkLogin) {
  8003. return true;
  8004. }
  8005. if ($('a[href*="/connect/steam"]').length > 0) {
  8006. window.open('/connect/steam', '_self');
  8007. }
  8008. return true;
  8009. } catch (error) {
  8010. throwError(error, 'Keyhub.checkLogin');
  8011. return false;
  8012. }
  8013. }
  8014. }
  8015. const website_Keyhub = Keyhub;
  8016. const Givekey_defaultTasksTemplate = {
  8017. steam: {
  8018. groupLinks: [],
  8019. wishlistLinks: [],
  8020. curatorLinks: [],
  8021. curatorLikeLinks: []
  8022. },
  8023. twitter: {
  8024. userLinks: []
  8025. },
  8026. vk: {
  8027. nameLinks: []
  8028. },
  8029. discord: {
  8030. serverLinks: []
  8031. }
  8032. };
  8033. const Givekey_defaultTasks = JSON.stringify(Givekey_defaultTasksTemplate);
  8034. class Givekey extends website_Website {
  8035. name = 'Givekey';
  8036. tasks = [];
  8037. socialTasks = JSON.parse(Givekey_defaultTasks);
  8038. undoneTasks = JSON.parse(Givekey_defaultTasks);
  8039. userId;
  8040. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8041. static test() {
  8042. return window.location.host === 'givekey.ru';
  8043. }
  8044. async after() {
  8045. try {
  8046. await new Promise(resolve => {
  8047. const checker = setInterval(() => {
  8048. if ($('#navbarDropdown').length > 0) {
  8049. clearInterval(checker);
  8050. resolve(true);
  8051. }
  8052. }, 500);
  8053. });
  8054. if (!await this.#checkLeftKey()) {
  8055. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8056. }
  8057. } catch (error) {
  8058. throwError(error, 'Givekey.after');
  8059. }
  8060. }
  8061. init() {
  8062. try {
  8063. const logStatus = scripts_echoLog({
  8064. text: i18n('initing')
  8065. });
  8066. if ($('a[href*="/auth/steam"]').length > 0) {
  8067. window.open('/auth/steam', '_self');
  8068. logStatus.warning(i18n('needLogin'));
  8069. return false;
  8070. }
  8071. if (!this.#getGiveawayId()) {
  8072. return false;
  8073. }
  8074. const userId = $('meta[name="user-id"]').attr('content');
  8075. if (!userId) {
  8076. logStatus.error(i18n('getFailed', i18n('userId')));
  8077. return false;
  8078. }
  8079. this.userId = userId;
  8080. this.initialized = true;
  8081. logStatus.success();
  8082. return true;
  8083. } catch (error) {
  8084. throwError(error, 'Givekey.init');
  8085. return false;
  8086. }
  8087. }
  8088. async classifyTask(action) {
  8089. try {
  8090. const logStatus = scripts_echoLog({
  8091. text: i18n('getTasksInfo')
  8092. });
  8093. if (action === 'undo') {
  8094. this.socialTasks = GM_getValue(`gkTasks-${this.giveawayId}`)?.tasks || JSON.parse(Givekey_defaultTasks);
  8095. }
  8096. const tasks = $('.card-body:has("button") .row');
  8097. for (const task of tasks) {
  8098. const taskEle = $(task);
  8099. const isSuccess = /Complete/i.test(taskEle.find('button').text().trim());
  8100. if (isSuccess && action !== 'undo') {
  8101. continue;
  8102. }
  8103. const checkButton = taskEle.find('#task_check');
  8104. const taskId = checkButton.attr('data-id');
  8105. if (taskId) {
  8106. this.tasks.push(taskId);
  8107. }
  8108. if (action === 'verify') {
  8109. continue;
  8110. }
  8111. let href = taskEle.find('a').attr('href') || null;
  8112. const text = taskEle.find('a').text().trim();
  8113. const icon = taskEle.find('i');
  8114. if (!href || !text) {
  8115. continue;
  8116. }
  8117. if (/^https?:\/\/givekey\.ru\/giveaway\/[\d]+\/execution_task/.test(href)) {
  8118. href = await getRedirectLink(href);
  8119. }
  8120. if (!href) {
  8121. continue;
  8122. }
  8123. if (/^https?:\/\/vk\.com\//.test(href)) {
  8124. this.socialTasks.vk.nameLinks.push(href);
  8125. if (action === 'do' && !isSuccess) {
  8126. this.undoneTasks.vk.nameLinks.push(href);
  8127. }
  8128. } else if (/^https?:\/\/steamcommunity\.com\/groups/.test(href)) {
  8129. this.socialTasks.steam.groupLinks.push(href);
  8130. if (action === 'do' && !isSuccess) {
  8131. this.undoneTasks.steam.groupLinks.push(href);
  8132. }
  8133. } else if (/^https?:\/\/store\.steampowered\.com\/app\//.test(href)) {
  8134. this.socialTasks.steam.wishlistLinks.push(href);
  8135. if (action === 'do' && !isSuccess) {
  8136. this.undoneTasks.steam.wishlistLinks.push(href);
  8137. }
  8138. } else if (/Subscribe/gi.test(text) && icon.hasClass('fa-steam-square')) {
  8139. if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(href)) {
  8140. this.socialTasks.steam.curatorLinks.push(href);
  8141. if (action === 'do' && !isSuccess) {
  8142. this.undoneTasks.steam.curatorLinks.push(href);
  8143. }
  8144. } else {
  8145. this.socialTasks.steam.curatorLikeLinks.push(href);
  8146. if (action === 'do' && !isSuccess) {
  8147. this.undoneTasks.steam.curatorLikeLinks.push(href);
  8148. }
  8149. }
  8150. } else if (/^https?:\/\/twitter\.com\//.test(href) && /Subscribe/gi.test(text)) {
  8151. this.socialTasks.twitter.userLinks.push(href);
  8152. if (action === 'do' && !isSuccess) {
  8153. this.undoneTasks.twitter.userLinks.push(href);
  8154. }
  8155. } else if (icon.hasClass('fa-discord') || /^https?:\/\/discord\.com\/invite\//.test(href)) {
  8156. this.socialTasks.discord.serverLinks.push(href);
  8157. if (action === 'do' && !isSuccess) {
  8158. this.undoneTasks.discord.serverLinks.push(href);
  8159. }
  8160. } else {
  8161. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${text}(${href})`);
  8162. }
  8163. }
  8164. logStatus.success();
  8165. this.tasks = unique(this.tasks);
  8166. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8167. this.socialTasks = this.uniqueTasks(this.socialTasks);
  8168. if (window.DEBUG) {
  8169. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8170. }
  8171. GM_setValue(`gkTasks-${this.giveawayId}`, {
  8172. tasks: this.socialTasks,
  8173. time: new Date().getTime()
  8174. });
  8175. return true;
  8176. } catch (error) {
  8177. throwError(error, 'Givekey.classifyTask');
  8178. return false;
  8179. }
  8180. }
  8181. async verifyTask() {
  8182. try {
  8183. if (!this.initialized && !this.init()) {
  8184. return false;
  8185. }
  8186. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  8187. return false;
  8188. }
  8189. scripts_echoLog({}).warning(i18n('giveKeyNoticeBefore'));
  8190. const taskLength = this.tasks.length;
  8191. for (let i = 0; i < taskLength; i++) {
  8192. await this.#verify(this.tasks[i]);
  8193. if (i < taskLength - 1) {
  8194. await delay(15e3);
  8195. }
  8196. }
  8197. scripts_echoLog({}).success(i18n('allTasksComplete'));
  8198. scripts_echoLog({
  8199. html: `<li><font class="warning">${i18n('giveKeyNoticeAfter')}</font></li>`
  8200. });
  8201. return true;
  8202. } catch (error) {
  8203. throwError(error, 'Givekey.verifyTask');
  8204. return false;
  8205. }
  8206. }
  8207. async #verify(task) {
  8208. try {
  8209. const logStatus = scripts_echoLog({
  8210. html: `<li>${i18n('verifyingTask')}${task}...<font></font></li>`
  8211. });
  8212. return await new Promise(resolve => {
  8213. $.ajax({
  8214. url: 'https://givekey.ru/giveaway/task',
  8215. method: 'POST',
  8216. data: `id=${task}&user_id=${this.userId}`,
  8217. dataType: 'json',
  8218. headers: {
  8219. 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  8220. },
  8221. success: data => {
  8222. if (data.btn) {
  8223. $(`button[data-id=${this.userId}]`).html(data.btn);
  8224. }
  8225. if (data.status === 'ok') {
  8226. $(`.task_check_${data.id}`).html(`<button class="btn btn-success mb-2 btn-block" disabled>${data.btn}</button>`);
  8227. logStatus.success();
  8228. resolve(true);
  8229. } else if (data.status === 'end') {
  8230. logStatus.success();
  8231. scripts_echoLog({}).success(data.key);
  8232. resolve(true);
  8233. } else {
  8234. logStatus.error(`Error:${data.msg}`);
  8235. resolve(false);
  8236. }
  8237. },
  8238. error: xhr => {
  8239. logStatus.error(`Error:${xhr.statusText}(${xhr.status})`);
  8240. resolve(false);
  8241. }
  8242. });
  8243. });
  8244. } catch (error) {
  8245. throwError(error, 'Givekey.verify');
  8246. return false;
  8247. }
  8248. }
  8249. #getGiveawayId() {
  8250. try {
  8251. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  8252. if (giveawayId) {
  8253. this.giveawayId = giveawayId;
  8254. return true;
  8255. }
  8256. scripts_echoLog({
  8257. text: i18n('getFailed', 'GiveawayId')
  8258. });
  8259. return false;
  8260. } catch (error) {
  8261. throwError(error, 'Givekey.getGiveawayId');
  8262. return false;
  8263. }
  8264. }
  8265. async #checkLeftKey() {
  8266. try {
  8267. if (!globalOptions.other.checkLeftKey) {
  8268. return true;
  8269. }
  8270. if (!$('#keys_count').text()) {
  8271. await external_Swal_default().fire({
  8272. icon: 'warning',
  8273. title: i18n('notice'),
  8274. text: i18n('noKeysLeft'),
  8275. confirmButtonText: i18n('confirm'),
  8276. cancelButtonText: i18n('cancel'),
  8277. showCancelButton: true
  8278. }).then(({
  8279. value
  8280. }) => {
  8281. if (value) {
  8282. window.close();
  8283. }
  8284. });
  8285. }
  8286. return true;
  8287. } catch (error) {
  8288. throwError(error, 'Givekey.checkLeftKey');
  8289. return false;
  8290. }
  8291. }
  8292. }
  8293. const website_Givekey = Givekey;
  8294. class GiveeClub extends GiveawaySu {
  8295. name = 'GiveeClub';
  8296. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8297. static test() {
  8298. return /^https?:\/\/givee\.club\/.*?\/event\/[\d]+/.test(window.location.href);
  8299. }
  8300. async after() {
  8301. try {
  8302. if (!this.#checkLogin()) {
  8303. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8304. }
  8305. if (!await this.#checkLeftKey()) {
  8306. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8307. }
  8308. } catch (error) {
  8309. throwError(error, 'GiveeClub.after');
  8310. }
  8311. }
  8312. init() {
  8313. try {
  8314. const logStatus = scripts_echoLog({
  8315. text: i18n('initing')
  8316. });
  8317. if (!this.#checkLogin()) {
  8318. logStatus.warning(i18n('needLogin'));
  8319. return false;
  8320. }
  8321. if (!this.#getGiveawayId()) {
  8322. return false;
  8323. }
  8324. this.initialized = true;
  8325. logStatus.success();
  8326. return true;
  8327. } catch (error) {
  8328. throwError(error, 'GiveeClub.init');
  8329. return false;
  8330. }
  8331. }
  8332. async classifyTask(action) {
  8333. try {
  8334. const logStatus = scripts_echoLog({
  8335. text: i18n('getTasksInfo')
  8336. });
  8337. if (action === 'undo') {
  8338. this.socialTasks = GM_getValue(`gcTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  8339. return true;
  8340. }
  8341. this.undoneTasks = Giveawaysu_defaultTasks;
  8342. const pro = [];
  8343. const tasks = $('.event-actions tr');
  8344. for (const task of tasks) {
  8345. pro.push(new Promise(resolve => {
  8346. const taskDes = $(task).find('.event-action-label a');
  8347. const taskIcon = $(task).find('.event-action-icon i').attr('class') || '';
  8348. const taskName = taskDes.text().trim();
  8349. const taskType = $(task).find('button[data-type]')?.attr('data-type');
  8350. const taskFinished = $(task).find('.event-action-buttons .btn-success')?.length;
  8351. if (taskIcon.includes('ban') || /AdBlock/i.test(taskName) || taskIcon.includes('envelope') || taskFinished) {
  8352. return resolve(true);
  8353. }
  8354. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  8355. if (!taskLink) {
  8356. return resolve(false);
  8357. }
  8358. if (taskType === 'steam.group.join' && /^https?:\/\/steamcommunity\.com\/groups/.test(taskLink)) {
  8359. this.undoneTasks.steam.groupLinks.push(taskLink);
  8360. } else if (/like.*announcement/gi.test(taskName)) {
  8361. this.undoneTasks.steam.announcementLinks.push(taskLink);
  8362. } else if (taskType === 'steam.game.wishlist' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8363. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  8364. } else if (taskType === 'steam.game.wishlist' && taskDes.attr('data-steam-wishlist-appid')) {
  8365. this.undoneTasks.steam.wishlistLinks.push(`https://store.steampowered.com/app/${taskDes.attr('data-steam-wishlist-appid')}`);
  8366. } else if (taskType === 'steam.game.follow' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8367. this.undoneTasks.steam.followLinks.push(taskLink);
  8368. } else if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  8369. this.undoneTasks.steam.curatorLinks.push(taskLink);
  8370. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  8371. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  8372. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  8373. this.undoneTasks.steam.forumLinks.push(taskLink);
  8374. } else if (taskIcon.includes('discord')) {
  8375. this.undoneTasks.discord.serverLinks.push(taskLink);
  8376. } else if (taskIcon.includes('instagram')) {
  8377. this.undoneTasks.instagram.userLinks.push(taskLink);
  8378. } else if (taskIcon.includes('twitch')) {
  8379. this.undoneTasks.twitch.channelLinks.push(taskLink);
  8380. } else if (taskIcon.includes('reddit')) {
  8381. this.undoneTasks.reddit.redditLinks.push(taskLink);
  8382. } else if (/watch.*art/gim.test(taskName)) {
  8383. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  8384. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  8385. this.undoneTasks.youtube.channelLinks.push(taskLink);
  8386. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  8387. this.undoneTasks.youtube.likeLinks.push(taskLink);
  8388. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  8389. this.undoneTasks.vk.nameLinks.push(taskLink);
  8390. } else if (taskIcon.includes('twitter')) {
  8391. if (/https?:\/\/(twitter|x)\.com\/[^/]+\/?$/gim.test(taskLink)) {
  8392. this.undoneTasks.twitter.userLinks.push(taskLink);
  8393. } else if (/https?:\/\/(twitter|x)\.com\/[^/]+?\/status\/[\d]+/gim.test(taskLink)) {
  8394. this.undoneTasks.twitter.retweetLinks.push(taskLink);
  8395. }
  8396. } else {
  8397. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  8398. if (/follow.*button/gim.test(taskName)) {
  8399. this.undoneTasks.steam.followLinks.push(taskLink);
  8400. }
  8401. }
  8402. }
  8403. resolve(true);
  8404. }).catch(error => {
  8405. throwError(error, 'GiveeClub.classifyTask->getRedirectLink');
  8406. return false;
  8407. });
  8408. }));
  8409. }
  8410. await Promise.all(pro);
  8411. logStatus.success();
  8412. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8413. this.socialTasks = this.undoneTasks;
  8414. if (window.DEBUG) {
  8415. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8416. }
  8417. GM_setValue(`gcTasks-${this.giveawayId}`, {
  8418. tasks: this.socialTasks,
  8419. time: new Date().getTime()
  8420. });
  8421. return true;
  8422. } catch (error) {
  8423. throwError(error, 'GiveeClub.classifyTask');
  8424. return false;
  8425. }
  8426. }
  8427. async verifyTask() {
  8428. try {
  8429. const logStatus = scripts_echoLog({
  8430. text: i18n('giveeClubVerifyNotice')
  8431. });
  8432. const taskButtons = $('.event-actions tr button').has('i.glyphicon-refresh').not('[data-type="user.adblock"]');
  8433. for (const button of taskButtons) {
  8434. button.click();
  8435. if ($(button).attr('data-type') !== 'steam.game.wishlist') {
  8436. await delay(1e3);
  8437. }
  8438. }
  8439. logStatus.warning(i18n('giveeClubVerifyFinished'));
  8440. return true;
  8441. } catch (error) {
  8442. throwError(error, 'Givekey.verifyTask');
  8443. return false;
  8444. }
  8445. }
  8446. #checkLogin() {
  8447. try {
  8448. if (!globalOptions.other.checkLogin) {
  8449. return true;
  8450. }
  8451. if ($('a[href*="/account/auth"]').length > 0) {
  8452. window.open($('a[href*="/account/auth"]').attr('href'), '_self');
  8453. }
  8454. return true;
  8455. } catch (error) {
  8456. throwError(error, 'GiveeClub.checkLogin');
  8457. return false;
  8458. }
  8459. }
  8460. #getGiveawayId() {
  8461. const giveawayId = window.location.href.match(/\/event\/([\d]+)/)?.[1];
  8462. if (giveawayId) {
  8463. this.giveawayId = giveawayId;
  8464. return true;
  8465. }
  8466. scripts_echoLog({
  8467. text: i18n('getFailed', 'GiveawayId')
  8468. });
  8469. return false;
  8470. }
  8471. async #checkLeftKey() {
  8472. try {
  8473. if (!globalOptions.other.checkLeftKey) {
  8474. return true;
  8475. }
  8476. if ($('.event-ended').length > 0 && $('.event-winner').length === 0) {
  8477. await external_Swal_default().fire({
  8478. icon: 'warning',
  8479. title: i18n('notice'),
  8480. text: i18n('giveawayEnded'),
  8481. confirmButtonText: i18n('confirm'),
  8482. cancelButtonText: i18n('cancel'),
  8483. showCancelButton: true
  8484. }).then(({
  8485. value
  8486. }) => {
  8487. if (value) {
  8488. window.close();
  8489. }
  8490. });
  8491. }
  8492. return true;
  8493. } catch (error) {
  8494. throwError(error, 'Giveawaysu.checkLeftKey');
  8495. return false;
  8496. }
  8497. }
  8498. }
  8499. const website_GiveeClub = GiveeClub;
  8500. const defaultOptions = {
  8501. maxPoint: '99999999'
  8502. };
  8503. class OpiumPulses {
  8504. name = 'OpiumPulses';
  8505. options = {
  8506. ...defaultOptions,
  8507. ...GM_getValue('OpiumPulsesOptions')
  8508. };
  8509. maxPoints = 99999999;
  8510. myPoints = 0;
  8511. buttons = [ 'doFreeTask', 'doPointTask' ];
  8512. static test() {
  8513. return window.location.host === 'www.opiumpulses.com';
  8514. }
  8515. async after() {
  8516. try {
  8517. if (!this.#checkLogin()) {
  8518. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8519. }
  8520. this.maxPoints = parseInt(this.options.maxPoint, 10);
  8521. } catch (error) {
  8522. throwError(error, 'OpiumPulses.after');
  8523. }
  8524. }
  8525. async doFreeTask() {
  8526. try {
  8527. this.#toggleTask('FREE');
  8528. } catch (error) {
  8529. throwError(error, 'OpiumPulses.doFreeTask');
  8530. }
  8531. }
  8532. async doPointTask() {
  8533. try {
  8534. this.myPoints = parseInt($('.page-header__nav-func-user-nav-items.points-items').text().match(/[\d]+/gim)?.[0] || '0', 10);
  8535. this.#toggleTask('points');
  8536. } catch (error) {
  8537. throwError(error, 'OpiumPulses.doPointTask');
  8538. }
  8539. }
  8540. async #toggleTask(type) {
  8541. try {
  8542. const items = $(`.giveaways-page-item:contains('${type}'):not(:contains('ENTERED'))`);
  8543. for (const item of items) {
  8544. const needPoints = parseInt($(item).find('.giveaways-page-item-header-points').text().match(/[\d]+/gim)?.[0] || '999999', 10);
  8545. const name = $(item).find('.giveaways-page-item-footer-name').text().trim();
  8546. if (type === 'points' && needPoints > this.myPoints) {
  8547. scripts_echoLog({}).warning(`${i18n('noPoints')}: ${name}`);
  8548. } else if (type === 'points' && !needPoints) {
  8549. scripts_echoLog({}).warning(`${i18n('getNeedPointsFailed')}: ${name}`);
  8550. } else if (!(type === 'points' && needPoints > this.maxPoints)) {
  8551. const logStatus = scripts_echoLog({
  8552. text: `${i18n('joiningLottery')}<a href="${$(item).find('a.giveaways-page-item-img-btn-more').attr('href')}" target="_blank">${name}</a>...`
  8553. });
  8554. const aElement = $(item).find('a.giveaways-page-item-img-btn-enter:contains(\'enter\')');
  8555. if (aElement?.attr('onclick')?.includes('checkUser')) {
  8556. const giveawayId = aElement.attr('onclick')?.match(/[\d]+/)?.[0];
  8557. if (giveawayId) {
  8558. checkUser(giveawayId);
  8559. }
  8560. }
  8561. if (!aElement.attr('href')) {
  8562. logStatus.error('Error: No "href".');
  8563. continue;
  8564. }
  8565. const {
  8566. result,
  8567. statusText,
  8568. status,
  8569. data
  8570. } = await tools_httpRequest({
  8571. url: aElement.attr('href'),
  8572. method: 'GET'
  8573. });
  8574. if (result === 'Success') {
  8575. const {
  8576. result: result0,
  8577. statusText: statusText0,
  8578. status: status0,
  8579. data: data0
  8580. } = await tools_httpRequest({
  8581. url: data?.finalUrl,
  8582. method: 'GET'
  8583. });
  8584. if (data0?.responseText && /You've entered this giveaway/gim.test(data0.responseText)) {
  8585. logStatus.success();
  8586. const points = data0.responseText.match(/Points:[\s]*?([\d]+)/)?.[1];
  8587. if (type === 'points' && points) {
  8588. this.myPoints = parseInt(points, 10);
  8589. }
  8590. } else if (data0?.responseText && /You're not eligible to enter/gim.test(data0.responseText)) {
  8591. logStatus.error('You\'re not eligible to enter');
  8592. } else {
  8593. logStatus.error(`${result0}:${statusText0}(${status0})`);
  8594. }
  8595. } else {
  8596. logStatus.error(`${result}:${statusText}(${status})`);
  8597. }
  8598. }
  8599. }
  8600. scripts_echoLog({
  8601. text: '-----END-----'
  8602. });
  8603. } catch (error) {
  8604. throwError(error, 'OpiumPulses.toggleTask');
  8605. }
  8606. }
  8607. init() {
  8608. return true;
  8609. }
  8610. classifyTask() {
  8611. return true;
  8612. }
  8613. #checkLogin() {
  8614. try {
  8615. if (!globalOptions.other.checkLogin) {
  8616. return true;
  8617. }
  8618. if ($('a[href*="/site/login"]').length > 1) {
  8619. window.open('/site/login', '_self');
  8620. }
  8621. return true;
  8622. } catch (error) {
  8623. throwError(error, 'OpiumPulses.checkLogin');
  8624. return false;
  8625. }
  8626. }
  8627. }
  8628. const website_OpiumPulses = OpiumPulses;
  8629. const external_dayjs_namespaceObject = dayjs;
  8630. var external_dayjs_default = __webpack_require__.n(external_dayjs_namespaceObject);
  8631. const leftKeyChecker = {
  8632. async classify(link) {
  8633. try {
  8634. if (/^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(link)) {
  8635. return await this.giveawaySu(link);
  8636. }
  8637. if (/^https?:\/\/givee\.club\/[\w]+?\/event\/[\d]+/.test(link)) {
  8638. return await this.giveeClub(link);
  8639. }
  8640. if (/^https?:\/\/gleam\.io\/.+?\/.+/.test(link)) {
  8641. return await this.gleam(link);
  8642. }
  8643. if (/^https?:\/\/www\.indiedb\.com\/giveaways\/.+/.test(link)) {
  8644. return await this.indieDb(link);
  8645. }
  8646. if (/^https?:\/\/key-hub\.eu\/giveaway\/[\d]+/.test(link)) {
  8647. return await this.keyhub(link);
  8648. }
  8649. if (/^https?:\/\/opquests\.com\/quests\/[\d]+/.test(link)) {
  8650. return await this.opquests(link);
  8651. }
  8652. if (/^https?:\/\/itch\.io\/s\/[\d]+?\/.*/.test(link)) {
  8653. return await this.itch(link);
  8654. }
  8655. return false;
  8656. } catch (error) {
  8657. throwError(error, 'leftKeyChecker.classify');
  8658. return false;
  8659. }
  8660. },
  8661. async giveawaySu(link) {
  8662. try {
  8663. const {
  8664. result,
  8665. data
  8666. } = await tools_httpRequest({
  8667. url: link,
  8668. method: 'GET'
  8669. });
  8670. if (result === 'Success' && data?.status === 200) {
  8671. if (data.responseText.includes('class="steam-login"')) {
  8672. return false;
  8673. }
  8674. if (data.responseText.includes('class="giveaway-ended"')) {
  8675. return 'Ended';
  8676. }
  8677. return 'Active';
  8678. }
  8679. return false;
  8680. } catch (error) {
  8681. throwError(error, 'leftKeyChecker.giveawaySu');
  8682. return false;
  8683. }
  8684. },
  8685. async giveeClub(link) {
  8686. try {
  8687. const {
  8688. result,
  8689. data
  8690. } = await tools_httpRequest({
  8691. url: link,
  8692. method: 'GET'
  8693. });
  8694. if (result === 'Success' && data?.status === 200) {
  8695. if (data.responseText.includes('class="event-winner"')) {
  8696. return 'Won';
  8697. }
  8698. if (data.responseText.includes('class="event-ended"')) {
  8699. return 'Ended';
  8700. }
  8701. return 'Active';
  8702. }
  8703. return false;
  8704. } catch (error) {
  8705. throwError(error, 'leftKeyChecker.giveeClub');
  8706. return false;
  8707. }
  8708. },
  8709. async gleam(link) {
  8710. try {
  8711. const {
  8712. result,
  8713. data
  8714. } = await tools_httpRequest({
  8715. url: link,
  8716. method: 'GET'
  8717. });
  8718. if (result === 'Success' && data?.status === 200) {
  8719. if (/incentives&quot;:{&quot;[\d]+?&quot;:\[&quot;.+?&quot;\]/.test(data.responseText)) {
  8720. return 'Won';
  8721. }
  8722. const campaignDiv = data.responseText.match(/<div class='popup-blocks-container'[\w\W]+?'>/)?.[0];
  8723. if (!campaignDiv) {
  8724. return false;
  8725. }
  8726. const campaignString = $(campaignDiv).attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  8727. if (!campaignString) {
  8728. return false;
  8729. }
  8730. const {
  8731. campaign
  8732. } = JSON.parse(campaignString);
  8733. if (campaign.banned) {
  8734. return 'Banned';
  8735. }
  8736. if (campaign.finished) {
  8737. return 'Ended';
  8738. }
  8739. if (campaign.paused) {
  8740. return 'Paused';
  8741. }
  8742. if (new Date().getTime() < campaign.starts_at * 1e3) {
  8743. return 'NotStart';
  8744. }
  8745. return 'Active';
  8746. }
  8747. return false;
  8748. } catch (error) {
  8749. throwError(error, 'leftKeyChecker.gleam');
  8750. return false;
  8751. }
  8752. },
  8753. async indieDb(link) {
  8754. try {
  8755. const {
  8756. result,
  8757. data
  8758. } = await tools_httpRequest({
  8759. url: link,
  8760. method: 'GET'
  8761. });
  8762. if (result === 'Success' && data?.status === 200) {
  8763. if (data.responseText.includes('Congrats you WON')) {
  8764. return 'Won';
  8765. }
  8766. if (data.responseText.includes('Giveaway is closed') || data.responseText.includes('next time')) {
  8767. return 'Ended';
  8768. }
  8769. return 'Active';
  8770. }
  8771. return false;
  8772. } catch (error) {
  8773. throwError(error, 'leftKeyChecker.indieDb');
  8774. return false;
  8775. }
  8776. },
  8777. async keyhub(link) {
  8778. try {
  8779. const {
  8780. result,
  8781. data
  8782. } = await tools_httpRequest({
  8783. url: link,
  8784. method: 'GET'
  8785. });
  8786. if (result === 'Success' && data?.status === 200) {
  8787. const keysleft = data.responseText.match(/<span id="keysleft">([\d]+?)<\/span>/)?.[1];
  8788. if (!keysleft) {
  8789. return false;
  8790. }
  8791. if (keysleft === '0') {
  8792. return 'Ended';
  8793. }
  8794. return `Active(${keysleft})`;
  8795. }
  8796. return false;
  8797. } catch (error) {
  8798. throwError(error, 'leftKeyChecker.keyhub');
  8799. return false;
  8800. }
  8801. },
  8802. async opquests(link) {
  8803. try {
  8804. const {
  8805. result,
  8806. data
  8807. } = await tools_httpRequest({
  8808. url: link,
  8809. method: 'GET'
  8810. });
  8811. if (result === 'Success' && data?.status === 200) {
  8812. const keysleft = data.responseText.match(/<div class="">[\s]*?([\d]+?)[\s]*?of/)?.[1];
  8813. if (!keysleft) {
  8814. return false;
  8815. }
  8816. if (keysleft === '0') {
  8817. return 'Ended';
  8818. }
  8819. return `Active(${keysleft})`;
  8820. } else if (data?.status === 404) {
  8821. return 'Ended';
  8822. }
  8823. return false;
  8824. } catch (error) {
  8825. throwError(error, 'leftKeyChecker.opquests');
  8826. return false;
  8827. }
  8828. },
  8829. async itch(link) {
  8830. try {
  8831. const {
  8832. result,
  8833. data
  8834. } = await tools_httpRequest({
  8835. url: link,
  8836. method: 'GET'
  8837. });
  8838. if (result === 'Success' && data?.status === 200) {
  8839. const endDate = data.responseText.match(/{"start_date":"[0-9A-Z-:]+?".*?"end_date":"([0-9A-Z-:]+?)".*?}/)?.[1];
  8840. if (!endDate) {
  8841. return false;
  8842. }
  8843. if (new Date().getTime() > new Date(endDate).getTime()) {
  8844. return 'Ended';
  8845. }
  8846. return `Active(${external_dayjs_default()(endDate).format('YYYY-MM-DD HH:mm:ss')})`;
  8847. }
  8848. return false;
  8849. } catch (error) {
  8850. throwError(error, 'leftKeyChecker.itch');
  8851. return false;
  8852. }
  8853. }
  8854. };
  8855. const website_leftKeyChecker = leftKeyChecker;
  8856. const Keylol_defaultTasksTemplate = {
  8857. steam: {
  8858. groupLinks: [],
  8859. wishlistLinks: [],
  8860. curatorLinks: [],
  8861. curatorLikeLinks: [],
  8862. followLinks: [],
  8863. forumLinks: [],
  8864. announcementLinks: [],
  8865. workshopVoteLinks: [],
  8866. licenseLinks: []
  8867. },
  8868. discord: {
  8869. serverLinks: []
  8870. },
  8871. instagram: {
  8872. userLinks: []
  8873. },
  8874. vk: {
  8875. nameLinks: []
  8876. },
  8877. twitch: {
  8878. channelLinks: []
  8879. },
  8880. reddit: {
  8881. redditLinks: []
  8882. },
  8883. twitter: {
  8884. userLinks: [],
  8885. retweetLinks: []
  8886. },
  8887. youtube: {
  8888. channelLinks: [],
  8889. likeLinks: []
  8890. }
  8891. };
  8892. const Keylol_defaultTasks = JSON.stringify(Keylol_defaultTasksTemplate);
  8893. class Keylol extends website_Website {
  8894. name = 'Keylol';
  8895. socialTasks = JSON.parse(Keylol_defaultTasks);
  8896. undoneTasks = JSON.parse(Keylol_defaultTasks);
  8897. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect' ];
  8898. static test() {
  8899. return window.location.host === 'keylol.com' && (!!$('.subforum_left_title_left_up a').eq(3).attr('href')?.includes('319') || !!$('.subforum_left_title_left_up a').eq(3).attr('href')?.includes('234'));
  8900. }
  8901. init() {
  8902. return true;
  8903. }
  8904. after() {
  8905. try {
  8906. const selector = this.name === 'Keylol' ? '#postlist>div[id^="post_"]:first' : 'div.container';
  8907. const mainPost = $(selector);
  8908. const discordLinks = mainPost.find('a[href*="discord.com"]:visible');
  8909. const redditLinks = mainPost.find('a[href*="reddit.com"]:visible');
  8910. const insLinks = mainPost.find('a[href*="instagram.com"]:visible');
  8911. const twitterLinks = mainPost.find('a[href*="twitter.com"]:visible,a[href*="x.com"]:visible');
  8912. const twitchLinks = mainPost.find('a[href*="twitch.tv"]:visible');
  8913. const vkLinks = mainPost.find('a[href*="vk.com"]:visible');
  8914. const steamStoreLinks = mainPost.find('a[href*="store.steampowered.com"]:visible');
  8915. const steamCommunityLinks = mainPost.find('a[href*="steamcommunity.com"]:visible');
  8916. const ytbLinks = mainPost.find('a[href*="youtube.com"]:visible');
  8917. if (discordLinks.length > 0) {
  8918. for (const discordLink of discordLinks) {
  8919. const link = $(discordLink).attr('href');
  8920. if (!(link && /^https?:\/\/discord\.com\/invite\/.+/.test(link))) {
  8921. continue;
  8922. }
  8923. this.#addBtn(discordLink, 'discord', 'serverLinks', link);
  8924. }
  8925. }
  8926. if (redditLinks.length > 0) {
  8927. for (const redditLink of redditLinks) {
  8928. const link = $(redditLink).attr('href');
  8929. if (!(link && /^https?:\/\/www\.reddit\.com\/(r|user)\/.+/.test(link))) {
  8930. continue;
  8931. }
  8932. this.#addBtn(redditLink, 'reddit', 'redditLinks', link);
  8933. }
  8934. }
  8935. if (insLinks.length > 0) {
  8936. for (const insLink of insLinks) {
  8937. const link = $(insLink).attr('href');
  8938. if (!(link && /^https:\/\/www\.instagram\.com\/.+/.test(link))) {
  8939. continue;
  8940. }
  8941. this.#addBtn(insLink, 'instagram', 'userLinks', link);
  8942. }
  8943. }
  8944. if (twitterLinks.length > 0) {
  8945. for (const twitterLink of twitterLinks) {
  8946. const link = $(twitterLink).attr('href');
  8947. if (!(link && /^https:\/\/twitter\.com\/.+/.test(link))) {
  8948. continue;
  8949. }
  8950. if (/https:\/\/twitter\.com\/.*?\/status\/[\d]+/.test(link)) {
  8951. this.#addBtn(twitterLink, 'twitter', 'retweetLinks', link);
  8952. } else {
  8953. this.#addBtn(twitterLink, 'twitter', 'userLinks', link);
  8954. }
  8955. }
  8956. }
  8957. if (twitchLinks.length > 0) {
  8958. for (const twitchLink of twitchLinks) {
  8959. const link = $(twitchLink).attr('href');
  8960. if (!(link && /^https:\/\/(www\.)?twitch\.tv\/.+/.test(link))) {
  8961. continue;
  8962. }
  8963. this.#addBtn(twitchLink, 'twitch', 'channelLinks', link);
  8964. }
  8965. }
  8966. if (vkLinks.length > 0) {
  8967. for (const vkLink of vkLinks) {
  8968. const link = $(vkLink).attr('href');
  8969. if (!(link && /^https:\/\/vk\.com\/.+/.test(link))) {
  8970. continue;
  8971. }
  8972. this.#addBtn(vkLink, 'vk', 'nameLinks', link);
  8973. }
  8974. }
  8975. if (steamStoreLinks.length > 0) {
  8976. for (const steamStoreLink of steamStoreLinks) {
  8977. const link = $(steamStoreLink).attr('href');
  8978. if (!link) {
  8979. continue;
  8980. }
  8981. if (/curator\/[\d]+/.test(link)) {
  8982. this.#addBtn(steamStoreLink, 'steam', 'curatorLinks', link);
  8983. } else if (/(publisher|developer|franchise)\/.+/.test(link)) {
  8984. this.#addBtn(steamStoreLink, 'steam', 'curatorLikeLinks', link);
  8985. } else if (/news(hub)?\/app\/[\d]+\/view\/[\d]+/.test(link)) {
  8986. this.#addBtn(steamStoreLink, 'steam', 'announcementLinks', link);
  8987. } else if (/app\/[\d]+/.test(link)) {
  8988. this.#addBtn(steamStoreLink, 'steam', 'followLinks', link);
  8989. this.#addBtn(steamStoreLink, 'steam', 'wishlistLinks', link);
  8990. }
  8991. }
  8992. }
  8993. if (steamCommunityLinks.length > 0) {
  8994. for (const steamCommunityLink of steamCommunityLinks) {
  8995. const link = $(steamCommunityLink).attr('href');
  8996. if (!link) {
  8997. continue;
  8998. }
  8999. if (/groups\/.+/.test(link)) {
  9000. this.#addBtn(steamCommunityLink, 'steam', 'groupLinks', link);
  9001. } else if (/announcements\/detail\/[\d]+/.test(link)) {
  9002. this.#addBtn(steamCommunityLink, 'steam', 'announcementLinks', link);
  9003. }
  9004. }
  9005. }
  9006. if (ytbLinks.length > 0) {
  9007. for (const ytbLink of ytbLinks) {
  9008. const link = $(ytbLink).attr('href');
  9009. if (!link) {
  9010. continue;
  9011. }
  9012. this.#addBtn(ytbLink, 'youtube', 'channelLinks', link);
  9013. this.#addBtn(ytbLink, 'youtube', 'likeLinks', link);
  9014. }
  9015. }
  9016. const giveawayLinks = mainPost.find('a[href*="giveaway.su/giveaway/view/"]:visible,a[href*="givee.club/"]:visible,a[href*="gleam.io/"]:visible,a[href*="www.indiedb.com/giveaways/"]:visible,a[href*="key-hub.eu/giveaway/"]:visible,a[href*="opquests.com/quests/"]:visible,a[href*="itch.io/s/"]:visible');
  9017. if (giveawayLinks.length > 0) {
  9018. for (const giveawayLink of giveawayLinks) {
  9019. const link = $(giveawayLink).attr('href');
  9020. if (!link) {
  9021. continue;
  9022. }
  9023. website_leftKeyChecker.classify(link).then(status => {
  9024. if (!status) {
  9025. return;
  9026. }
  9027. if (/^Active/.test(status)) {
  9028. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status active" title="${i18n('Active')}">${status}</font>`);
  9029. return;
  9030. }
  9031. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status not-active" title="${i18n(status)}">${status}</font>`);
  9032. }).catch(error => {
  9033. throwError(error, 'keylol.after -> leftKeyChecker');
  9034. });
  9035. }
  9036. }
  9037. if (this.name === 'Keylol') {
  9038. const asfLinks = mainPost.find('a[href^="#asf"]:visible');
  9039. if (asfLinks.length > 0) {
  9040. for (const asfLink of asfLinks) {
  9041. const link = $(asfLink).attr('href');
  9042. if (!link) {
  9043. continue;
  9044. }
  9045. this.#addBtn($(`a[href="${link}"]`).after('<span style="color: #ccc; margin: 0 -5px 0 5px"> | </span>').next()[0], 'steam', 'licenseLinks', `appid-${link.replace('#asf', '')}`);
  9046. }
  9047. }
  9048. const subLinks = mainPost.find('a[href*="steamdb.info/sub/"]:visible');
  9049. if (subLinks.length > 0) {
  9050. for (const subLink of subLinks) {
  9051. const link = $(subLink).attr('href');
  9052. if (!link) {
  9053. continue;
  9054. }
  9055. const subid = link.match(/^https:\/\/steamdb\.info\/sub\/([\d]+)/)?.[1];
  9056. if (!subid) {
  9057. continue;
  9058. }
  9059. this.#addBtn(subLink, 'steam', 'licenseLinks', `subid-${subid}`);
  9060. }
  9061. }
  9062. const asfLinks2 = mainPost.find('.blockcode:contains("addlicense"):visible');
  9063. if (asfLinks2.length > 0) {
  9064. for (const asfLink of asfLinks2) {
  9065. const appid = [ ...asfLink.innerText.matchAll(/a(pp)?\/([\d]+)/g) ].map(matched => matched?.[2]).filter(id => id) || [];
  9066. if (appid.length > 0) {
  9067. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `appid-${appid.join(',')}`);
  9068. }
  9069. const subid = asfLink.innerText.match(/[\d]+/g)?.filter(matched => !appid.includes(matched));
  9070. if (!subid || subid.length === 0) {
  9071. continue;
  9072. }
  9073. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `subid-${subid.join(',')}`);
  9074. }
  9075. }
  9076. }
  9077. if ($('#threadindex').length > 0) {
  9078. const [ targetNode ] = $('#postlist').children('div[id^="post_"]');
  9079. const config = {
  9080. childList: true
  9081. };
  9082. const observer = new MutationObserver(() => {
  9083. observer.disconnect();
  9084. this.after();
  9085. });
  9086. observer.observe(targetNode, config);
  9087. }
  9088. } catch (error) {
  9089. throwError(error, 'keylol.after');
  9090. }
  9091. }
  9092. classifyTask(action) {
  9093. try {
  9094. this.socialTasks = JSON.parse(Keylol_defaultTasks);
  9095. this.undoneTasks = JSON.parse(Keylol_defaultTasks);
  9096. const selectedBtns = $('.auto-task-keylol[selected="selected"]:visible');
  9097. for (const btn of selectedBtns) {
  9098. const button = $(btn);
  9099. const social = button.attr('data-social');
  9100. const type = button.attr('data-type');
  9101. const link = button.attr('data-link');
  9102. if (!(social && type && link)) {
  9103. continue;
  9104. }
  9105. if (action === 'do') {
  9106. this.undoneTasks[social][type].push(link);
  9107. }
  9108. if (action === 'undo') {
  9109. this.socialTasks[social][type].push(link);
  9110. }
  9111. }
  9112. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9113. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9114. if (window.DEBUG) {
  9115. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9116. }
  9117. return true;
  9118. } catch (error) {
  9119. throwError(error, 'Keylol.classifyTask');
  9120. return false;
  9121. }
  9122. }
  9123. selectAll() {
  9124. try {
  9125. $('.auto-task-keylol:visible').attr('selected', 'selected');
  9126. } catch (error) {
  9127. throwError(error, 'Keylol.selectAll');
  9128. }
  9129. }
  9130. selectNone() {
  9131. try {
  9132. $('.auto-task-keylol:visible').removeAttr('selected');
  9133. } catch (error) {
  9134. throwError(error, 'Keylol.selectNone');
  9135. }
  9136. }
  9137. invertSelect() {
  9138. try {
  9139. $('.auto-task-keylol:visible').each((index, element) => {
  9140. element.getAttribute('selected') ? element.removeAttribute('selected') : element.setAttribute('selected', 'selected');
  9141. });
  9142. } catch (error) {
  9143. throwError(error, 'Keylol.invertSelect');
  9144. }
  9145. }
  9146. #addBtn(before, social, linkType, link) {
  9147. try {
  9148. $(before).after('<a href="javascript:void(0);" class="auto-task-keylol" target="_self"' + ' onclick="this.getAttribute(\'selected\') ? this.removeAttribute(\'selected\') : this.setAttribute(\'selected\', \'selected\')"' + ` data-social="${social}" data-type="${linkType}" data-link="${link}">${linkType.replace('Links', '')}</a>`);
  9149. } catch (error) {
  9150. throwError(error, 'keylol.addBtn');
  9151. }
  9152. }
  9153. }
  9154. const website_Keylol = Keylol;
  9155. const Opquests_defaultTasks = {
  9156. steam: {
  9157. groupLinks: [],
  9158. wishlistLinks: [],
  9159. followLinks: [],
  9160. curatorLikeLinks: []
  9161. }
  9162. };
  9163. class Opquests extends website_Website {
  9164. name = 'Opquests';
  9165. undoneTasks = {
  9166. ...Opquests_defaultTasks
  9167. };
  9168. buttons = [ 'doTask', 'verifyTask', 'getKey' ];
  9169. static test() {
  9170. return window.location.host === 'opquests.com';
  9171. }
  9172. async after() {
  9173. try {
  9174. if (!this.#checkLogin()) {
  9175. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9176. }
  9177. const opquestsVerifyTasks = GM_getValue('opquestsVerifyTasks') || [];
  9178. if (opquestsVerifyTasks.length > 0) {
  9179. const taskId = opquestsVerifyTasks.pop();
  9180. GM_setValue('opquestsVerifyTasks', opquestsVerifyTasks);
  9181. const [ verifyBtn ] = $(`#task_id[value="${taskId}"]`).parent().find('button[type="button"]').has('i.fa-check');
  9182. if (verifyBtn) {
  9183. verifyBtn.click();
  9184. return;
  9185. }
  9186. this.after();
  9187. return;
  9188. }
  9189. if (GM_getValue('opquestsVerifyTasks')) {
  9190. GM_deleteValue('opquestsVerifyTasks');
  9191. }
  9192. } catch (error) {
  9193. throwError(error, 'Opquests.after');
  9194. }
  9195. }
  9196. init() {
  9197. try {
  9198. const logStatus = scripts_echoLog({
  9199. text: i18n('initing')
  9200. });
  9201. if ($('a[href*="/auth/redirect"]').length > 0) {
  9202. window.open('/auth/redirect', '_self');
  9203. logStatus.warning(i18n('needLogin'));
  9204. return false;
  9205. }
  9206. if (!this.#getGiveawayId()) {
  9207. return false;
  9208. }
  9209. this.initialized = true;
  9210. logStatus.success();
  9211. return true;
  9212. } catch (error) {
  9213. throwError(error, 'Opquests.init');
  9214. return false;
  9215. }
  9216. }
  9217. async classifyTask(action) {
  9218. try {
  9219. if (action === 'undo') {
  9220. scripts_echoLog({
  9221. text: i18n('cannotUndo')
  9222. });
  9223. return false;
  9224. }
  9225. const logStatus = scripts_echoLog({
  9226. text: i18n('getTasksInfo')
  9227. });
  9228. const tasks = $('.w-full:contains("Validate") .items-center');
  9229. for (const task of tasks) {
  9230. const link = $(task).find('a:contains("Open")').attr('href');
  9231. const taskDes = $(task).find('div').eq(1).text().trim();
  9232. if (!link) {
  9233. continue;
  9234. }
  9235. if (/steamcommunity\.com\/groups\//.test(link)) {
  9236. this.undoneTasks.steam.groupLinks.push(link);
  9237. } else if (/store\.steampowered\.com\/app\//.test(link)) {
  9238. if (/wishlist/gim.test(taskDes)) {
  9239. this.undoneTasks.steam.wishlistLinks.push(link);
  9240. } else if (/follow/gim.test(taskDes)) {
  9241. this.undoneTasks.steam.followLinks.push(link);
  9242. }
  9243. } else if (/store\.steampowered\.com\/(publisher|developer|curator)\//.test(link) && /follow/gim.test(taskDes)) {
  9244. this.undoneTasks.steam.curatorLikeLinks.push(link);
  9245. } else {
  9246. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  9247. }
  9248. }
  9249. logStatus.success();
  9250. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9251. if (window.DEBUG) {
  9252. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9253. }
  9254. return true;
  9255. } catch (error) {
  9256. throwError(error, 'Opquests.classifyTask');
  9257. return false;
  9258. }
  9259. }
  9260. async verifyTask() {
  9261. try {
  9262. if (!this.initialized) {
  9263. this.init();
  9264. }
  9265. const tasks = $.makeArray($('.items-center').has('input[name="task_id"]')).map(ele => $(ele).find('input[name="task_id"]').val());
  9266. GM_setValue('opquestsVerifyTasks', tasks);
  9267. await this.#confirm();
  9268. this.after();
  9269. return true;
  9270. } catch (error) {
  9271. throwError(error, 'Opquests.verifyTask');
  9272. return false;
  9273. }
  9274. }
  9275. async #confirm() {
  9276. try {
  9277. const logStatus = scripts_echoLog({
  9278. html: `<li>${i18n('confirmingTask')}...<font></font></li>`
  9279. });
  9280. const {
  9281. result,
  9282. statusText,
  9283. status,
  9284. data
  9285. } = await tools_httpRequest({
  9286. url: `https://opquests.com/quests/${this.giveawayId}?confirm=1`,
  9287. method: 'GET',
  9288. nochche: true,
  9289. headers: {
  9290. origin: 'https://opquests.com',
  9291. referer: `https://opquests.com/warning?id=${this.giveawayId}`
  9292. }
  9293. });
  9294. if (result === 'Success') {
  9295. if (data?.status === 200) {
  9296. logStatus.success();
  9297. return true;
  9298. }
  9299. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9300. return false;
  9301. }
  9302. logStatus.error(`${result}:${statusText}(${status})`);
  9303. return false;
  9304. } catch (error) {
  9305. throwError(error, 'Opquests.confirm');
  9306. return false;
  9307. }
  9308. }
  9309. async getKey(isButton) {
  9310. try {
  9311. const logStatus = scripts_echoLog({
  9312. text: i18n('gettingKey')
  9313. });
  9314. const {
  9315. result,
  9316. statusText,
  9317. status,
  9318. data
  9319. } = await tools_httpRequest({
  9320. url: 'https://opquests.com/keys',
  9321. method: 'GET'
  9322. });
  9323. if (result === 'Success') {
  9324. if (data?.responseText) {
  9325. const key = $(data?.responseText).find(`div.items-center:contains("${$('h1.font-bold').text().trim().replace(' Quest', '')}")`).find('div.font-bold').next().text();
  9326. if (!key) {
  9327. logStatus.error('Error: Key was not found');
  9328. if (isButton) {
  9329. window.open('https://opquests.com/keys', '_self');
  9330. }
  9331. return false;
  9332. }
  9333. logStatus.success();
  9334. scripts_echoLog({}).success(key);
  9335. return true;
  9336. }
  9337. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9338. return false;
  9339. }
  9340. logStatus.error(`${result}:${statusText}(${status})`);
  9341. return false;
  9342. } catch (error) {
  9343. throwError(error, 'Opquests.getGiveawayId');
  9344. return false;
  9345. }
  9346. }
  9347. #getGiveawayId() {
  9348. try {
  9349. const giveawayId = window.location.href.match(/quests\/([\d]+)/)?.[1];
  9350. if (giveawayId) {
  9351. this.giveawayId = giveawayId;
  9352. return true;
  9353. }
  9354. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  9355. return false;
  9356. } catch (error) {
  9357. throwError(error, 'Opquests.getGiveawayId');
  9358. return false;
  9359. }
  9360. }
  9361. #checkLogin() {
  9362. try {
  9363. if (!globalOptions.other.checkLogin) {
  9364. return true;
  9365. }
  9366. if ($('a[href*="/auth/redirect"]').length > 0) {
  9367. window.open('/auth/redirect', '_self');
  9368. }
  9369. return true;
  9370. } catch (error) {
  9371. throwError(error, 'Opquests.checkLogin');
  9372. return false;
  9373. }
  9374. }
  9375. }
  9376. const website_Opquests = Opquests;
  9377. const Gleam_defaultTasksTemplate = {
  9378. steam: {
  9379. groupLinks: [],
  9380. wishlistLinks: [],
  9381. followLinks: [],
  9382. curatorLinks: [],
  9383. curatorLikeLinks: []
  9384. },
  9385. twitter: {
  9386. userLinks: [],
  9387. retweetLinks: []
  9388. },
  9389. twitch: {
  9390. channelLinks: []
  9391. },
  9392. discord: {
  9393. serverLinks: []
  9394. },
  9395. youtube: {
  9396. channelLinks: []
  9397. },
  9398. extra: {
  9399. gleam: []
  9400. }
  9401. };
  9402. const Gleam_defaultTasks = JSON.stringify(Gleam_defaultTasksTemplate);
  9403. class Gleam extends website_Website {
  9404. name = 'Gleam';
  9405. undoneTasks = JSON.parse(Gleam_defaultTasks);
  9406. socialTasks = JSON.parse(Gleam_defaultTasks);
  9407. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  9408. static test() {
  9409. return window.location.host === 'gleam.io';
  9410. }
  9411. before() {
  9412. try {
  9413. unsafeWindow.confirm = () => {};
  9414. unsafeWindow.alert = () => {};
  9415. unsafeWindow.prompt = () => {};
  9416. } catch (error) {
  9417. throwError(error, 'Gleam.before');
  9418. }
  9419. }
  9420. async after() {
  9421. try {
  9422. if (window.location.search.includes('8b07d23f4bfa65f9')) {
  9423. const checkComplete = setInterval(() => {
  9424. if ($('.entry-content .entry-method i.fa-check').length > 0) {
  9425. clearInterval(checkComplete);
  9426. window.close();
  9427. }
  9428. });
  9429. for (const task of $('.entry-content .entry-method')) {
  9430. const taskInfo = $(task).find('.user-links');
  9431. const expandInfo = $(task).find('.expandable');
  9432. const aElements = expandInfo.find('a.btn,a:contains(Continue),button:contains(Continue)');
  9433. if (aElements.length > 0) {
  9434. for (const element of aElements) {
  9435. const $element = $(element);
  9436. const href = $element.attr('href');
  9437. $element.removeAttr('href')[0].click();
  9438. $element.attr('href', href);
  9439. await delay(1e3);
  9440. }
  9441. }
  9442. taskInfo[0].click();
  9443. await delay(1e3);
  9444. }
  9445. scripts_echoLog({}).warning(i18n('gleamTaskNotice'));
  9446. } else if (!await this.#checkLeftKey()) {
  9447. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  9448. }
  9449. } catch (error) {
  9450. throwError(error, 'Gleam.after');
  9451. }
  9452. }
  9453. init() {
  9454. try {
  9455. const logStatus = scripts_echoLog({
  9456. text: i18n('initing')
  9457. });
  9458. if (!this.#getGiveawayId()) {
  9459. return false;
  9460. }
  9461. this.initialized = true;
  9462. logStatus.success();
  9463. return true;
  9464. } catch (error) {
  9465. throwError(error, 'Gleam.init');
  9466. return false;
  9467. }
  9468. }
  9469. async classifyTask(action) {
  9470. try {
  9471. const logStatus = scripts_echoLog({
  9472. text: i18n('getTasksInfo')
  9473. });
  9474. if (action === 'undo') {
  9475. this.socialTasks = GM_getValue(`gleamTasks-${this.giveawayId}`)?.tasks || JSON.parse(Gleam_defaultTasks);
  9476. }
  9477. const tasks = $('.entry-content .entry-method');
  9478. for (const task of tasks) {
  9479. const $task = $(task);
  9480. if (action === 'do' && $task.find('i.fa-question').length === 0) {
  9481. continue;
  9482. }
  9483. const socialIcon = $task.find('.icon-wrapper i');
  9484. const taskInfo = $task.find('.user-links');
  9485. const taskText = taskInfo.text().trim();
  9486. const expandInfo = $task.find('.expandable');
  9487. const aElements = expandInfo.find('a.btn');
  9488. if (aElements.length > 0) {
  9489. for (const element of aElements) {
  9490. const $element = $(element);
  9491. const href = $element.attr('href');
  9492. $element.removeAttr('href')[0].click();
  9493. $element.attr('href', href);
  9494. }
  9495. }
  9496. if (socialIcon.hasClass('fa-twitter') || socialIcon.hasClass('fa-x-twitter')) {
  9497. const link = $task.find('a[href^="https://twitter.com/"],a[href^="https://x.com/"]').attr('href');
  9498. if (!link) {
  9499. continue;
  9500. }
  9501. if (/follow/gi.test(taskText)) {
  9502. if (action === 'undo') {
  9503. this.socialTasks.twitter.userLinks.push(link);
  9504. }
  9505. if (action === 'do') {
  9506. this.undoneTasks.twitter.userLinks.push(link);
  9507. }
  9508. } else if (/retweet/gim.test(taskText)) {
  9509. if (action === 'undo') {
  9510. this.socialTasks.twitter.retweetLinks.push(link);
  9511. }
  9512. if (action === 'do') {
  9513. this.undoneTasks.twitter.retweetLinks.push(link);
  9514. }
  9515. }
  9516. } else if (socialIcon.hasClass('fa-twitch')) {
  9517. if (/follow/gim.test(taskText)) {
  9518. const link = $task.find('a[href^="https://twitch.tv/"]').attr('href');
  9519. if (!link) {
  9520. continue;
  9521. }
  9522. if (action === 'undo') {
  9523. this.socialTasks.twitch.channelLinks.push(link);
  9524. }
  9525. if (action === 'do') {
  9526. this.undoneTasks.twitch.channelLinks.push(link);
  9527. }
  9528. }
  9529. } else if (socialIcon.hasClass('fa-discord')) {
  9530. if (/join/gim.test(taskText)) {
  9531. let link = $task.find('a[href^="https://discord.com/invite/"]').attr('href');
  9532. if (!link) {
  9533. const ggLink = $task.find('a[href^="https://discord.gg/"]').attr('href')?.match(/discord\.gg\/([^/]+)/)?.[1];
  9534. if (!ggLink) {
  9535. continue;
  9536. }
  9537. link = `https://discord.com/invite/${ggLink}`;
  9538. }
  9539. if (action === 'undo') {
  9540. this.socialTasks.discord.serverLinks.push(link);
  9541. }
  9542. if (action === 'do') {
  9543. this.undoneTasks.discord.serverLinks.push(link);
  9544. }
  9545. }
  9546. } else if (socialIcon.hasClass('fa-external-link-square-alt')) {
  9547. continue;
  9548. } else if (socialIcon.hasClass('fa-youtube')) {
  9549. if (/subscribe/gim.test(taskText)) {
  9550. const link = $task.find('a[href^="https://www.youtube.com/channel/"]').attr('href');
  9551. if (!link) {
  9552. continue;
  9553. }
  9554. if (action === 'undo') {
  9555. this.socialTasks.youtube.channelLinks.push(link);
  9556. }
  9557. if (action === 'do') {
  9558. this.undoneTasks.youtube.channelLinks.push(link);
  9559. }
  9560. }
  9561. } else if (socialIcon.attr('class')?.includes('steam')) {
  9562. if (/join.*group/gi.test(taskText)) {
  9563. const link = $task.find('a[href^="https://steamcommunity.com/groups/"]').attr('href');
  9564. if (!link) {
  9565. continue;
  9566. }
  9567. if (action === 'undo') {
  9568. this.socialTasks.steam.groupLinks.push(link);
  9569. }
  9570. if (action === 'do') {
  9571. this.undoneTasks.steam.groupLinks.push(link);
  9572. }
  9573. } else if (/follow.*curator/gi.test(taskText)) {
  9574. const link = $task.find('a[href^="https://store.steampowered.com/curator/"]').attr('href');
  9575. if (!link) {
  9576. continue;
  9577. }
  9578. if (action === 'undo') {
  9579. this.socialTasks.steam.curatorLinks.push(link);
  9580. }
  9581. if (action === 'do') {
  9582. this.undoneTasks.steam.curatorLinks.push(link);
  9583. }
  9584. }
  9585. } else if (socialIcon.hasClass('fa-bullhorn') && /Complete|Increase/gi.test(taskText)) {
  9586. if (action !== 'do') {
  9587. continue;
  9588. }
  9589. const gleamLink = await this.#getGleamLink(taskText);
  9590. if (!gleamLink) {
  9591. continue;
  9592. }
  9593. this.undoneTasks.extra.gleam.push(gleamLink);
  9594. } else if (socialIcon.hasClass('fa-question') || socialIcon.hasClass('fa-reddit') || socialIcon.hasClass('fa-instagram') || socialIcon.hasClass('fa-facebook-f') || socialIcon.hasClass('fa-telegram-plane') || socialIcon.hasClass('fa-telegram') || socialIcon.hasClass('fa-vk') || socialIcon.hasClass('fa-envelope') || socialIcon.hasClass('fa-gift') || socialIcon.hasClass('fa-square-up-right') || socialIcon.hasClass('fa-gamepad-modern') || socialIcon.hasClass('fa-dollar-sign') || socialIcon.hasClass('fa-tiktok') || socialIcon.hasClass('fa-gamepad-alt') || socialIcon.hasClass('fa-shield') && taskText.includes('one of our giveaways') || socialIcon.hasClass('fa-shield') && taskText.includes('Check out') || socialIcon.hasClass('fa-shield') && taskText.includes('vloot.io')) {} else {
  9595. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskText}`);
  9596. }
  9597. }
  9598. logStatus.success();
  9599. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9600. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9601. if (window.DEBUG) {
  9602. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9603. }
  9604. GM_setValue(`gleamTasks-${this.giveawayId}`, {
  9605. tasks: this.socialTasks,
  9606. time: new Date().getTime()
  9607. });
  9608. return true;
  9609. } catch (error) {
  9610. throwError(error, 'Gleam.classifyTask');
  9611. return false;
  9612. }
  9613. }
  9614. async extraDoTask({
  9615. gleam
  9616. }) {
  9617. try {
  9618. const pro = [];
  9619. for (const link of gleam) {
  9620. pro.push(this.#doGleamTask(link));
  9621. }
  9622. return Promise.all(pro).then(() => true);
  9623. } catch (error) {
  9624. throwError(error, 'Gleam.extraDoTask');
  9625. return false;
  9626. }
  9627. }
  9628. async verifyTask() {
  9629. try {
  9630. scripts_echoLog({
  9631. text: `${i18n('verifyingTask')}...`
  9632. });
  9633. const tasks = $('.entry-content .entry-method');
  9634. unsafeWindow._OxA = '_OxA';
  9635. for (const task of tasks) {
  9636. if ($('[campaign-key="campaign.key"]').length > 0) {
  9637. return scripts_echoLog({
  9638. text: i18n('campaign')
  9639. });
  9640. }
  9641. const $task = $(task);
  9642. if ($task.find('i.fa-question').length === 0) {
  9643. continue;
  9644. }
  9645. const taskInfo = $task.find('.user-links');
  9646. taskInfo[0].click();
  9647. const aElements = $task.find('.expandable').find('a.btn');
  9648. if (aElements.length > 0) {
  9649. for (const element of aElements) {
  9650. const $element = $(element);
  9651. const href = $element.attr('href');
  9652. $element.removeAttr('href')[0].click();
  9653. $element.attr('href', href);
  9654. }
  9655. }
  9656. unsafeWindow.$hookTimer?.setSpeed(1e3);
  9657. const visitBtn = $task.find('.expandable').find('span:contains(more seconds),button:contains(more seconds)').filter(':visible');
  9658. if (visitBtn.length > 0 && unsafeWindow.$hookTimer) {
  9659. const newTab = GM_openInTab('', {
  9660. active: true
  9661. });
  9662. await delay(1e3);
  9663. newTab?.close();
  9664. window.focus();
  9665. }
  9666. await delay(3e3);
  9667. unsafeWindow.$hookTimer?.setSpeed(1);
  9668. const expandInfo = $task.find('.expandable');
  9669. const [ input ] = expandInfo.find('input');
  9670. if (input) {
  9671. const evt = new Event('input', {
  9672. bubbles: true,
  9673. cancelable: true,
  9674. composed: true
  9675. });
  9676. const valuelimit = [ ...expandInfo.text().matchAll(/"(.+?)"/g) ].at(-1)?.[1];
  9677. input.value = valuelimit || 'vloot';
  9678. input.dispatchEvent(evt);
  9679. await delay(1e3);
  9680. }
  9681. await this.#checkSync();
  9682. const continueBtn = $task.find('.expandable').find('span:contains(Continue),button:contains(Continue)');
  9683. for (const button of continueBtn) {
  9684. button.click();
  9685. await delay(500);
  9686. await this.#checkSync();
  9687. }
  9688. }
  9689. scripts_echoLog({
  9690. text: i18n('verifiedGleamTasks')
  9691. });
  9692. } catch (error) {
  9693. throwError(error, 'Gleam.verifyTask');
  9694. return false;
  9695. }
  9696. }
  9697. async #checkSync() {
  9698. try {
  9699. return await new Promise(resolve => {
  9700. const checker = setInterval(() => {
  9701. if ($('.entry-content .entry-method i.fa-sync').length === 0) {
  9702. clearInterval(checker);
  9703. resolve(true);
  9704. }
  9705. }, 500);
  9706. });
  9707. } catch (error) {
  9708. throwError(error, 'Gleam.checkSync');
  9709. return false;
  9710. }
  9711. }
  9712. async #doGleamTask(link) {
  9713. try {
  9714. const logStatus = scripts_echoLog({
  9715. text: i18n('doingGleamTask')
  9716. });
  9717. return await new Promise(resolve => {
  9718. GM_openInTab(`${link}?8b07d23f4bfa65f9`, {
  9719. active: true,
  9720. insert: true,
  9721. setParent: true
  9722. }).onclose = () => {
  9723. logStatus.success();
  9724. resolve(true);
  9725. };
  9726. });
  9727. } catch (error) {
  9728. throwError(error, 'Gleam.doGleamTask');
  9729. return false;
  9730. }
  9731. }
  9732. #getGiveawayId() {
  9733. try {
  9734. const giveawayId = window.location.pathname;
  9735. if (giveawayId) {
  9736. this.giveawayId = giveawayId;
  9737. return true;
  9738. }
  9739. scripts_echoLog({
  9740. text: i18n('getFailed', 'GiveawayId')
  9741. });
  9742. return false;
  9743. } catch (error) {
  9744. throwError(error, 'Gleam.getGiveawayId');
  9745. return false;
  9746. }
  9747. }
  9748. async #getGleamLink(title) {
  9749. try {
  9750. const logStatus = scripts_echoLog({
  9751. text: i18n('gettingGleamLink')
  9752. });
  9753. const {
  9754. result,
  9755. statusText,
  9756. status,
  9757. data
  9758. } = await tools_httpRequest({
  9759. url: 'https://www.vloot.io/api/v1/giveaways',
  9760. method: 'GET',
  9761. responseType: 'json'
  9762. });
  9763. if (result === 'Success') {
  9764. if (data?.status === 200 && data?.response?.Success === true && data?.response?.Data) {
  9765. const {
  9766. link
  9767. } = data.response.Data.find(giveaway => title.replace(/[\s]/g, '').toLowerCase().includes(giveaway.title.replace(/[\s]/g, '').toLowerCase())) || {};
  9768. if (link) {
  9769. logStatus.success();
  9770. return link;
  9771. }
  9772. logStatus.error(`Error:${i18n('getLinkFailed')}`);
  9773. return false;
  9774. }
  9775. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9776. return false;
  9777. }
  9778. logStatus.error(`${result}:${statusText}(${status})`);
  9779. return false;
  9780. } catch (error) {
  9781. throwError(error, 'Gleam.getGleamLink');
  9782. return false;
  9783. }
  9784. }
  9785. async #checkLeftKey() {
  9786. try {
  9787. if (!globalOptions.other.checkLeftKey) {
  9788. return true;
  9789. }
  9790. const campaignString = $('div.popup-blocks-container').attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  9791. if (!campaignString) {
  9792. return false;
  9793. }
  9794. const {
  9795. campaign,
  9796. incentive
  9797. } = JSON.parse(campaignString);
  9798. const controllerString = $('div.campaign.reward').attr('ng-init')?.match(/initContestant\(([\w\W]+?)\);/)?.[1];
  9799. let ownedKey = false;
  9800. if (controllerString) {
  9801. if (JSON.parse(controllerString).contestant?.claims?.incentives?.[incentive.id]?.length) {
  9802. ownedKey = true;
  9803. }
  9804. }
  9805. if (campaign.banned || campaign.finished && !ownedKey || campaign.paused || new Date().getTime() < campaign.starts_at * 1e3) {
  9806. await external_Swal_default().fire({
  9807. icon: 'warning',
  9808. title: i18n('notice'),
  9809. text: i18n('giveawayNotWork'),
  9810. confirmButtonText: i18n('confirm'),
  9811. cancelButtonText: i18n('cancel'),
  9812. showCancelButton: true
  9813. }).then(({
  9814. value
  9815. }) => {
  9816. if (value) {
  9817. window.close();
  9818. }
  9819. });
  9820. }
  9821. return true;
  9822. } catch (error) {
  9823. throwError(error, 'Gleam.checkLeftKey');
  9824. return false;
  9825. }
  9826. }
  9827. }
  9828. const website_Gleam = Gleam;
  9829. const SweepWidget_defaultOptions = {
  9830. username: '',
  9831. email: ''
  9832. };
  9833. class SweepWidget extends website_Website {
  9834. name = 'SweepWidget';
  9835. options = {
  9836. ...SweepWidget_defaultOptions,
  9837. ...GM_getValue('SweepWidgetOptions')
  9838. };
  9839. buttons = [ 'doTask' ];
  9840. static test() {
  9841. return /^https?:\/\/sweepwidget\.com\/view\/[\d]+/.test(window.location.href);
  9842. }
  9843. async after() {
  9844. try {
  9845. if (!this.#checkLogin()) {
  9846. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9847. }
  9848. } catch (error) {
  9849. throwError(error, 'SweepWidget.after');
  9850. }
  9851. }
  9852. init() {
  9853. try {
  9854. const logStatus = scripts_echoLog({
  9855. text: i18n('initing')
  9856. });
  9857. if (!this.#checkLogin()) {
  9858. logStatus.warning(i18n('needLogin'));
  9859. return false;
  9860. }
  9861. if (!this.#getGiveawayId()) {
  9862. return false;
  9863. }
  9864. this.initialized = true;
  9865. logStatus.success();
  9866. return true;
  9867. } catch (error) {
  9868. throwError(error, 'SweepWidget.init');
  9869. return false;
  9870. }
  9871. }
  9872. classifyTask() {
  9873. return true;
  9874. }
  9875. async doTask() {
  9876. try {
  9877. if ($('#unlock_rewards_main_wrapper').length === 0) {
  9878. if ($('input[name="sw__login_name"]:visible').length > 0) {
  9879. $('input[name="sw__login_name"]').val(this.options.username);
  9880. }
  9881. if ($('input[name="sw__login_email"]:visible').length > 0) {
  9882. $('input[name="sw__login_email"]').val(this.options.email);
  9883. }
  9884. if ($('#sw_login_button:visible').length > 0) {
  9885. $('#sw_login_button')[0].click();
  9886. }
  9887. if (!await this.#checkEnter()) {
  9888. return false;
  9889. }
  9890. }
  9891. const logStatus = scripts_echoLog({
  9892. text: i18n('SweepWidgetNotice')
  9893. });
  9894. const tasks = $('#sw_inner_entry_methods_l2_wrapper>div.sw_entry');
  9895. for (const task of tasks) {
  9896. const $task = $(task);
  9897. if ($task.find('i.fa-check:visible').length > 0) {
  9898. continue;
  9899. }
  9900. const title = $task.find('.sw_text_inner');
  9901. title[0].click();
  9902. const aElement = $task.find('a.sw_link');
  9903. const link = aElement.attr('href');
  9904. aElement.attr('href', '#a').attr('target', '_self');
  9905. aElement[0]?.click();
  9906. await delay(300);
  9907. aElement.attr('href', link).attr('target', '_blank');
  9908. $task.find('input[type="text"]').val('test');
  9909. const verifyBtn = $task.find('input.sw_verify');
  9910. if (verifyBtn.prop('disabled') === true) {
  9911. title[0].click();
  9912. await delay(300);
  9913. title[0].click();
  9914. await delay(300);
  9915. }
  9916. $task.find('input.sw_verify').removeAttr('disabled')[0]?.click();
  9917. await this.#checkFinish($task);
  9918. await delay(parseInt(`${Math.random() * (3e3 - 1e3 + 1) + 1e3}`, 10));
  9919. }
  9920. logStatus.success();
  9921. return true;
  9922. } catch (error) {
  9923. throwError(error, 'SweepWidget.doTask');
  9924. return false;
  9925. }
  9926. }
  9927. #checkLogin() {
  9928. try {
  9929. if ($('#twitter_login_button').length > 0) {
  9930. $('#twitter_login_button')[0].click();
  9931. }
  9932. return true;
  9933. } catch (error) {
  9934. throwError(error, 'SweepWidget.checkLogin');
  9935. return false;
  9936. }
  9937. }
  9938. #getGiveawayId() {
  9939. try {
  9940. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  9941. if (giveawayId) {
  9942. this.giveawayId = giveawayId;
  9943. return true;
  9944. }
  9945. scripts_echoLog({
  9946. text: i18n('getFailed', 'GiveawayId')
  9947. });
  9948. return false;
  9949. } catch (error) {
  9950. throwError(error, 'SweepWidget.getGiveawayId');
  9951. return false;
  9952. }
  9953. }
  9954. async #checkEnter() {
  9955. try {
  9956. return new Promise(resolve => {
  9957. const checker = setInterval(() => {
  9958. if ($('#unlock_rewards_main_wrapper').length > 0) {
  9959. clearInterval(checker);
  9960. resolve(true);
  9961. }
  9962. }, 500);
  9963. });
  9964. } catch (error) {
  9965. throwError(error, 'SweepWidget.checkEnter');
  9966. return false;
  9967. }
  9968. }
  9969. async #checkFinish($task) {
  9970. try {
  9971. return new Promise(resolve => {
  9972. const checker = setInterval(() => {
  9973. if ($task.find('i.fa-check:visible').length > 0 || $task.find('.sw_entry_input:visible').length === 0) {
  9974. clearInterval(checker);
  9975. resolve(true);
  9976. }
  9977. }, 500);
  9978. });
  9979. } catch (error) {
  9980. throwError(error, 'SweepWidget.checkFinish');
  9981. return false;
  9982. }
  9983. }
  9984. }
  9985. const website_SweepWidget = SweepWidget;
  9986. const defaultWhiteList = {
  9987. discord: {
  9988. servers: []
  9989. },
  9990. instagram: {
  9991. users: []
  9992. },
  9993. twitch: {
  9994. channels: []
  9995. },
  9996. twitter: {
  9997. users: [],
  9998. retweets: [],
  9999. likes: []
  10000. },
  10001. vk: {
  10002. names: []
  10003. },
  10004. youtube: {
  10005. channels: [],
  10006. likes: []
  10007. },
  10008. reddit: {
  10009. reddits: []
  10010. },
  10011. steam: {
  10012. groups: [],
  10013. officialGroups: [],
  10014. wishlists: [],
  10015. follows: [],
  10016. forums: [],
  10017. workshops: [],
  10018. curators: [],
  10019. workshopVotes: [],
  10020. curatorLikes: [],
  10021. announcements: [],
  10022. licenses: [],
  10023. playtests: []
  10024. }
  10025. };
  10026. const link2id = async function(type) {
  10027. try {
  10028. const link = $('#socialLink').val();
  10029. let id = '';
  10030. switch (type) {
  10031. case 'discord.servers':
  10032. id = link.match(/invite\/(.+)/)?.[1] || '';
  10033. break;
  10034.  
  10035. case 'instagram.users':
  10036. id = link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1] || '';
  10037. break;
  10038.  
  10039. case 'twitch.channels':
  10040. id = link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2] || '';
  10041. break;
  10042.  
  10043. case 'twitter.users':
  10044. id = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || '';
  10045. break;
  10046.  
  10047. case 'twitter.retweets':
  10048. id = link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1] || '';
  10049. break;
  10050.  
  10051. case 'vk.names':
  10052. id = link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1] || '';
  10053. break;
  10054.  
  10055. case 'youtube.channels':
  10056. id = (await getInfo(link, 'channel'))?.params?.channelId || '';
  10057. break;
  10058.  
  10059. case 'youtube.likes':
  10060. id = (await getInfo(link, 'likeVideo'))?.params?.videoId || '';
  10061. break;
  10062.  
  10063. case 'reddit.reddits':
  10064. id = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1] || link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1] || '';
  10065. break;
  10066.  
  10067. case 'steam.groups':
  10068. id = link.match(/groups\/(.+)\/?/)?.[1] || '';
  10069. break;
  10070.  
  10071. case 'steam.wishlists':
  10072. case 'steam.follows':
  10073. case 'steam.forums':
  10074. id = link.match(/app\/([\d]+)/)?.[1] || '';
  10075. break;
  10076.  
  10077. case 'steam.workshops':
  10078. id = link.match(/\?id=([\d]+)/)?.[1] || '';
  10079. break;
  10080.  
  10081. case 'steam.curators':
  10082. {
  10083. if (link.includes('curator')) {
  10084. id = link.match(/curator\/([\d]+)/)?.[1] || '';
  10085. } else {
  10086. const param = link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3);
  10087. if (!param || param.length !== 2) {
  10088. break;
  10089. }
  10090. const steam = new social_Steam();
  10091. if (await steam.init()) {
  10092. id = await steam.getCuratorId(param[0], param[1]) || '';
  10093. }
  10094. }
  10095. }
  10096. break;
  10097. }
  10098. return id;
  10099. } catch (error) {
  10100. throwError(error, 'link2id');
  10101. return i18n('getFailed', 'id');
  10102. }
  10103. };
  10104. const disabledType = {
  10105. steam: [ 'workshopVotes', 'curatorLikes', 'announcements' ],
  10106. twitter: [ 'likes' ]
  10107. };
  10108. const assignWhiteList = whiteList => {
  10109. try {
  10110. const newWhiteList = {};
  10111. for (const [ key, value ] of Object.entries(defaultWhiteList)) {
  10112. newWhiteList[key] = {
  10113. ...value,
  10114. ...whiteList[key]
  10115. };
  10116. }
  10117. return newWhiteList;
  10118. } catch (error) {
  10119. throwError(error, 'assignWhiteList');
  10120. return defaultWhiteList;
  10121. }
  10122. };
  10123. const whiteListOptions = function(showType) {
  10124. try {
  10125. const whiteList = assignWhiteList(GM_getValue('whiteList') || {});
  10126. let whiteListOptionsForm = `<form id="whiteListForm" class="auto-task-form">
  10127. <table class="auto-task-table"><thead><tr><td>${i18n('website')}</td><td>${i18n('type')}</td><td>${i18n('edit')}</td></tr></thead><tbody>`;
  10128. for (const [ social, types ] of Object.entries(whiteList)) {
  10129. whiteListOptionsForm += Object.keys(types).map((type, index) => disabledType[social]?.includes(type) ? '' : `<tr style="background-color: ${stringToColour(social)}66">${index === 0 ? `<th rowspan="${Object.keys(types).length - (disabledType[social] || []).length}" style="background-color: ${stringToColour(social)}66">${social}</th>` : ''}<td>${i18n(type)}</td><td><button type="button" class="editWhiteList" data-value="${social}.${type}">${i18n('edit')}</button></td></tr>`).join('');
  10130. }
  10131. whiteListOptionsForm += '</tbody></table></form>';
  10132. if (showType === 'swal') {
  10133. external_Swal_default().fire({
  10134. title: i18n('whiteListOptions'),
  10135. html: whiteListOptionsForm,
  10136. showConfirmButton: false,
  10137. showCloseButton: true
  10138. });
  10139. } else {
  10140. $('body').append(`<h2>${i18n('whiteList')}</h2>${whiteListOptionsForm}`);
  10141. }
  10142. $('.editWhiteList').on('click', function() {
  10143. const value = $(this).attr('data-value');
  10144. if (!value) {
  10145. return;
  10146. }
  10147. const [ social, type ] = value.split('.');
  10148. if (!whiteList?.[social]?.[type]) {
  10149. scripts_echoLog({}).warning(i18n('whiteListNotFound', value));
  10150. return;
  10151. }
  10152. external_Swal_default().fire({
  10153. title: i18n('changeWhiteListOption', value),
  10154. input: 'textarea',
  10155. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10156. <button id="link2id" data-type="${value}" class="swal2-confirm swal2-styled">获取id</button>
  10157. <p style="margin-bottom:0 !important;">在下方填写白名单,每行一个</p>`,
  10158. inputValue: whiteList[social][type].join('\n'),
  10159. showConfirmButton: true,
  10160. confirmButtonText: i18n('save'),
  10161. showCancelButton: true,
  10162. cancelButtonText: i18n('close'),
  10163. showDenyButton: true,
  10164. denyButtonText: i18n('return')
  10165. }).then(({
  10166. isDenied,
  10167. isConfirmed,
  10168. value
  10169. }) => {
  10170. if (isDenied) {
  10171. if (showType === 'swal') {
  10172. whiteListOptions(showType);
  10173. }
  10174. return;
  10175. } else if (isConfirmed) {
  10176. whiteList[social][type] = value.split('\n');
  10177. GM_setValue('whiteList', whiteList);
  10178. external_Swal_default().fire({
  10179. title: i18n('changeWhiteListSuccess'),
  10180. icon: 'success'
  10181. });
  10182. }
  10183. });
  10184. $('#link2id').on('click', async function() {
  10185. const type = $(this).attr('data-type');
  10186. $('#socialLink').val(await link2id(type));
  10187. });
  10188. });
  10189. } catch (error) {
  10190. throwError(error, 'whiteListOptions');
  10191. }
  10192. };
  10193. const whiteList = whiteListOptions;
  10194. const setGistData = async (token, gistId, fileName, content) => {
  10195. try {
  10196. const logStatus = scripts_echoLog({
  10197. text: i18n('settingData')
  10198. });
  10199. const contentData = JSON.stringify({
  10200. files: {
  10201. [fileName]: {
  10202. content: JSON.stringify(content)
  10203. }
  10204. }
  10205. });
  10206. const {
  10207. result,
  10208. statusText,
  10209. status,
  10210. data
  10211. } = await tools_httpRequest({
  10212. url: `https://api.github.com/gists/${gistId}`,
  10213. headers: {
  10214. Accept: 'application/vnd.github.v3+json',
  10215. Authorization: `token ${token}`
  10216. },
  10217. data: contentData,
  10218. responseType: 'json',
  10219. method: 'POST',
  10220. timeout: 3e4
  10221. });
  10222. if (result === 'Success') {
  10223. if (data?.status === 200 && data.response.files?.[fileName]?.content === JSON.stringify(content)) {
  10224. logStatus.success();
  10225. return true;
  10226. }
  10227. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10228. return false;
  10229. }
  10230. logStatus.error(`${result}:${statusText}(${status})`);
  10231. return false;
  10232. } catch (error) {
  10233. throwError(error, 'setGistData');
  10234. return false;
  10235. }
  10236. };
  10237. const getGistData = async (token, gistId, fileName, test = false) => {
  10238. try {
  10239. const logStatus = scripts_echoLog({
  10240. text: i18n('gettingData')
  10241. });
  10242. const {
  10243. result,
  10244. statusText,
  10245. status,
  10246. data
  10247. } = await tools_httpRequest({
  10248. url: `https://api.github.com/gists/${gistId}`,
  10249. headers: {
  10250. Accept: 'application/vnd.github.v3+json',
  10251. Authorization: `token ${token}`
  10252. },
  10253. responseType: 'json',
  10254. method: 'GET',
  10255. timeout: 3e4
  10256. });
  10257. if (result === 'Success') {
  10258. if (data?.status === 200) {
  10259. const content = data.response?.files?.[fileName]?.content;
  10260. let formatedContent;
  10261. if (!content) {
  10262. logStatus.error(`Error:${i18n('noRemoteData')}`);
  10263. return false;
  10264. }
  10265. if (test) {
  10266. logStatus.success();
  10267. return true;
  10268. }
  10269. try {
  10270. formatedContent = JSON.parse(content);
  10271. } catch (error) {
  10272. logStatus.error(`Error:${i18n('errorRemoteDataFormat')}`);
  10273. return false;
  10274. }
  10275. logStatus.success();
  10276. return formatedContent;
  10277. }
  10278. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10279. return false;
  10280. }
  10281. logStatus.error(`${result}:${statusText}(${status})`);
  10282. return false;
  10283. } catch (error) {
  10284. throwError(error, 'getGistData');
  10285. return false;
  10286. }
  10287. };
  10288. const syncOptions = () => {
  10289. try {
  10290. const {
  10291. TOKEN,
  10292. GIST_ID,
  10293. FILE_NAME,
  10294. SYNC_HISTORY
  10295. } = GM_getValue('gistOptions') || {
  10296. TOKEN: '',
  10297. GIST_ID: '',
  10298. FILE_NAME: '',
  10299. SYNC_HISTORY: true
  10300. };
  10301. external_Swal_default().fire({
  10302. title: i18n('gistOptions'),
  10303. html: `<p>Github Token<input id="github-token" class="swal2-input" placeholder="Github Token" value="${TOKEN}"></p>` + `<p>Gist ID<input id="gist-id" class="swal2-input" placeholder="Gist ID" value="${GIST_ID}"></p>` + `<p>${i18n('fileName')}<input id="file-name" class="swal2-input" placeholder="${i18n('fileName')}" value="${FILE_NAME}"></p>` + '<p><label for="sync-history" class="swal2-checkbox-custom" style="display: flex;">' + `<input id="sync-history" type="checkbox"${SYNC_HISTORY ? ' checked="checked"' : ''}/>` + `<span class="swal2-label">${i18n('syncHistory')}</span></label></p>` + `<p><button id="upload-data" type="button" class="swal2-confirm swal2-styled" style="display: inline-block;">
  10304. ${i18n('upload2gist')}</button>` + `<button id="download-data" type="button" class="swal2-confirm swal2-styled" style="display: inline-block;">
  10305. ${i18n('downloadFromGist')}</button></p>`,
  10306. focusConfirm: false,
  10307. showLoaderOnConfirm: true,
  10308. footer: `<a href="https://auto-task-doc.js.org/guide/#%E6%95%B0%E6%8D%AE%E5%90%8C%E6%AD%A5" target="_blank">${i18n('help')}</a>`,
  10309. preConfirm: async () => {
  10310. const token = $('#github-token').val();
  10311. const gistId = $('#gist-id').val();
  10312. const fileName = $('#file-name').val();
  10313. const syncHistory = $('#sync-history').prop('checked');
  10314. GM_setValue('gistOptions', {
  10315. TOKEN: token,
  10316. GIST_ID: gistId,
  10317. FILE_NAME: fileName,
  10318. SYNC_HISTORY: syncHistory
  10319. });
  10320. return await getGistData(token, gistId, fileName, true);
  10321. },
  10322. allowOutsideClick: () => !external_Swal_default().isLoading(),
  10323. confirmButtonText: i18n('saveAndTest'),
  10324. showCancelButton: true,
  10325. cancelButtonText: i18n('close')
  10326. }).then(({
  10327. value
  10328. }) => {
  10329. if (value) {
  10330. external_Swal_default().fire({
  10331. icon: 'success',
  10332. title: i18n('testSuccess')
  10333. }).then(syncOptions);
  10334. } else if (value !== undefined) {
  10335. external_Swal_default().fire({
  10336. icon: 'error',
  10337. title: i18n('testFailed')
  10338. }).then(syncOptions);
  10339. }
  10340. });
  10341. $('#upload-data').on('click', async () => {
  10342. const {
  10343. TOKEN,
  10344. GIST_ID,
  10345. FILE_NAME
  10346. } = GM_getValue('gistOptions') || {};
  10347. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10348. return external_Swal_default().fire({
  10349. icon: 'error',
  10350. title: i18n('saveAndTestNotice')
  10351. }).then(syncOptions);
  10352. }
  10353. external_Swal_default().fire({
  10354. icon: 'info',
  10355. title: i18n('processingData')
  10356. });
  10357. const data = {};
  10358. const names = GM_listValues();
  10359. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10360. for (const name of names) {
  10361. if (name === 'gistOptions' || /^[\w]+?Auth$/.test(name)) {
  10362. continue;
  10363. }
  10364. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10365. continue;
  10366. }
  10367. data[name] = GM_getValue(name);
  10368. }
  10369. external_Swal_default().update({
  10370. icon: 'info',
  10371. title: i18n('updatingData')
  10372. });
  10373. if (await setGistData(TOKEN, GIST_ID, FILE_NAME, data)) {
  10374. external_Swal_default().fire({
  10375. icon: 'success',
  10376. title: i18n('syncDataSuccess')
  10377. });
  10378. } else {
  10379. external_Swal_default().fire({
  10380. icon: 'error',
  10381. title: i18n('syncDataFailed')
  10382. });
  10383. }
  10384. });
  10385. $('#download-data').on('click', async () => {
  10386. const {
  10387. TOKEN,
  10388. GIST_ID,
  10389. FILE_NAME
  10390. } = GM_getValue('gistOptions') || {};
  10391. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10392. return external_Swal_default().fire({
  10393. icon: 'error',
  10394. title: i18n('saveAndTestNotice')
  10395. }).then(syncOptions);
  10396. }
  10397. external_Swal_default().fire({
  10398. icon: 'info',
  10399. title: i18n('downloadingData')
  10400. });
  10401. const data = await getGistData(TOKEN, GIST_ID, FILE_NAME);
  10402. if (!data) {
  10403. return external_Swal_default().fire({
  10404. icon: 'error',
  10405. title: i18n('checkedNoData')
  10406. }).then(syncOptions);
  10407. }
  10408. external_Swal_default().update({
  10409. icon: 'info',
  10410. title: i18n('savingData')
  10411. });
  10412. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10413. for (const [ name, value ] of Object.entries(data)) {
  10414. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10415. continue;
  10416. }
  10417. GM_setValue(name, value);
  10418. }
  10419. external_Swal_default().fire({
  10420. icon: 'success',
  10421. title: i18n('syncDataSuccess')
  10422. });
  10423. });
  10424. } catch (error) {
  10425. throwError(error, 'syncOptions');
  10426. }
  10427. };
  10428. const dataSync = syncOptions;
  10429. class Setting {
  10430. name = 'Setting';
  10431. buttons = [ 'saveGlobalOptions', 'syncData', 'tasksHistory' ];
  10432. syncData = dataSync;
  10433. tasksHistory() {
  10434. GM_openInTab('https://auto-task-v4.hclonely.com/history.html', {
  10435. active: true
  10436. });
  10437. }
  10438. static test() {
  10439. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/setting.html';
  10440. }
  10441. before() {
  10442. try {
  10443. $('body').html('').addClass('auto-task-options');
  10444. } catch (error) {
  10445. throwError(error, 'Setting.before');
  10446. }
  10447. }
  10448. after() {
  10449. try {
  10450. this.#environment();
  10451. changeGlobalOptions('page');
  10452. whiteList('page');
  10453. $('input[name="other.twitterVerifyId"]').after(`<button id="getTwitterUserId" type="button">${i18n('getTwitterUserId')}</button>`);
  10454. $('#getTwitterUserId').on('click', () => {
  10455. this.#getId('twitterUser');
  10456. });
  10457. $('input[name="other.youtubeVerifyChannel"]').after(`<button id="getYoutubeChannelId" type="button">${i18n('getYoutubeChannelId')}</button>`);
  10458. $('#getYoutubeChannelId').on('click', () => {
  10459. this.#getId('youtubeChannel');
  10460. });
  10461. $('input[name^="position"]').on('input', function() {
  10462. const type = $(this).attr('name').replace('position.', '');
  10463. const xLabel = 'rightleft';
  10464. const yLabel = 'topbottpm';
  10465. switch (type) {
  10466. case 'buttonSideX':
  10467. case 'buttonSideY':
  10468. case 'buttonDistance':
  10469. {
  10470. const distance = $('input[name="position.buttonDistance"]').val();
  10471. const sideX = $('input[name="position.buttonSideX"]').val();
  10472. const sideY = $('input[name="position.buttonSideY"]').val();
  10473. if (![ 'right', 'left' ].includes(sideX)) {
  10474. break;
  10475. }
  10476. if (![ 'top', 'bottom' ].includes(sideY)) {
  10477. break;
  10478. }
  10479. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10480. break;
  10481. }
  10482. const distanceArr = distance.split(',');
  10483. $('#auto-task-buttons').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10484. break;
  10485. }
  10486.  
  10487. case 'showButtonSideX':
  10488. case 'showButtonSideY':
  10489. case 'showButtonDistance':
  10490. {
  10491. const distance = $('input[name="position.showButtonDistance"]').val();
  10492. const sideX = $('input[name="position.showButtonSideX"]').val();
  10493. const sideY = $('input[name="position.showButtonSideY"]').val();
  10494. if (![ 'right', 'left' ].includes(sideX)) {
  10495. break;
  10496. }
  10497. if (![ 'top', 'bottom' ].includes(sideY)) {
  10498. break;
  10499. }
  10500. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10501. break;
  10502. }
  10503. const distanceArr = distance.split(',');
  10504. $('div.show-button-div').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10505. break;
  10506. }
  10507.  
  10508. case 'logSideX':
  10509. case 'logSideY':
  10510. case 'logDistance':
  10511. {
  10512. const distance = $('input[name="position.logDistance"]').val();
  10513. const sideX = $('input[name="position.logSideX"]').val();
  10514. const sideY = $('input[name="position.logSideY"]').val();
  10515. if (![ 'right', 'left' ].includes(sideX)) {
  10516. break;
  10517. }
  10518. if (![ 'top', 'bottom' ].includes(sideY)) {
  10519. break;
  10520. }
  10521. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10522. break;
  10523. }
  10524. const distanceArr = distance.split(',');
  10525. $('#auto-task-info').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10526. break;
  10527. }
  10528.  
  10529. default:
  10530. break;
  10531. }
  10532. });
  10533. $('input[name^="hotKey"]').attr('readonly', 'readonly').off('keydown').on('keydown', function(event) {
  10534. let functionKey = '';
  10535. if (event.altKey) {
  10536. functionKey += 'alt + ';
  10537. } else if (event.ctrlKey) {
  10538. functionKey += 'ctrl + ';
  10539. } else if (event.shiftKey) {
  10540. functionKey += 'shift + ';
  10541. }
  10542. $(this).val(functionKey + (event.key.length === 1 ? event.key.toLowerCase() : ''));
  10543. });
  10544. } catch (error) {
  10545. throwError(error, 'Setting.after');
  10546. }
  10547. }
  10548. saveGlobalOptions() {
  10549. try {
  10550. saveData();
  10551. } catch (error) {
  10552. throwError(error, 'Setting.saveGlobalOptions');
  10553. }
  10554. }
  10555. #getId(social) {
  10556. try {
  10557. external_Swal_default().fire({
  10558. title: i18n('getId', i18n(social)),
  10559. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10560. <button id="link2id" data-type="${social}" class="swal2-confirm swal2-styled">获取id</button>`,
  10561. showCancelButton: true,
  10562. cancelButtonText: i18n('close'),
  10563. showConfirmButton: false
  10564. });
  10565. $('#link2id').on('click', async function() {
  10566. const link = $('#socialLink').val();
  10567. if (!link) {
  10568. return;
  10569. }
  10570. const type = $(this).attr('data-type');
  10571. if (type === 'twitterUser') {
  10572. const name = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || link;
  10573. $('#socialLink').val(await new social_Twitter().userName2id(name) || '');
  10574. } else if (type === 'youtubeChannel') {
  10575. const name = /^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www.youtube.com\/.*/.test(link) ? link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1] : link;
  10576. $('#socialLink').val((await getInfo(name, 'channel'))?.params?.channelId || '');
  10577. }
  10578. });
  10579. } catch (error) {
  10580. throwError(error, 'Setting.getId');
  10581. }
  10582. }
  10583. #environment() {
  10584. try {
  10585. const userAgent = (0, javascript_utils_umd_min.ua)();
  10586. const environmentForm = `<form id="environmentForm" class="auto-task-form">
  10587. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('name')}</td><td>${i18n('version')}</td></tr></thead><tbody>
  10588. <tr><td>${i18n('os')}</td><td>${userAgent.os}</td><td>${userAgent.osVersion}</td></tr>
  10589. <tr><td>${i18n('browser')}</td><td>${userAgent.browserZH}</td><td>${userAgent.browserVersion}</td></tr>
  10590. <tr><td>${i18n('scriptManager')}</td><td>${GM_info.scriptHandler}</td><td>${GM_info.version}</td></tr>
  10591. <tr><td>${i18n('script')}</td><td>${GM_info.script.name}</td><td>${GM_info.script.version}</td></tr>
  10592. </tbody></table></form>`;
  10593. $('body').append(`<h2>${i18n('environment')}</h2>${environmentForm}`);
  10594. } catch (error) {
  10595. throwError(error, 'Setting.environment');
  10596. }
  10597. }
  10598. }
  10599. const website_Setting = Setting;
  10600. class History extends website_Keylol {
  10601. name = 'History';
  10602. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect', 'clearHistory' ];
  10603. static test() {
  10604. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/history.html';
  10605. }
  10606. before() {
  10607. try {
  10608. $('body').html('<div class="container"></div>').addClass('auto-task-history');
  10609. const data = GM_listValues() || [];
  10610. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  10611. for (const item of tasksHistory) {
  10612. this.#addItem(item);
  10613. }
  10614. } catch (error) {
  10615. throwError(error, 'History.before');
  10616. }
  10617. }
  10618. clearHistory() {
  10619. try {
  10620. const data = GM_listValues() || [];
  10621. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  10622. for (const item of tasksHistory) {
  10623. GM_deleteValue(item);
  10624. }
  10625. external_Swal_default().fire({
  10626. title: i18n('clearHistoryFinished'),
  10627. icon: 'success'
  10628. });
  10629. } catch (error) {
  10630. throwError(error, 'History.clearHistory');
  10631. }
  10632. }
  10633. #addItem(item) {
  10634. try {
  10635. const tasksData = GM_getValue(item);
  10636. if (!tasksData?.tasks) {
  10637. return;
  10638. }
  10639. let html = '';
  10640. let title = '';
  10641. let link = '';
  10642. const [ website, id ] = item.split('-');
  10643. switch (website) {
  10644. case 'fawTasks':
  10645. title = `Freeanywhere[${id}]`;
  10646. link = `https://freeanywhere.net/#/giveaway/${id}`;
  10647. break;
  10648.  
  10649. case 'gasTasks':
  10650. title = `Giveawaysu[${id}]`;
  10651. link = `https://giveaway.su/giveaway/view/${id}`;
  10652. break;
  10653.  
  10654. case 'gcTasks':
  10655. title = `GiveeClub[${id}]`;
  10656. link = `https://givee.club/event/${id}`;
  10657. break;
  10658.  
  10659. case 'gkTasks':
  10660. title = `Givekey[${id}]`;
  10661. link = `https://givekey.ru/giveaway/${id}`;
  10662. break;
  10663.  
  10664. case 'gleamTasks':
  10665. title = `Gleam[${id}]`;
  10666. link = `https://gleam.io${id}`;
  10667. break;
  10668.  
  10669. case 'khTasks':
  10670. title = `keyhub[${id}]`;
  10671. link = `https://key-hub.eu/giveaway/${id}`;
  10672. break;
  10673.  
  10674. case 'prysTasks':
  10675. title = `Prys[${id}]`;
  10676. link = `https://prys.revadike.com/giveaway/?id=${id}`;
  10677. break;
  10678.  
  10679. default:
  10680. return;
  10681. }
  10682. for (const [ social, types ] of Object.entries(tasksData.tasks)) {
  10683. for (const [ type, tasks ] of Object.entries(types)) {
  10684. for (const task of tasks) {
  10685. html += `<li><font class="auto-task-capitalize">${social}.${i18n(type.replace('Link', ''))}: </font><a href="${task}" target="_blank">${task.length > 55 ? `${task.slice(0, 55)}...` : task}</a></li>`;
  10686. }
  10687. }
  10688. }
  10689. $('.container').append(`<div class="card" data-name="${item}"><div class="title"><a href="${link}" target="_blank">${title}</a><span class="delete-task" data-name="${item}" title="${i18n('deleteTask')}"><svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2734" width="32" height="32"><path d="M607.897867 768.043004c-17.717453 0-31.994625-14.277171-31.994625-31.994625L575.903242 383.935495c0-17.717453 14.277171-31.994625 31.994625-31.994625s31.994625 14.277171 31.994625 31.994625l0 351.94087C639.892491 753.593818 625.61532 768.043004 607.897867 768.043004z" p-id="2735" fill="#d81e06"></path><path d="M415.930119 768.043004c-17.717453 0-31.994625-14.277171-31.994625-31.994625L383.935495 383.935495c0-17.717453 14.277171-31.994625 31.994625-31.994625 17.717453 0 31.994625 14.277171 31.994625 31.994625l0 351.94087C447.924744 753.593818 433.647573 768.043004 415.930119 768.043004z" p-id="2736" fill="#d81e06"></path><path d="M928.016126 223.962372l-159.973123 0L768.043004 159.973123c0-52.980346-42.659499-95.983874-95.295817-95.983874L351.94087 63.989249c-52.980346 0-95.983874 43.003528-95.983874 95.983874l0 63.989249-159.973123 0c-17.717453 0-31.994625 14.277171-31.994625 31.994625s14.277171 31.994625 31.994625 31.994625l832.032253 0c17.717453 0 31.994625-14.277171 31.994625-31.994625S945.73358 223.962372 928.016126 223.962372zM319.946246 159.973123c0-17.545439 14.449185-31.994625 31.994625-31.994625l320.806316 0c17.545439 0 31.306568 14.105157 31.306568 31.994625l0 63.989249L319.946246 223.962372 319.946246 159.973123 319.946246 159.973123z" p-id="2737" fill="#d81e06"></path><path d="M736.048379 960.010751 288.123635 960.010751c-52.980346 0-95.983874-43.003528-95.983874-95.983874L192.139761 383.591466c0-17.717453 14.277171-31.994625 31.994625-31.994625s31.994625 14.277171 31.994625 31.994625l0 480.435411c0 17.717453 14.449185 31.994625 31.994625 31.994625l448.096758 0c17.717453 0 31.994625-14.277171 31.994625-31.994625L768.215018 384.795565c0-17.717453 14.277171-31.994625 31.994625-31.994625s31.994625 14.277171 31.994625 31.994625l0 479.231312C832.032253 916.835209 789.028725 960.010751 736.048379 960.010751z" p-id="2738" fill="#d81e06"></path></svg></span></div><ul>${html}</ul><span class="time">${i18n('lastChangeTime')}: ${external_dayjs_namespaceObject(tasksData.time).format('YYYY-MM-DD HH:mm:ss')}</span></div>`);
  10690. $('span.delete-task').on('click', function() {
  10691. const itemName = $(this).attr('data-name');
  10692. if (itemName) {
  10693. GM_deleteValue(itemName);
  10694. $(`div.card[data-name="${itemName}"]`).remove();
  10695. external_Swal_default().fire({
  10696. title: i18n('clearTaskFinished'),
  10697. text: itemName,
  10698. icon: 'success'
  10699. });
  10700. } else {
  10701. external_Swal_default().fire({
  10702. title: i18n('clearTaskFailed'),
  10703. icon: 'error'
  10704. });
  10705. }
  10706. });
  10707. } catch (error) {
  10708. throwError(error, 'History.addItem');
  10709. }
  10710. }
  10711. }
  10712. const website_History = History;
  10713. const GiveawayHopper_defaultTasksTemplate = {
  10714. steam: {
  10715. groupLinks: [],
  10716. wishlistLinks: [],
  10717. followLinks: [],
  10718. curatorLinks: [],
  10719. curatorLikeLinks: []
  10720. },
  10721. twitter: {
  10722. userLinks: [],
  10723. retweetLinks: []
  10724. },
  10725. twitch: {
  10726. channelLinks: []
  10727. },
  10728. discord: {
  10729. serverLinks: []
  10730. },
  10731. youtube: {
  10732. channelLinks: []
  10733. },
  10734. extra: {
  10735. giveawayHopper: []
  10736. }
  10737. };
  10738. const GiveawayHopper_defaultTasks = JSON.stringify(GiveawayHopper_defaultTasksTemplate);
  10739. class GiveawayHopper extends website_Website {
  10740. name = 'GiveawayHopper';
  10741. undoneTasks = JSON.parse(GiveawayHopper_defaultTasks);
  10742. socialTasks = JSON.parse(GiveawayHopper_defaultTasks);
  10743. tasks = [];
  10744. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  10745. static test() {
  10746. return window.location.host === 'giveawayhopper.com';
  10747. }
  10748. async after() {
  10749. try {
  10750. if (!this.#checkLogin()) {
  10751. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  10752. }
  10753. this.#getGiveawayId();
  10754. } catch (error) {
  10755. throwError(error, 'GiveawayHopper.after');
  10756. }
  10757. }
  10758. async init() {
  10759. try {
  10760. const logStatus = scripts_echoLog({
  10761. text: i18n('initing')
  10762. });
  10763. if (!await this.#checkLeftKey()) {
  10764. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  10765. }
  10766. this.initialized = true;
  10767. logStatus.success();
  10768. return true;
  10769. } catch (error) {
  10770. throwError(error, 'GiveawayHopper.init');
  10771. return false;
  10772. }
  10773. }
  10774. async classifyTask(action) {
  10775. try {
  10776. if (!this.giveawayId) {
  10777. await this.#getGiveawayId();
  10778. }
  10779. const logStatus = scripts_echoLog({
  10780. text: i18n('getTasksInfo')
  10781. });
  10782. if (action === 'undo') {
  10783. this.socialTasks = GM_getValue(`giveawayHopperTasks-${this.giveawayId}`)?.tasks || JSON.parse(GiveawayHopper_defaultTasks);
  10784. }
  10785. const {
  10786. result,
  10787. statusText,
  10788. status,
  10789. data
  10790. } = await tools_httpRequest({
  10791. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/with-auth`,
  10792. method: 'GET',
  10793. responseType: 'json',
  10794. fetch: true,
  10795. headers: {
  10796. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10797. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10798. }
  10799. });
  10800. if (result === 'Success') {
  10801. if (data?.status === 200 && data?.response?.tasks) {
  10802. this.tasks = data.response.tasks;
  10803. for (const task of data.response.tasks) {
  10804. if (task.isDone) {
  10805. continue;
  10806. }
  10807. await tools_httpRequest({
  10808. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/visited`,
  10809. method: 'GET',
  10810. responseType: 'json',
  10811. fetch: true,
  10812. headers: {
  10813. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10814. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10815. }
  10816. });
  10817. if (task.category === 'Steam' && task.type === 'JoinGroup') {
  10818. const steamGroupLink = await getRedirectLink(`https://steamcommunity.com/gid/${task.group_id}`);
  10819. if (!steamGroupLink) {
  10820. continue;
  10821. }
  10822. if (action === 'undo') {
  10823. this.socialTasks.steam.groupLinks.push(steamGroupLink);
  10824. }
  10825. if (action === 'do') {
  10826. this.undoneTasks.steam.groupLinks.push(steamGroupLink);
  10827. }
  10828. continue;
  10829. }
  10830. if (task.category === 'Discord' && task.type === 'JoinServer') {
  10831. if (action === 'undo') {
  10832. this.socialTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  10833. }
  10834. if (action === 'do') {
  10835. this.undoneTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  10836. }
  10837. continue;
  10838. }
  10839. if ([ 'TikTok', 'YouTube', 'General' ].includes(task.category)) {
  10840. continue;
  10841. }
  10842. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${task.category}-${task.type}`);
  10843. }
  10844. logStatus.success();
  10845. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  10846. this.socialTasks = this.uniqueTasks(this.socialTasks);
  10847. if (window.DEBUG) {
  10848. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  10849. }
  10850. GM_setValue(`giveawayHopperTasks-${this.giveawayId}`, {
  10851. tasks: this.socialTasks,
  10852. time: new Date().getTime()
  10853. });
  10854. return true;
  10855. }
  10856. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10857. return false;
  10858. }
  10859. logStatus.error(`${result}:${statusText}(${status})`);
  10860. return false;
  10861. } catch (error) {
  10862. throwError(error, 'GiveawayHopper.classifyTask');
  10863. return false;
  10864. }
  10865. }
  10866. async verifyTask() {
  10867. try {
  10868. for (const task of this.tasks) {
  10869. if (task.isDone) {
  10870. continue;
  10871. }
  10872. const logStatus = scripts_echoLog({
  10873. text: `${i18n('verifyingTask')}[${task.displayName?.replace(':target', task.targetName) || task.name}]...`
  10874. });
  10875. if (!task.link) {
  10876. if (task.category === 'YouTube' && task.type === 'FollowAccount') {
  10877. task.link = `https://www.youtube.com/@${task.targetName}`;
  10878. } else if (task.category === 'TikTok' && task.type === 'FollowAccount') {
  10879. task.link = `https://www.tiktok.com/@${task.targetName}`;
  10880. } else if (task.category === 'Steam' && task.type === 'JoinGroup') {
  10881. task.link = '';
  10882. } else if (task.category === 'Discord' && task.type === 'JoinServer') {
  10883. task.link = '';
  10884. }
  10885. }
  10886. if (task.link) {
  10887. await tools_httpRequest({
  10888. url: `https://giveawayhopper.com/fw?url=${encodeURIComponent(task.link)}&src=campaign&src_id=${this.giveawayId}&ref=task&ref_id=${task.id}&token=${window.sessionStorage.gw_auth}`,
  10889. method: 'GET',
  10890. fetch: true,
  10891. headers: {
  10892. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10893. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10894. }
  10895. });
  10896. }
  10897. await delay(1e3);
  10898. const postData = {
  10899. taskcategory: task.category,
  10900. taskname: task.type
  10901. };
  10902. if ([ 'YouTube', 'TikTok' ].includes(task.category)) {
  10903. postData.username = '1';
  10904. }
  10905. const {
  10906. result,
  10907. statusText,
  10908. status,
  10909. data
  10910. } = await tools_httpRequest({
  10911. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/complete`,
  10912. method: 'POST',
  10913. fetch: true,
  10914. headers: {
  10915. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10916. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1]),
  10917. 'content-type': 'application/json'
  10918. },
  10919. dataType: 'json',
  10920. data: JSON.stringify(postData)
  10921. });
  10922. if (result === 'Success') {
  10923. if (data?.status === 200 && data?.response?.completed) {
  10924. logStatus.success();
  10925. continue;
  10926. }
  10927. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10928. continue;
  10929. }
  10930. logStatus.error(`${result}:${statusText}(${status})`);
  10931. continue;
  10932. }
  10933. } catch (error) {
  10934. throwError(error, 'GiveawayHopper.verifyTask');
  10935. return false;
  10936. }
  10937. }
  10938. #getGiveawayId() {
  10939. try {
  10940. const giveawayId = window.location.pathname.split('/').at(-1);
  10941. if (giveawayId) {
  10942. this.giveawayId = giveawayId;
  10943. return true;
  10944. }
  10945. scripts_echoLog({
  10946. text: i18n('getFailed', 'GiveawayId')
  10947. });
  10948. return false;
  10949. } catch (error) {
  10950. throwError(error, 'GiveawayHopper.getGiveawayId');
  10951. return false;
  10952. }
  10953. }
  10954. #checkLogin() {
  10955. try {
  10956. if (!globalOptions.other.checkLogin) {
  10957. return true;
  10958. }
  10959. if ($('div.widget-connections-edit:contains("Log in")').length > 0) {
  10960. $('div.widget-connections-edit:contains("Log in") a')[0].click();
  10961. }
  10962. return true;
  10963. } catch (error) {
  10964. throwError(error, 'GiveawayHopper.checkLogin');
  10965. return false;
  10966. }
  10967. }
  10968. async #checkLeftKey() {
  10969. try {
  10970. if (!globalOptions.other.checkLeftKey) {
  10971. return true;
  10972. }
  10973. if ($('p.widget-single-prize span').length > 0 && parseInt($('p.widget-single-prize span').text()?.match(/\d+/)?.[0] || '0', 10) > 0) {
  10974. return true;
  10975. }
  10976. await external_Swal_default().fire({
  10977. icon: 'warning',
  10978. title: i18n('notice'),
  10979. text: i18n('noKeysLeft'),
  10980. confirmButtonText: i18n('confirm'),
  10981. cancelButtonText: i18n('cancel'),
  10982. showCancelButton: true
  10983. }).then(({
  10984. value
  10985. }) => {
  10986. if (value) {
  10987. window.close();
  10988. }
  10989. });
  10990. return true;
  10991. } catch (error) {
  10992. throwError(error, 'GiveawayHopper.checkLeftKey');
  10993. return false;
  10994. }
  10995. }
  10996. }
  10997. const website_GiveawayHopper = GiveawayHopper;
  10998. const Websites = [ Freeanywhere, GiveawaySu, website_Indiedb, website_Keyhub, website_Givekey, website_GiveeClub, website_OpiumPulses, website_Keylol, website_Opquests, website_Gleam, website_SweepWidget, website_Setting, website_History, website_GiveawayHopper ];
  10999. const websiteOptions = function(website, options) {
  11000. try {
  11001. let websiteOptionsForm = `<form id="websiteOptionsForm" class="auto-task-form">
  11002. <table class="auto-task-table"><thead><tr><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  11003. for (const [ option, value ] of Object.entries(options)) {
  11004. websiteOptionsForm += `<tr><td>${option}</td><td><input class="editOption" type="text" name="${option}" value="${value}"/></td></tr>`;
  11005. }
  11006. websiteOptionsForm += '</tbody></table></form>';
  11007. external_Swal_default().fire({
  11008. title: i18n('websiteOptions'),
  11009. html: websiteOptionsForm,
  11010. showConfirmButton: true,
  11011. confirmButtonText: i18n('save'),
  11012. showCancelButton: true,
  11013. cancelButtonText: i18n('close')
  11014. }).then(({
  11015. isConfirmed
  11016. }) => {
  11017. if (isConfirmed) {
  11018. $('#websiteOptionsForm').serializeArray().map(value => {
  11019. options[value.name] = value.value;
  11020. return value;
  11021. });
  11022. GM_setValue(`${website}Options`, options);
  11023. external_Swal_default().fire({
  11024. title: i18n('changeWebsiteOptionsSuccess'),
  11025. icon: 'success'
  11026. });
  11027. }
  11028. });
  11029. } catch (error) {
  11030. throwError(error, 'websiteOptions');
  11031. }
  11032. };
  11033. const options = websiteOptions;
  11034. const external_keyboardJS_namespaceObject = keyboardJS;
  11035. var external_keyboardJS_default = __webpack_require__.n(external_keyboardJS_namespaceObject);
  11036. const checkUpdate = async (updateLink, auto) => {
  11037. try {
  11038. const checkUrl = `${updateLink}package.json?time=${new Date().getTime()}`;
  11039. const {
  11040. result,
  11041. statusText,
  11042. status,
  11043. data
  11044. } = await tools_httpRequest({
  11045. url: checkUrl,
  11046. responseType: 'json',
  11047. method: 'GET',
  11048. timeout: 3e4
  11049. });
  11050. if (result === 'Success') {
  11051. if (data?.response?.version) {
  11052. return data.response;
  11053. }
  11054. if (!auto) {
  11055. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${data?.statusText}(${data?.status})]`);
  11056. }
  11057. return false;
  11058. }
  11059. if (!auto) {
  11060. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${result}:${statusText}(${status})]`);
  11061. }
  11062. return false;
  11063. } catch (error) {
  11064. throwError(error, 'checkUpdate');
  11065. return false;
  11066. }
  11067. };
  11068. const hasNewVersion = (currentVersion, remoteVersion) => {
  11069. try {
  11070. const [ currentRealVersion ] = currentVersion.split('-');
  11071. const [ remoteRealVersion, isPreview ] = remoteVersion.split('-');
  11072. if (isPreview && !globalOptions.other.receivePreview) {
  11073. return false;
  11074. }
  11075. const [ currentVersion1, currentVersion2, currentVersion3 ] = currentRealVersion.split('.').map(value => parseInt(value, 10));
  11076. const [ remoteVersion1, remoteVersion2, remoteVersion3 ] = remoteRealVersion.split('.').map(value => parseInt(value, 10));
  11077. if (remoteVersion1 > currentVersion1) {
  11078. return true;
  11079. }
  11080. if (remoteVersion1 < currentVersion1) {
  11081. return false;
  11082. }
  11083. if (remoteVersion2 > currentVersion2) {
  11084. return true;
  11085. }
  11086. if (remoteVersion2 < currentVersion2) {
  11087. return false;
  11088. }
  11089. if (remoteVersion3 > currentVersion3) {
  11090. return true;
  11091. }
  11092. return false;
  11093. } catch (error) {
  11094. throwError(error, 'compareVersion');
  11095. return false;
  11096. }
  11097. };
  11098. const updateChecker = async () => {
  11099. try {
  11100. const currentVersion = GM_info.script.version;
  11101. const updateSource = globalOptions.other.autoUpdateSource.toLowerCase();
  11102. const updateLinks = {
  11103. github: 'https://github.com/HCLonely/auto-task-new/raw/main/',
  11104. jsdelivr: 'https://cdn.jsdelivr.net/gh/HCLonely/auto-task-v4@main/',
  11105. standby: 'https://auto-task-v4.hclonely.com/'
  11106. };
  11107. let version;
  11108. let updateLink = '';
  11109. let packageData;
  11110. if ([ 'github', 'jsdelivr', 'standby' ].includes(updateSource)) {
  11111. updateLink = updateLinks[updateSource];
  11112. packageData = await checkUpdate(updateLink, false);
  11113. } else {
  11114. updateLink = updateLinks.github;
  11115. packageData = await checkUpdate(updateLink, true);
  11116. if (!packageData) {
  11117. updateLink = updateLinks.jsdelivr;
  11118. packageData = await checkUpdate(updateLink, true);
  11119. if (!packageData) {
  11120. updateLink = updateLinks.standby;
  11121. packageData = await checkUpdate(updateLink, true);
  11122. }
  11123. }
  11124. }
  11125. if (packageData) {
  11126. version = packageData.version || currentVersion;
  11127. } else {
  11128. version = currentVersion;
  11129. scripts_echoLog({}).error(i18n('checkUpdateFailed'));
  11130. }
  11131. if (packageData && hasNewVersion(currentVersion, version)) {
  11132. scripts_echoLog({
  11133. html: `<li><font>${i18n('newVersionNotice', version, `${updateLink}dist/${GM_info.script.name}.user.js`)}</font></li>`
  11134. });
  11135. scripts_echoLog({
  11136. html: `<li>${i18n('updateText', version)}</li><ol class="update-text">${packageData.change?.map(change => `<li>${change}</li>`).join('')}<li>${i18n('updateHistory')}</li></ol>`
  11137. });
  11138. }
  11139. } catch (error) {
  11140. throwError(error, 'updateChecker');
  11141. }
  11142. };
  11143. const scripts_updateChecker = updateChecker;
  11144. window.STYLE = GM_addStyle(auto_task.A + GM_getResourceText('style'));
  11145. window.DEBUG = !!globalOptions.other?.debug;
  11146. window.TRACE = !!globalOptions.other?.debug && typeof console.trace === 'function';
  11147. const loadScript = async () => {
  11148. if (window.name === 'ATv4_twitchAuth' && window.location.hostname === 'www.twitch.tv') {
  11149. const authToken = external_Cookies_default().get('auth-token');
  11150. const isLogin = !!external_Cookies_default().get('login');
  11151. if (isLogin) {
  11152. GM_setValue('twitchAuth', {
  11153. authToken: authToken,
  11154. clientVersion: __twilightBuildID,
  11155. clientId: commonOptions?.headers?.['Client-ID'],
  11156. deviceId: commonOptions?.headers?.['Device-ID'],
  11157. clientSessionId: window.localStorage.local_storage_app_session_id.replace(/"/g, '')
  11158. });
  11159. window.close();
  11160. external_Swal_default().fire('', i18n('closePageNotice'));
  11161. } else {
  11162. external_Swal_default().fire('', i18n('needLogin'));
  11163. }
  11164. return;
  11165. }
  11166. if (window.name === 'ATv4_redditAuth' && window.location.hostname === 'www.reddit.com') {
  11167. const betaButton = $('#redesign-beta-optin-btn');
  11168. if (betaButton.length > 0) {
  11169. return betaButton[0].click();
  11170. }
  11171. window.close();
  11172. external_Swal_default().fire('', i18n('closePageNotice'));
  11173. return;
  11174. }
  11175. let website;
  11176. for (const Website of Websites) {
  11177. if (Website.test()) {
  11178. website = new Website();
  11179. break;
  11180. }
  11181. }
  11182. if (!website) {
  11183. console.log('%c%s', 'color:#ff0000', 'Auto-Task[Warning]: 脚本停止加载,当前网站不支持!');
  11184. return;
  11185. }
  11186. if (website?.before) {
  11187. await website?.before();
  11188. }
  11189. $('body').append(`
  11190. <div id="auto-task-info"
  11191. style="display:${globalOptions.other.defaultShowLog ? 'block' : 'none'};
  11192. ${globalOptions.position.logSideX}:${globalOptions.position.logDistance.split(',')[0]}px;
  11193. ${globalOptions.position.logSideY}:${globalOptions.position.logDistance.split(',')[1]}px;">
  11194. </div>
  11195. <div id="auto-task-buttons"
  11196. style="display:${globalOptions.other.defaultShowButton ? 'block' : 'none'};
  11197. ${globalOptions.position.buttonSideX}:${globalOptions.position.buttonDistance.split(',')[0]}px;
  11198. ${globalOptions.position.buttonSideY}:${globalOptions.position.buttonDistance.split(',')[1]}px;">
  11199. </div>
  11200. <div class="show-button-div"
  11201. style="display:${globalOptions.other.defaultShowButton ? 'none' : 'block'};
  11202. ${globalOptions.position.showButtonSideX}:${globalOptions.position.showButtonDistance.split(',')[0]}px;
  11203. ${globalOptions.position.showButtonSideY}:${globalOptions.position.showButtonDistance.split(',')[1]}px;">
  11204. <a class="auto-task-website-btn"
  11205. href="javascript:void(0);"
  11206. target="_self"
  11207. title="${i18n('showButton')}"> </a>
  11208. </div>
  11209. `);
  11210. $('div.show-button-div').on('click', () => {
  11211. $('#auto-task-buttons').show();
  11212. $('div.show-button-div').hide();
  11213. });
  11214. const toggleLog = () => {
  11215. const $this = $('#toggle-log');
  11216. const status = $this.attr('data-status');
  11217. if (status === 'show') {
  11218. $('#auto-task-info').hide();
  11219. $this.attr('data-status', 'hide').text(i18n('showLog'));
  11220. } else {
  11221. $('#auto-task-info').show();
  11222. $this.attr('data-status', 'show').text(i18n('hideLog'));
  11223. }
  11224. };
  11225. external_keyboardJS_default().bind(globalOptions.hotKey.doTaskKey, () => {
  11226. if (website.doTask) {
  11227. website.doTask();
  11228. }
  11229. });
  11230. external_keyboardJS_default().bind(globalOptions.hotKey.undoTaskKey, () => {
  11231. if (website.undoTask) {
  11232. website.undoTask();
  11233. }
  11234. });
  11235. external_keyboardJS_default().bind(globalOptions.hotKey.toggleLogKey, toggleLog);
  11236. if (website?.after) {
  11237. await website?.after();
  11238. }
  11239. if (website?.buttons && $('#auto-task-buttons').children().length === 0) {
  11240. $('#auto-task-buttons').addClass(`${website.name}-buttons`);
  11241. for (const button of website.buttons) {
  11242. if (website[button]) {
  11243. const btnElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">${i18n(button)}</a></p>`);
  11244. btnElement.find('a.auto-task-website-btn').on('click', () => {
  11245. website[button]();
  11246. });
  11247. $('#auto-task-buttons').append(btnElement);
  11248. }
  11249. }
  11250. }
  11251. const hideButtonElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">
  11252. ${i18n('hideButton')}</a></p>`);
  11253. hideButtonElement.find('a.auto-task-website-btn').on('click', () => {
  11254. $('#auto-task-buttons').hide();
  11255. $('div.show-button-div').show();
  11256. });
  11257. const toggleLogElement = $(`<p><a id="toggle-log" class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self" data-status="${globalOptions.other.defaultShowLog ? 'show' : 'hide'}">
  11258. ${globalOptions.other.defaultShowLog ? i18n('hideLog') : i18n('showLog')}</a></p>`);
  11259. toggleLogElement.find('a.auto-task-website-btn').on('click', toggleLog);
  11260. $('#auto-task-buttons').append(hideButtonElement).append(toggleLogElement);
  11261. if (website?.options) {
  11262. GM_registerMenuCommand(i18n('changeWebsiteOptions'), () => {
  11263. options(website.name, website.options);
  11264. });
  11265. }
  11266. if (website.name !== 'Setting') {
  11267. GM_registerMenuCommand(i18n('changeGlobalOptions'), () => {
  11268. changeGlobalOptions('swal');
  11269. });
  11270. GM_registerMenuCommand(i18n('settingPage'), () => {
  11271. GM_openInTab('https://auto-task-v4.hclonely.com/setting.html', {
  11272. active: true
  11273. });
  11274. });
  11275. }
  11276. console.log('%c%s', 'color:#1bbe1a', 'Auto-Task[Load]: 脚本加载完成');
  11277. const [ v1, v2 ] = GM_info.version.split('.');
  11278. if (!(parseInt(v1, 10) >= 5 && parseInt(v2, 10) >= 2)) {
  11279. scripts_echoLog({}).error(i18n('versionNotMatched'));
  11280. }
  11281. if (!GM_getValue('notice')) {
  11282. external_Swal_default().fire({
  11283. title: i18n('swalNotice'),
  11284. icon: 'warning'
  11285. }).then(() => {
  11286. GM_openInTab(i18n('noticeLink'), {
  11287. active: true
  11288. });
  11289. GM_setValue('notice', new Date().getTime());
  11290. });
  11291. scripts_echoLog({
  11292. html: `<li><font class="warning">${i18n('echoNotice', i18n('noticeLink'))}</font></li>`
  11293. }).font?.find('a').on('click', () => {
  11294. GM_setValue('notice', new Date().getTime());
  11295. });
  11296. }
  11297. scripts_updateChecker();
  11298. };
  11299. if (window.location.hostname === 'discord.com') {
  11300. const LocalStorage = window.localStorage;
  11301. if (window.name === 'ATv4_discordAuth') {
  11302. window.localStorage.removeItem = () => true;
  11303. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11304. if (discordAuth && discordAuth.length > 0) {
  11305. GM_setValue('discordAuth', {
  11306. auth: discordAuth
  11307. });
  11308. window.close();
  11309. external_Swal_default().fire('', i18n('closePageNotice'));
  11310. } else {
  11311. external_Swal_default().fire({
  11312. text: i18n('getDiscordAuthFailed'),
  11313. icon: 'error'
  11314. });
  11315. }
  11316. } else {
  11317. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11318. if (discordAuth && discordAuth.length > 0) {
  11319. GM_setValue('discordAuth', {
  11320. auth: discordAuth
  11321. });
  11322. }
  11323. }
  11324. } else if (window.location.hostname === 'opquests.com') {
  11325. loadScript();
  11326. } else if ((window.name === 'ATv4_updateStoreAuth' || GM_getValue('ATv4_updateStoreAuth')) && window.location.host === 'store.steampowered.com') {
  11327. $(() => {
  11328. if ($('[data-miniprofile]').length === 0) {
  11329. return;
  11330. }
  11331. const storeSessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11332. if (storeSessionID) {
  11333. GM_deleteValue('ATv4_updateStoreAuth');
  11334. GM_setValue('steamStoreAuth', {
  11335. storeSessionID: storeSessionID
  11336. });
  11337. window.close();
  11338. external_Swal_default().fire('', i18n('closePageNotice'));
  11339. } else {
  11340. external_Swal_default().fire({
  11341. title: 'Error: Get "sessionID" failed',
  11342. icon: 'error'
  11343. });
  11344. }
  11345. });
  11346. } else if ((window.name === 'ATv4_updateCommunityAuth' || GM_getValue('ATv4_updateCommunityAuth')) && window.location.host === 'steamcommunity.com') {
  11347. $(() => {
  11348. const steam64Id = document.body.innerHTML.match(/g_steamID = "(.+?)";/)?.[1];
  11349. const communitySessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11350. if (steam64Id && communitySessionID) {
  11351. GM_deleteValue('ATv4_updateCommunityAuth');
  11352. GM_setValue('steamCommunityAuth', {
  11353. steam64Id: steam64Id,
  11354. communitySessionID: communitySessionID
  11355. });
  11356. window.close();
  11357. external_Swal_default().fire('', i18n('closePageNotice'));
  11358. } else {
  11359. setTimeout(() => {
  11360. external_Swal_default().fire({
  11361. title: 'Error: Get "sessionID" failed',
  11362. icon: 'error'
  11363. });
  11364. }, 3e3);
  11365. }
  11366. });
  11367. } else {
  11368. if (window.location.hostname === 'key-hub.eu') {
  11369. unsafeWindow.keyhubtracker = 1;
  11370. unsafeWindow.gaData = {};
  11371. }
  11372. $(loadScript);
  11373. }
  11374. }();
  11375. })();