auto-task-v4

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

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

  1. // ==UserScript==
  2. // @name auto-task-v4
  3. // @namespace auto-task-v4
  4. // @version 4.7.1
  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{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;z-index:999999999 !important;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{display:inline-block;text-transform:capitalize;margin-left:10px;text-decoration:none !important;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{position:fixed;top:30px;right:15px;width:124px;z-index:999999999 !important;transform:scale(0.85)}#auto-task-buttons p,.show-button-div p{line-height:30px;height:40px;text-align:center;margin:5px !important}#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. notConnect: '社交平台未连接,跳过任务',
  1475. confirmingTask: '正在跳过警告页面...'
  1476. };
  1477. const zh_CN = data;
  1478. const en_US_data = {
  1479. website: 'Website',
  1480. type: 'Type',
  1481. edit: 'Edit',
  1482. whiteList: 'Whitelist',
  1483. skipTask: 'Skip undo task',
  1484. whiteListOptions: 'Whitelist options',
  1485. changeWhiteListOption: 'Whitelist option(%0)',
  1486. whiteListNotFound: 'Cannot find this whitelist: %0',
  1487. changeWhiteListSuccess: 'The whitelist is successfully modified, and the page refresh will take effect!',
  1488. changeWebsiteOptions: 'Website options',
  1489. changeGlobalOptions: 'Global options',
  1490. ok: 'OK',
  1491. save: 'Save',
  1492. close: 'Close',
  1493. return: 'Return',
  1494. option: 'Option',
  1495. value: 'Value',
  1496. websiteOptions: 'Current website settings',
  1497. changeWebsiteOptionsSuccess: 'The current website setting is changed successfully, and the page refresh will take effect!',
  1498. changeGlobalOptionsSuccess: 'The global setting is changed successfully, and the refresh will take effect!',
  1499. needLogin: 'Please log in first!',
  1500. getTasksInfo: 'Obtaining and processing task information...',
  1501. gettingKey: 'Getting Key...',
  1502. verifyingTask: 'Verifying task',
  1503. notice: 'Automatic task script notice',
  1504. noKeysLeft: 'There are no more keys left on this page. Do you want to close it?',
  1505. giveawayEnded: 'This event has ended, do you want to close it?',
  1506. 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?',
  1507. confirm: 'Confirm',
  1508. cancel: 'Cancel',
  1509. unKnown: 'Unknown',
  1510. unKnownTaskType: 'Unrecognized task',
  1511. doing: 'Doing a task',
  1512. allTasksComplete: 'All tasks have been completed!',
  1513. getTaskIdFailed: 'Failed to obtain task Id!',
  1514. initSuccess: '%0 was initialized successfully!',
  1515. initFailed: '%0 initialization failed!',
  1516. errorLink: 'Link error: %0',
  1517. needInit: 'Please initialize first',
  1518. verifyingAuth: 'Verifying %0 token...',
  1519. updatingAuth: 'Update %0 token...',
  1520. refreshingToken: 'Refreshing %0 token...',
  1521. settingToken: 'Setting %0 token...',
  1522. steamStoreTab: 'Steam store (new tab)',
  1523. steamCommunityTab: 'Steam community(new tab)',
  1524. initing: 'Initializing...',
  1525. getFailed: 'Failed to get %0!',
  1526. checkLoginFailed: 'Failed to detect login status!',
  1527. checkLeftKeyFailed: 'Failed to detect the remaining keys!',
  1528. userId: 'User Id',
  1529. joiningGiveaway: 'Joining giveaway',
  1530. needJoinGiveaway: 'Need to join the giveaway first',
  1531. cannotUndo: 'This website does not support canceling tasks',
  1532. verifyAuth: 'Verifying %0 token...',
  1533. closePageNotice: 'f this page does not close automatically, please close this page yourself.',
  1534. errorReport: 'A script error is detected, do you want to report the BUG?',
  1535. visitingLink: 'Visiting link: ',
  1536. doTask: 'DoTask',
  1537. undoTask: 'UndoTask',
  1538. verifyTask: 'Verify',
  1539. getKey: 'GetKey',
  1540. selectAll: 'SelectAll',
  1541. selectNone: 'SelectNone',
  1542. invertSelect: 'InvertSelect',
  1543. doFreeTask: 'FreeTask',
  1544. doPointTask: 'PointTask',
  1545. skipTaskOption: 'Skip task has been configured in the settings',
  1546. other: 'Other',
  1547. globalOptions: 'Global Options',
  1548. checkLogin: 'Login detection</br>Need to log in to the website automatically log in, part of this website supports.',
  1549. checkLeftKey: 'Key remaining detection</br>The end of the giveaway event prompts whether to close or not, part of this website supports.',
  1550. 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.',
  1551. 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.',
  1552. 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.',
  1553. saveGlobalOptions: 'SaveSettings',
  1554. settingPage: 'Setting Page',
  1555. name: 'Name',
  1556. version: 'Version',
  1557. scriptManager: 'Script Manager',
  1558. script: 'Script',
  1559. environment: 'Environment',
  1560. os: 'OS',
  1561. browser: 'Browser',
  1562. getId: 'Get %0 id',
  1563. getTwitterUserId: 'Get Twitter user id (Get id function is only available on the settings page).',
  1564. getYoutubeChannelId: 'Get Youtube channel id (Get id function is only available on the settings page).',
  1565. showButton: 'ShowButton',
  1566. hideButton: 'HideButton',
  1567. showLog: 'ShowLog',
  1568. hideLog: 'HideLog',
  1569. defaultShowButton: 'Default display button',
  1570. defaultShowLog: 'Display log by default',
  1571. debug: 'Output debug log, do not enable this option!',
  1572. receivePreview: 'Receive preview updates',
  1573. position: 'Component position',
  1574. buttonSideX: 'Horizontal positioning of the button area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1575. 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',
  1576. 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',
  1577. showButtonSideX: 'ShowButton horizontal positioning (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1578. showButtonSideY: 'ShowButton vertical positioning (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  1579. 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',
  1580. logSideX: 'Horizontal positioning of the log area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1581. logSideY: 'Vertical positioning of the log area (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  1582. 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',
  1583. hotKey: 'Shortcut key',
  1584. doTaskKey: 'DoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  1585. undoTaskKey: 'UndoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  1586. toggleLogKey: 'ShowLog/HideLog shortcut keys</br> (real-time preview function is only available on the settings page).',
  1587. tasksHistory: 'TasksHistory',
  1588. clearHistory: 'Clear history',
  1589. clearHistoryFinished: 'The mission history has been cleared!',
  1590. deleteTask: 'Delete task',
  1591. lastChangeTime: 'Last Change Time',
  1592. clearTaskFinished: 'Delete the following tasks completed!',
  1593. clearTaskFailed: 'Failed to delete the task, the task name was not found!',
  1594. syncData: 'DataSync',
  1595. settingData: 'Uploading data...',
  1596. gettingData: 'Getting data...',
  1597. help: 'Help',
  1598. fileName: 'Filename',
  1599. upload2gist: 'Sync to Gist',
  1600. downloadFromGist: 'Sync from Gist',
  1601. saveAndTest: 'Save configuration and test',
  1602. testSuccess: 'Test success!',
  1603. testFailed: 'Test failed!',
  1604. saveAndTestNotice: 'Please save the configuration and test first!',
  1605. processingData: 'Processing data...',
  1606. updatingData: 'Uploading data...',
  1607. syncDataSuccess: 'Synchronized data successfully!',
  1608. syncDataFailed: 'Failed to synchronize data, please check the error message on the console!',
  1609. downloadingData: 'Downloading data...',
  1610. checkedNoData: 'No remote data is detected, please confirm whether the configuration is correct!',
  1611. savingData: 'Saving data...',
  1612. syncHistory: 'Synchronize tasks history',
  1613. checkUpdateFailed: 'Check update failed',
  1614. newVersionNotice: 'Checked a new version V%0, <a class="high-light" href="%1" target="_blank">click to update</a>',
  1615. language: 'Language</br> Currently only supports zh: Chinese, en: English',
  1616. gistOptions: 'Gist Settings',
  1617. 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!',
  1618. 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!',
  1619. noticeLink: 'https://auto-task-doc.js.org/en/guide/#read-me-first',
  1620. toGithub: 'Feedback(Github)',
  1621. toKeylol: 'Feedback(Keylol)',
  1622. copySuccess: 'The error message has been copied to the clipboard. Do you want to go to the Keylol forum to give feedback?',
  1623. copyFailed: 'Please copy the error information below and report back to the Keylol forum!',
  1624. updateText: 'Updates in version %0:',
  1625. Active: 'Active',
  1626. Ended: 'Ended',
  1627. Banned: 'Banned',
  1628. Paused: 'Paused',
  1629. notStart: 'notStart',
  1630. noRemoteData: 'No data remotely',
  1631. errorRemoteDataFormat: 'Remote data has wrong format',
  1632. updateHistory: '<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">Click here</a>' + ' to view the historical update record.',
  1633. AsfEnabled: 'Use ASF to do Steam related tasks (requires <a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a> plugin)',
  1634. AsfIpcUrl: 'ASF IPC URL',
  1635. AsfIpcPassword: 'ASF IPC Password',
  1636. groups: 'Group',
  1637. officialGroups: 'Official Group',
  1638. wishlists: 'Wishlist',
  1639. follows: 'Follow Game',
  1640. forums: 'Forum',
  1641. workshops: 'Favorite Workshop',
  1642. curators: 'Curator',
  1643. workshopVotes: 'Voteup Workshop',
  1644. announcements: 'Announcement',
  1645. steamCommunity: 'Steam Community',
  1646. steamStore: 'Steam Store',
  1647. licenses: 'Add License',
  1648. playtests: 'Playtest Access',
  1649. needLoginSteamStore: 'Please <a href="https://store.steampowered.com/login/" target="_blank">log in to the Steam Store</a>',
  1650. needLoginSteamCommunity: 'Please <a href="https://steamcommunity.com/login/home/" target="_blank">log in to the Steam Community</a>',
  1651. joiningSteamGroup: 'Joining Steam Group',
  1652. leavingSteamGroup: 'Leaving Steam Group',
  1653. gettingSteamGroupId: 'Getting Steam Group Id',
  1654. joiningSteamOfficialGroup: 'Joining Steam Official Group',
  1655. leavingSteamOfficialGroup: 'Leaving Steam Official Group',
  1656. gettingSteamOfficialGroupId: 'Getting Steam Official Group Id',
  1657. subscribingForum: 'Subscribing the Steam Forum',
  1658. unsubscribingForum: 'Unsubscribing the Steam Forum',
  1659. gettingForumId: 'Getting Steam Forum Id',
  1660. followingCurator: 'Following Steam Curator',
  1661. unfollowingCurator: 'Unfollowing Steam Curator',
  1662. gettingCuratorId: 'Getting Steam Curator Id',
  1663. addingToWishlist: 'Adding the game to the Steam wishlist',
  1664. removingFromWishlist: 'Removing the game from the Steam wishlist',
  1665. followingGame: 'Following Steam games',
  1666. unfollowingGame: 'Unfollowing Steam games',
  1667. favoritingWorkshop: 'Favouring Steam Workshop Items',
  1668. unfavoritingWorkshop: 'Unfavoriting Steam Workshop Items',
  1669. gettingWorkshopAppId: 'Getting Steam Workshop Item Id',
  1670. votingUpWorkshop: 'Liking Steam workshop items',
  1671. gettingAnnouncementParams: 'Getting Steam announcement information',
  1672. likingAnnouncement: 'Liking Steam announcement',
  1673. changingArea: 'Changing Steam area: %0...',
  1674. notNeededChangeArea: 'The current area does not need to be changed',
  1675. noAnotherArea: 'Please check whether the proxy is turned on correctly',
  1676. gettingAreaInfo: 'Getting Steam area information...',
  1677. changeAreaNotice: 'Suspected of a locked zone game, try to change the zone to execute',
  1678. steamFinishNotice: 'Steam task completed, try to change the shopping cart area back to ',
  1679. gettingSubid: 'Getting subid',
  1680. addingFreeLicense: 'Adding free license',
  1681. missParams: 'Missing parameters',
  1682. gettingLicenses: 'Getting licenses...',
  1683. requestingPlayTestAccess: 'Requesting play test access',
  1684. 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.',
  1685. versionNotMatched: 'The script manager version is too low, requiring TamperMonkey >= 5.2.0 or TamperMonkey Beta >= 5.2.6196',
  1686. gettingUserLink: 'Getting steam user community link...',
  1687. retry: 'Retry',
  1688. owned: 'Owned',
  1689. redirect: 'Redirect',
  1690. noSubid: 'skip due to unrecognized',
  1691. initingASF: 'Initing ASF...',
  1692. servers: 'Server',
  1693. joiningDiscordServer: 'Joining Discord Server',
  1694. leavingDiscordServer: 'Leaving Discord Server',
  1695. gettingDiscordGuild: 'Getting Discord server Id',
  1696. getDiscordAuthFailed: 'Failed to get Discord token, please check whether the Discord account is logged in',
  1697. discordImportantNotice: 'Important Reminder! ! !',
  1698. 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! ! !',
  1699. continue: 'Continue',
  1700. skipDiscordTask: 'Skip',
  1701. continueAndDontRemindAgain: 'Continue without Reminders',
  1702. users: 'User',
  1703. loginIns: 'Please <a href="https://www.instagram.com/accounts/login/" target="_blank">log in to Instagram</a>',
  1704. insBanned: 'Your Instagram account has been banned',
  1705. verifyingInsAuth: 'Verifying Instagram token...',
  1706. gettingInsUserId: 'Getting Instagram user Id',
  1707. followingIns: 'Following Instagram user',
  1708. unfollowingIns: 'Unfollowing Instagram user',
  1709. reddits: 'Reddit/User',
  1710. loginReddit: 'Please <a href="https://www.reddit.com/login/" target="_blank">log in to Reddit</a>',
  1711. changingRedditVersion: 'Switching Reddit to a new version page...',
  1712. joiningReddit: 'Joining the Reddit',
  1713. leavingReddit: 'Leaving the Reddit',
  1714. followingRedditUser: 'Following Reddit User',
  1715. unfollowingRedditUser: 'Unfollowing Reddit User',
  1716. channels: 'Channel',
  1717. followingTwitchChannel: 'Following Twitch Channel',
  1718. unfollowingTwitchChannel: 'Unfollowing Twitch Channel',
  1719. gettingTwitchChannelId: 'Getting Twitch Channel Id',
  1720. checkingTwitchIntegrity: 'Checking Twitch integrity...',
  1721. twitterUser: 'Twitter User',
  1722. retweets: 'Retweet',
  1723. gettingTwitterUserId: 'Getting Twitter User Id',
  1724. followingTwitterUser: 'Following Twitter User',
  1725. unfollowingTwitterUser: 'Unfollowing Twitter User',
  1726. retweetting: 'Retweetting',
  1727. unretweetting: 'Unretweetting',
  1728. names: 'Group/Public/Wall',
  1729. loginVk: 'Please <a href="https://vk.com/login/" target="_blank">log in to Vk</a>',
  1730. gettingVkId: 'Getting Vk task Id',
  1731. joiningVkGroup: 'Joining Vk Group',
  1732. leavingVkGroup: 'Leaving Vk Group',
  1733. joiningVkPublic: 'Joining Vk Public',
  1734. leavingVkPublic: 'Leaving Vk Public',
  1735. sendingVkWall: 'Sending Vk Wall',
  1736. deletingVkWall: 'Deleting Vk Wall',
  1737. youtubeChannel: 'YouTube Channel',
  1738. likes: 'Like',
  1739. loginYtb: 'Please <a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">log in to YouTube</a>',
  1740. tryUpdateYtbAuth: 'Please try to <a href="https://www.youtube.com/#auth" target="_blank">update YouTube token</a>',
  1741. gettingYtbToken: 'Getting YouTube Token...',
  1742. followingYtbChannel: 'Subscribing to YouTube channel',
  1743. unfollowingYtbChannel: 'Unsubscribing to YouTube channel',
  1744. likingYtbVideo: 'Liking YouTube video',
  1745. unlikingYtbVideo: 'Unliking YouTube video',
  1746. giveKeyNoticeBefore: 'Each verification interval is 15s',
  1747. giveKeyNoticeAfter: 'If there is no key, please check at <a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>',
  1748. noPoints: 'Not enough points, skip the lottery',
  1749. getNeedPointsFailed: 'ailed to obtain the required points, skip the lottery',
  1750. joiningLottery: 'Joining the lottery',
  1751. doingGleamTask: 'Doing Gleam Task...',
  1752. gettingGleamLink: 'Getting Gleam task link...',
  1753. gleamTaskNotice: 'If this page has not been closed for a long time, please close it yourself after completing any task!',
  1754. verifiedGleamTasks: 'Attempted to verify all tasks. If the verification fails, please try to verify manually or complete it!',
  1755. campaign: 'ReCAPTCHA detected, please complete it and re-verify the tasks!',
  1756. 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!',
  1757. giveeClubVerifyNotice: 'Verifying task...',
  1758. giveeClubVerifyFinished: 'Wait for the verification to complete and join it by yourself',
  1759. doingKeyhubTask: 'Doing Keyhub Task...',
  1760. 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...',
  1761. tasksNotCompleted: 'Tasks Not Completed',
  1762. notConnect: 'Social platform is not connectted, skip',
  1763. confirmingTask: 'Confirming task...'
  1764. };
  1765. const en_US = en_US_data;
  1766. const languages = {
  1767. zh: zh_CN,
  1768. en: en_US
  1769. };
  1770. const language = [ 'zh', 'en' ].includes(globalOptions.other.language) ? globalOptions.other.language : 'en';
  1771. const I18n = (key, ...argvs) => {
  1772. if (!languages[language]?.[key]) {
  1773. return key;
  1774. }
  1775. return languages[language][key].replace(/%([\d]+)/g, (match, index) => argvs[parseInt(index, 10)]);
  1776. };
  1777. const i18n = I18n;
  1778. function throwError(error, name) {
  1779. if (window.TRACE) {
  1780. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  1781. }
  1782. external_Swal_default().fire({
  1783. title: i18n('errorReport'),
  1784. icon: 'error',
  1785. showCancelButton: true,
  1786. confirmButtonText: i18n('toGithub'),
  1787. showDenyButton: true,
  1788. denyButtonText: i18n('toKeylol'),
  1789. cancelButtonText: i18n('close')
  1790. }).then(({
  1791. isDenied,
  1792. isConfirmed
  1793. }) => {
  1794. if (isConfirmed) {
  1795. 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,
  1796. 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'))}`, {
  1797. active: true
  1798. });
  1799. } else if (isDenied) {
  1800. const text = `错误链接: [url=${window.location.href}]${window.location.href}[/url]
  1801.  
  1802. 环境:
  1803.  
  1804. [code]${JSON.stringify((0, javascript_utils_umd_min.ua)(), null, 4)}[/code]
  1805.  
  1806. 脚本管理器: ${GM_info.scriptHandler} ${GM_info.version}
  1807. 脚本版本: ${GM_info.script.version}
  1808.  
  1809. 报错信息:
  1810. [code]${error.stack}[/code]
  1811.  
  1812. 执行日志:
  1813. [code]${$.makeArray($('#auto-task-info>li')).map(element => element.innerText).join('\n')}[/code]`;
  1814. GM_setClipboard(text);
  1815. external_Swal_default().fire({
  1816. title: i18n('copySuccess'),
  1817. icon: 'success',
  1818. confirmButtonText: i18n('ok')
  1819. }).then(() => {
  1820. GM_openInTab('https://keylol.com/forum.php?mod=post&action=reply&fid=319&tid=777450', {
  1821. active: true
  1822. });
  1823. });
  1824. }
  1825. });
  1826. console.log('%c%s', 'color:white;background:red', `Auto-Task[Error]: ${name}\n${error.stack}`);
  1827. }
  1828. class Social {
  1829. tasks;
  1830. getRealParams(name, links, doTask, link2param) {
  1831. try {
  1832. let realParams = [];
  1833. if (links.length > 0) {
  1834. realParams = [ ...realParams, ...links.map(link => link2param(link)).filter(link => link) ];
  1835. }
  1836. if (!doTask && this.tasks[name].length > 0) {
  1837. realParams = [ ...realParams, ...this.tasks[name] ];
  1838. }
  1839. return unique(realParams);
  1840. } catch (error) {
  1841. throwError(error, 'Social.getRealParams');
  1842. return [];
  1843. }
  1844. }
  1845. }
  1846. const social_Social = Social;
  1847. class Discord extends social_Social {
  1848. tasks;
  1849. whiteList;
  1850. #auth = GM_getValue('discordAuth') || {};
  1851. #cache = GM_getValue('discordCache') || {};
  1852. #initialized = false;
  1853. constructor() {
  1854. super();
  1855. const defaultTasksTemplate = {
  1856. servers: []
  1857. };
  1858. this.tasks = defaultTasksTemplate;
  1859. this.whiteList = {
  1860. ...defaultTasksTemplate,
  1861. ...GM_getValue('whiteList')?.discord || {}
  1862. };
  1863. }
  1864. async init(action) {
  1865. try {
  1866. if (!GM_getValue('dontRemindDiscordAgain')) {
  1867. const result = await external_Swal_default().fire({
  1868. title: i18n('discordImportantNotice'),
  1869. text: i18n('discordImportantNoticeText'),
  1870. showCancelButton: true,
  1871. showDenyButton: true,
  1872. confirmButtonText: i18n('continue'),
  1873. cancelButtonText: i18n('skipDiscordTask'),
  1874. denyButtonText: i18n('continueAndDontRemindAgain')
  1875. }).then(({
  1876. isConfirmed,
  1877. isDenied
  1878. }) => {
  1879. if (isConfirmed) {
  1880. return true;
  1881. }
  1882. if (isDenied) {
  1883. GM_setValue('dontRemindDiscordAgain', true);
  1884. return true;
  1885. }
  1886. return false;
  1887. });
  1888. if (!result) {
  1889. this.#initialized = false;
  1890. return 'skip';
  1891. }
  1892. }
  1893. if (GM_getValue('dontRemindDiscordAgain') || action === 'do' && !globalOptions.doTask.discord.servers || action === 'undo' && !globalOptions.undoTask.discord.servers) {
  1894. this.#initialized = false;
  1895. return 'skip';
  1896. }
  1897. if (this.#initialized) {
  1898. return true;
  1899. }
  1900. if (!this.#auth.auth) {
  1901. if (await this.#updateAuth()) {
  1902. this.#initialized = true;
  1903. return true;
  1904. }
  1905. return false;
  1906. }
  1907. const isVerified = await this.#verifyAuth();
  1908. if (isVerified) {
  1909. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  1910. this.#initialized = true;
  1911. return true;
  1912. }
  1913. GM_setValue('discordAuth', {
  1914. auth: null
  1915. });
  1916. if (await this.#updateAuth()) {
  1917. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  1918. this.#initialized = true;
  1919. return true;
  1920. }
  1921. scripts_echoLog({}).error(i18n('initFailed', 'Discord'));
  1922. return false;
  1923. } catch (error) {
  1924. throwError(error, 'Discord.init');
  1925. return false;
  1926. }
  1927. }
  1928. async #verifyAuth() {
  1929. try {
  1930. const logStatus = scripts_echoLog({
  1931. text: i18n('verifyingAuth', 'Discord')
  1932. });
  1933. const {
  1934. result,
  1935. statusText,
  1936. status,
  1937. data
  1938. } = await tools_httpRequest({
  1939. url: 'https://discord.com/api/v6/users/@me',
  1940. method: 'HEAD',
  1941. headers: {
  1942. authorization: this.#auth.auth
  1943. }
  1944. });
  1945. if (result === 'Success') {
  1946. if (data?.status === 200) {
  1947. logStatus.success();
  1948. return true;
  1949. }
  1950. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  1951. return false;
  1952. }
  1953. logStatus.error(`${result}:${statusText}(${status})`);
  1954. return false;
  1955. } catch (error) {
  1956. throwError(error, 'Discord.verifyAuth');
  1957. return false;
  1958. }
  1959. }
  1960. async #updateAuth() {
  1961. try {
  1962. const logStatus = scripts_echoLog({
  1963. text: i18n('updatingAuth', 'Discord')
  1964. });
  1965. return await new Promise(resolve => {
  1966. const newTab = GM_openInTab('https://discord.com/channels/@me', {
  1967. active: true,
  1968. insert: true,
  1969. setParent: true
  1970. });
  1971. newTab.name = 'ATv4_discordAuth';
  1972. newTab.onclose = async () => {
  1973. const auth = GM_getValue('discordAuth')?.auth;
  1974. if (auth) {
  1975. this.#auth = {
  1976. auth: auth
  1977. };
  1978. logStatus.success();
  1979. resolve(await this.#verifyAuth());
  1980. } else {
  1981. logStatus.error('Error: Update discord auth failed!');
  1982. resolve(false);
  1983. }
  1984. };
  1985. });
  1986. } catch (error) {
  1987. throwError(error, 'Discord.updateAuth');
  1988. return false;
  1989. }
  1990. }
  1991. async #joinServer(inviteId) {
  1992. try {
  1993. const logStatus = scripts_echoLog({
  1994. type: 'joiningDiscordServer',
  1995. text: inviteId
  1996. });
  1997. const {
  1998. result,
  1999. statusText,
  2000. status,
  2001. data
  2002. } = await tools_httpRequest({
  2003. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2004. method: 'POST',
  2005. dataType: 'json',
  2006. headers: {
  2007. authorization: this.#auth.auth,
  2008. origin: 'https://discord.com',
  2009. referer: `https://discord.com/invite/${inviteId}`
  2010. }
  2011. });
  2012. if (result === 'Success' && data?.status === 200) {
  2013. logStatus.success();
  2014. const guild = String(data.response?.guild?.id);
  2015. if (guild) {
  2016. this.#setCache(inviteId, guild);
  2017. this.tasks.servers = unique([ ...this.tasks.servers, inviteId ]);
  2018. }
  2019. return true;
  2020. }
  2021. logStatus.error(`${result}:${statusText}(${status})`);
  2022. return false;
  2023. } catch (error) {
  2024. throwError(error, 'Discord.joinServer');
  2025. return false;
  2026. }
  2027. }
  2028. async #leaveServer(inviteId) {
  2029. try {
  2030. if (this.whiteList.servers.includes(inviteId)) {
  2031. scripts_echoLog({
  2032. type: 'whiteList',
  2033. text: 'Discord.leaveServer',
  2034. id: inviteId
  2035. });
  2036. return true;
  2037. }
  2038. const guild = await this.#getGuild(inviteId);
  2039. if (!guild) {
  2040. return false;
  2041. }
  2042. const logStatus = scripts_echoLog({
  2043. type: 'leavingDiscordServer',
  2044. text: guild
  2045. });
  2046. const {
  2047. result,
  2048. statusText,
  2049. status,
  2050. data
  2051. } = await tools_httpRequest({
  2052. url: `https://discord.com/api/v9/users/@me/guilds/${guild}`,
  2053. method: 'DELETE',
  2054. headers: {
  2055. authorization: this.#auth.auth
  2056. }
  2057. });
  2058. if (result === 'Success' && data?.status === 204) {
  2059. logStatus.success();
  2060. return true;
  2061. }
  2062. logStatus.error(`${result}:${statusText}(${status})`);
  2063. return false;
  2064. } catch (error) {
  2065. throwError(error, 'Discord.leaveServer');
  2066. return false;
  2067. }
  2068. }
  2069. async #getGuild(inviteId) {
  2070. try {
  2071. const logStatus = scripts_echoLog({
  2072. type: 'gettingDiscordGuild',
  2073. text: inviteId
  2074. });
  2075. const guild = this.#cache[inviteId];
  2076. if (guild) {
  2077. logStatus.success();
  2078. return guild;
  2079. }
  2080. const {
  2081. result,
  2082. statusText,
  2083. status,
  2084. data
  2085. } = await tools_httpRequest({
  2086. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2087. responseType: 'json',
  2088. method: 'GET'
  2089. });
  2090. if (result === 'Success' && data?.status === 200) {
  2091. const guild = data.response?.guild?.id;
  2092. if (guild) {
  2093. logStatus.success();
  2094. this.#setCache(inviteId, guild);
  2095. return guild;
  2096. }
  2097. logStatus.error(`${result}:${statusText}(${status})`);
  2098. return false;
  2099. }
  2100. logStatus.error(`${result}:${statusText}(${status})`);
  2101. return false;
  2102. } catch (error) {
  2103. throwError(error, 'Discord.getGuild');
  2104. return false;
  2105. }
  2106. }
  2107. async toggle({
  2108. doTask = true,
  2109. serverLinks = []
  2110. }) {
  2111. try {
  2112. if (!this.#initialized) {
  2113. scripts_echoLog({
  2114. text: i18n('needInit')
  2115. });
  2116. return false;
  2117. }
  2118. const prom = [];
  2119. if (doTask && !globalOptions.doTask.discord.servers || !doTask && !globalOptions.undoTask.discord.servers) {
  2120. scripts_echoLog({
  2121. type: 'globalOptionsSkip',
  2122. text: 'discord.servers'
  2123. });
  2124. } else {
  2125. const realServers = this.getRealParams('servers', serverLinks, doTask, link => link.match(/invite\/(.+)/)?.[1]);
  2126. if (realServers.length > 0) {
  2127. for (const server of realServers) {
  2128. if (doTask) {
  2129. prom.push(this.#joinServer(server));
  2130. } else {
  2131. prom.push(this.#leaveServer(server));
  2132. }
  2133. await delay(1e3);
  2134. }
  2135. }
  2136. }
  2137. return await Promise.all(prom).then(() => true);
  2138. } catch (error) {
  2139. throwError(error, 'Discord.toggleServers');
  2140. return false;
  2141. }
  2142. }
  2143. #setCache(inviteId, guild) {
  2144. try {
  2145. this.#cache[inviteId] = guild;
  2146. GM_setValue('discordCache', this.#cache);
  2147. } catch (error) {
  2148. throwError(error, 'Discord.setCache');
  2149. }
  2150. }
  2151. }
  2152. const social_Discord = Discord;
  2153. class Instagram extends social_Social {
  2154. tasks;
  2155. whiteList;
  2156. #cache = GM_getValue('instagramCache') || {};
  2157. #auth = {};
  2158. #initialized = false;
  2159. constructor() {
  2160. super();
  2161. const defaultTasksTemplate = {
  2162. users: []
  2163. };
  2164. this.tasks = defaultTasksTemplate;
  2165. this.whiteList = {
  2166. ...defaultTasksTemplate,
  2167. ...GM_getValue('whiteList')?.instagram || {}
  2168. };
  2169. }
  2170. async init() {
  2171. try {
  2172. if (this.#initialized) {
  2173. return true;
  2174. }
  2175. const isVerified = await this.#getUserInfo();
  2176. if (isVerified) {
  2177. scripts_echoLog({}).success(i18n('initSuccess', 'Instagram'));
  2178. this.#initialized = true;
  2179. return true;
  2180. }
  2181. scripts_echoLog({}).error(i18n('initFailed', 'Instagram'));
  2182. return false;
  2183. } catch (error) {
  2184. throwError(error, 'Instagram.init');
  2185. return false;
  2186. }
  2187. }
  2188. async #getUserInfo(name = 'instagram') {
  2189. try {
  2190. const logStatus = scripts_echoLog({
  2191. type: name === 'instagram' ? 'verifyingInsAuth' : 'gettingInsUserId',
  2192. text: name
  2193. });
  2194. const userId = this.#cache[name];
  2195. if (userId && name !== 'instagram') {
  2196. logStatus.success();
  2197. return userId;
  2198. }
  2199. const {
  2200. result,
  2201. statusText,
  2202. status,
  2203. data
  2204. } = await tools_httpRequest({
  2205. url: `https://www.instagram.com/${name}/`,
  2206. method: 'GET'
  2207. });
  2208. if (result === 'Success') {
  2209. if (data?.finalUrl.includes('accounts/login')) {
  2210. logStatus.error(`Error:${i18n('loginIns')}`, true);
  2211. return false;
  2212. } else if (data?.finalUrl.includes('www.instagram.com/challenge')) {
  2213. logStatus.error(`Error:${i18n('insBanned')}`);
  2214. return false;
  2215. }
  2216. if (data?.status === 200) {
  2217. const csrftoken = data.responseText.match(/"csrf_token":"(.+?)"/)?.[1];
  2218. const hash = data.responseText.match(/"rollout_hash":"(.+?)"/)?.[1];
  2219. if (name === 'instagram') {
  2220. if (csrftoken && hash) {
  2221. this.#auth = {
  2222. csrftoken: csrftoken,
  2223. hash: hash
  2224. };
  2225. return true;
  2226. }
  2227. return false;
  2228. }
  2229. const id = data.responseText.match(/"profilePage_([\d]+?)"/)?.[1];
  2230. if (id) {
  2231. this.#setCache(name, id);
  2232. logStatus.success();
  2233. return id;
  2234. }
  2235. logStatus.error('Error: Get ins data error!');
  2236. return false;
  2237. }
  2238. logStatus.error(`${result}:${statusText}(${status})`);
  2239. return false;
  2240. }
  2241. return false;
  2242. } catch (error) {
  2243. throwError(error, 'Instagram.getUserInfo');
  2244. return false;
  2245. }
  2246. }
  2247. async #followUser(name) {
  2248. try {
  2249. const id = await this.#getUserInfo(name);
  2250. if (!id) {
  2251. return false;
  2252. }
  2253. const logStatus = scripts_echoLog({
  2254. type: 'followingIns',
  2255. text: name
  2256. });
  2257. const {
  2258. result,
  2259. statusText,
  2260. status,
  2261. data
  2262. } = await tools_httpRequest({
  2263. url: `https://www.instagram.com/web/friendships/${id}/follow/`,
  2264. method: 'POST',
  2265. dataType: 'json',
  2266. headers: {
  2267. 'x-csrftoken': this.#auth.csrftoken,
  2268. origin: 'https://www.instagram.com',
  2269. referer: `https://www.instagram.com/${name}/`,
  2270. 'content-type': 'application/x-www-form-urlencoded',
  2271. 'sec-fetch-site': 'same-origin',
  2272. 'x-instagram-ajax': this.#auth.hash
  2273. }
  2274. });
  2275. if (result === 'Success') {
  2276. if (data?.status === 200 && data.response?.result === 'following') {
  2277. logStatus.success();
  2278. this.tasks.users = unique([ ...this.tasks.users, name ]);
  2279. return true;
  2280. }
  2281. logStatus.error(`Error:${data?.response?.feedback_message || `${data?.statusText}(${data?.status})`}`);
  2282. return false;
  2283. }
  2284. logStatus.error(`${result}:${statusText}(${status})`);
  2285. return false;
  2286. } catch (error) {
  2287. throwError(error, 'Instagram.followUser');
  2288. return false;
  2289. }
  2290. }
  2291. async #unfollowUser(name) {
  2292. try {
  2293. if (this.whiteList.users.includes(name)) {
  2294. scripts_echoLog({
  2295. type: 'whiteList',
  2296. text: 'Instagram.unfollowUser',
  2297. id: name
  2298. });
  2299. return true;
  2300. }
  2301. const id = await this.#getUserInfo(name);
  2302. if (!id) {
  2303. return false;
  2304. }
  2305. const logStatus = scripts_echoLog({
  2306. type: 'unfollowingIns',
  2307. text: name
  2308. });
  2309. const {
  2310. result,
  2311. statusText,
  2312. status,
  2313. data
  2314. } = await tools_httpRequest({
  2315. url: `https://www.instagram.com/web/friendships/${id}/unfollow/`,
  2316. method: 'POST',
  2317. dataType: 'json',
  2318. headers: {
  2319. 'x-csrftoken': this.#auth.csrftoken,
  2320. origin: 'https://www.instagram.com',
  2321. referer: `https://www.instagram.com/${name}/`,
  2322. 'content-type': 'application/x-www-form-urlencoded',
  2323. 'sec-fetch-site': 'same-origin',
  2324. 'x-instagram-ajax': this.#auth.hash
  2325. }
  2326. });
  2327. if (result === 'Success') {
  2328. if (data?.status === 200 && data.response?.status === 'ok') {
  2329. logStatus.success();
  2330. return true;
  2331. }
  2332. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2333. return false;
  2334. }
  2335. logStatus.error(`${result}:${statusText}(${status})`);
  2336. return false;
  2337. } catch (error) {
  2338. throwError(error, 'Instagram.unfollowUser');
  2339. return false;
  2340. }
  2341. }
  2342. async toggle({
  2343. doTask = true,
  2344. userLinks = []
  2345. }) {
  2346. try {
  2347. if (!this.#initialized) {
  2348. scripts_echoLog({
  2349. text: i18n('needInit')
  2350. });
  2351. return false;
  2352. }
  2353. const prom = [];
  2354. if (doTask && !globalOptions.doTask.instagram.users || !doTask && !globalOptions.undoTask.instagram.users) {
  2355. scripts_echoLog({
  2356. type: 'globalOptionsSkip',
  2357. text: 'instagram.users'
  2358. });
  2359. } else {
  2360. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1]);
  2361. if (realUsers.length > 0) {
  2362. for (const username of realUsers) {
  2363. if (doTask) {
  2364. prom.push(this.#followUser(username));
  2365. } else {
  2366. prom.push(this.#unfollowUser(username));
  2367. }
  2368. await delay(1e3);
  2369. }
  2370. }
  2371. }
  2372. return await Promise.all(prom).then(() => true);
  2373. } catch (error) {
  2374. throwError(error, 'Instagram.toggleUsers');
  2375. return false;
  2376. }
  2377. }
  2378. #setCache(name, id) {
  2379. try {
  2380. this.#cache[name] = id;
  2381. GM_setValue('instagramCache', this.#cache);
  2382. } catch (error) {
  2383. throwError(error, 'Instagram.setCache');
  2384. }
  2385. }
  2386. }
  2387. const social_Instagram = Instagram;
  2388. class Reddit extends social_Social {
  2389. tasks;
  2390. whiteList;
  2391. #auth;
  2392. #initialized = false;
  2393. constructor() {
  2394. super();
  2395. const defaultTasksTemplate = {
  2396. reddits: []
  2397. };
  2398. this.tasks = defaultTasksTemplate;
  2399. this.whiteList = {
  2400. ...defaultTasksTemplate,
  2401. ...GM_getValue('whiteList')?.reddit || {}
  2402. };
  2403. }
  2404. async init() {
  2405. try {
  2406. if (this.#initialized) {
  2407. return true;
  2408. }
  2409. const isVerified = await this.#updateAuth();
  2410. if (isVerified) {
  2411. scripts_echoLog({}).success(i18n('initSuccess', 'Reddit'));
  2412. this.#initialized = true;
  2413. return true;
  2414. }
  2415. scripts_echoLog({}).error(i18n('initFailed', 'Reddit'));
  2416. return false;
  2417. } catch (error) {
  2418. throwError(error, 'Reddit.init');
  2419. return false;
  2420. }
  2421. }
  2422. async #useBeta() {
  2423. try {
  2424. const logStatus = scripts_echoLog({
  2425. text: i18n('changingRedditVersion')
  2426. });
  2427. return await new Promise(resolve => {
  2428. const newTab = GM_openInTab('https://www.reddit.com/', {
  2429. active: true,
  2430. insert: true,
  2431. setParent: true
  2432. });
  2433. newTab.name = 'ATv4_redditAuth';
  2434. newTab.onclose = async () => {
  2435. logStatus.success();
  2436. resolve(await this.#updateAuth(true));
  2437. };
  2438. });
  2439. } catch (error) {
  2440. throwError(error, 'Reddit.useBeta');
  2441. return false;
  2442. }
  2443. }
  2444. async #updateAuth(beta = false) {
  2445. try {
  2446. const logStatus = scripts_echoLog({
  2447. text: i18n('updatingAuth', 'Reddit')
  2448. });
  2449. const {
  2450. result,
  2451. statusText,
  2452. status,
  2453. data
  2454. } = await tools_httpRequest({
  2455. url: 'https://www.reddit.com/',
  2456. method: 'GET',
  2457. nochche: true,
  2458. headers: {
  2459. 'Cache-Control': 'no-cache'
  2460. }
  2461. });
  2462. if (result === 'Success') {
  2463. if (data?.responseText.includes('www.reddit.com/login/')) {
  2464. logStatus.error(`Error:${i18n('loginReddit')}`, true);
  2465. return false;
  2466. }
  2467. if (data?.status === 200) {
  2468. if (data.responseText.includes('redesign-beta-optin-btn') && !beta) {
  2469. return await this.#useBeta();
  2470. }
  2471. const accessToken = data.responseText.match(/"accessToken":"(.*?)","expires":"(.*?)"/)?.[1];
  2472. if (accessToken) {
  2473. this.#auth = {
  2474. token: accessToken
  2475. };
  2476. logStatus.success();
  2477. return true;
  2478. }
  2479. logStatus.error('Error: Parameter "accessToken" not found!');
  2480. return false;
  2481. }
  2482. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2483. return false;
  2484. }
  2485. logStatus.error(`${result}:${statusText}(${status})`);
  2486. return false;
  2487. } catch (error) {
  2488. throwError(error, 'Reddit.updateAuth');
  2489. return false;
  2490. }
  2491. }
  2492. async #toggleTask({
  2493. name,
  2494. doTask = true
  2495. }) {
  2496. try {
  2497. if (!doTask && this.whiteList.reddits.includes(name)) {
  2498. scripts_echoLog({
  2499. type: 'whiteList',
  2500. text: 'Reddit.undoTask',
  2501. id: name
  2502. });
  2503. return true;
  2504. }
  2505. let type = doTask ? 'joiningReddit' : 'leavingReddit';
  2506. if (/^u_/.test(name)) {
  2507. type = doTask ? 'followingRedditUser' : 'unfollowingRedditUser';
  2508. }
  2509. const logStatus = scripts_echoLog({
  2510. type: type,
  2511. text: name
  2512. });
  2513. const {
  2514. result,
  2515. statusText,
  2516. status,
  2517. data
  2518. } = await tools_httpRequest({
  2519. url: 'https://oauth.reddit.com/api/subscribe?redditWebClient=desktop2x&app=desktop2x-client-production&raw_json=1&gilding_detail=1',
  2520. method: 'POST',
  2521. headers: {
  2522. authorization: `Bearer ${this.#auth.token}`,
  2523. 'content-type': 'application/x-www-form-urlencoded'
  2524. },
  2525. data: $.param({
  2526. action: doTask ? 'sub' : 'unsub',
  2527. sr_name: name,
  2528. api_type: 'json'
  2529. })
  2530. });
  2531. if (result === 'Success') {
  2532. if (data?.status === 200) {
  2533. logStatus.success();
  2534. if (doTask) {
  2535. this.tasks.reddits = unique([ ...this.tasks.reddits, name ]);
  2536. }
  2537. return true;
  2538. }
  2539. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2540. return false;
  2541. }
  2542. logStatus.error(`${result}:${statusText}(${status})`);
  2543. return false;
  2544. } catch (error) {
  2545. throwError(error, 'Reddit.toggleTask');
  2546. return false;
  2547. }
  2548. }
  2549. async toggle({
  2550. doTask = true,
  2551. redditLinks = []
  2552. }) {
  2553. try {
  2554. if (!this.#initialized) {
  2555. scripts_echoLog({
  2556. text: i18n('needInit')
  2557. });
  2558. return false;
  2559. }
  2560. const prom = [];
  2561. if (doTask && !globalOptions.doTask.reddit.reddits || !doTask && !globalOptions.undoTask.reddit.reddits) {
  2562. scripts_echoLog({
  2563. type: 'globalOptionsSkip',
  2564. text: 'reddit.reddits'
  2565. });
  2566. } else {
  2567. const realReddits = this.getRealParams('reddits', redditLinks, doTask, link => {
  2568. const name = link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1];
  2569. const userName = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1];
  2570. if (userName) {
  2571. return name || userName;
  2572. }
  2573. return name;
  2574. });
  2575. if (realReddits.length > 0) {
  2576. for (const name of realReddits) {
  2577. prom.push(this.#toggleTask({
  2578. name: name,
  2579. doTask: doTask
  2580. }));
  2581. await delay(1e3);
  2582. }
  2583. }
  2584. }
  2585. return await Promise.all(prom).then(() => true);
  2586. } catch (error) {
  2587. throwError(error, 'Reddit.toggle');
  2588. return false;
  2589. }
  2590. }
  2591. }
  2592. const social_Reddit = Reddit;
  2593. class Twitch extends social_Social {
  2594. tasks;
  2595. whiteList;
  2596. #auth = GM_getValue('twitchAuth') || {};
  2597. #cache = GM_getValue('twitchCache') || {};
  2598. #initialized = false;
  2599. #integrityToken;
  2600. constructor() {
  2601. super();
  2602. const defaultTasksTemplate = {
  2603. channels: []
  2604. };
  2605. this.tasks = defaultTasksTemplate;
  2606. this.whiteList = {
  2607. ...defaultTasksTemplate,
  2608. ...GM_getValue('whiteList')?.twitch || {}
  2609. };
  2610. }
  2611. async init() {
  2612. try {
  2613. if (this.#initialized) {
  2614. return true;
  2615. }
  2616. if (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId) {
  2617. if (await this.#updateAuth()) {
  2618. this.#initialized = true;
  2619. return true;
  2620. }
  2621. return false;
  2622. }
  2623. const isVerified = await this.#verifyAuth(true);
  2624. if (isVerified) {
  2625. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  2626. this.#initialized = true;
  2627. return true;
  2628. }
  2629. GM_setValue('twitchAuth', null);
  2630. if (await this.#updateAuth()) {
  2631. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  2632. this.#initialized = true;
  2633. return true;
  2634. }
  2635. scripts_echoLog({}).error(i18n('initFailed', 'Twitch'));
  2636. return false;
  2637. } catch (error) {
  2638. throwError(error, 'Twitch.init');
  2639. return false;
  2640. }
  2641. }
  2642. async #verifyAuth(isFirst) {
  2643. try {
  2644. const logStatus = scripts_echoLog({
  2645. text: i18n('verifyingAuth', 'Twitch')
  2646. });
  2647. const {
  2648. result,
  2649. statusText,
  2650. status,
  2651. data
  2652. } = await tools_httpRequest({
  2653. url: 'https://gql.twitch.tv/gql',
  2654. method: 'POST',
  2655. dataType: 'json',
  2656. headers: {
  2657. Authorization: `OAuth ${this.#auth.authToken}`,
  2658. 'Client-Id': this.#auth.clientId
  2659. },
  2660. data: '[{"operationName":"FrontPageNew_User","variables":{"limit":1},"extensions":{"persistedQuery":{"version":1,' + '"sha256Hash":"64bd07a2cbaca80699d62636d966cf6395a5d14a1f0a14282067dcb28b13eb11"}}}]'
  2661. });
  2662. if (result === 'Success') {
  2663. if (data?.status === 200 && data.response?.[0]?.data?.currentUser) {
  2664. await this.#integrity(isFirst);
  2665. logStatus.success();
  2666. return true;
  2667. }
  2668. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2669. return false;
  2670. }
  2671. logStatus.error(`${result}:${statusText}(${status})`);
  2672. return false;
  2673. } catch (error) {
  2674. throwError(error, 'Twitch.verifyAuth');
  2675. return false;
  2676. }
  2677. }
  2678. async #integrity(isFirst = true, ct = '') {
  2679. try {
  2680. const logStatus = scripts_echoLog({
  2681. text: i18n('checkingTwitchIntegrity')
  2682. });
  2683. if (isFirst && (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId)) {
  2684. return await this.#updateAuth(false);
  2685. }
  2686. const {
  2687. result,
  2688. statusText,
  2689. status,
  2690. data
  2691. } = await tools_httpRequest({
  2692. url: 'https://gql.twitch.tv/integrity',
  2693. method: 'POST',
  2694. dataType: 'json',
  2695. anonymous: true,
  2696. headers: {
  2697. Origin: 'https://www.twitch.tv',
  2698. Referer: 'https://www.twitch.tv/',
  2699. Authorization: `OAuth ${this.#auth.authToken}`,
  2700. 'Client-Id': this.#auth.clientId,
  2701. 'Client-Version': this.#auth.clientVersion,
  2702. 'X-Device-Id': this.#auth.deviceId,
  2703. 'Client-Session-Id': this.#auth.clientSessionId,
  2704. 'x-kpsdk-ct': ct
  2705. }
  2706. });
  2707. if (result === 'Success') {
  2708. if (!ct && data?.responseHeaders?.['x-kpsdk-ct']) {
  2709. return await this.#integrity(isFirst, data.responseHeaders['x-kpsdk-ct']);
  2710. }
  2711. if (data?.status === 200 && data.response?.token) {
  2712. this.#integrityToken = data.response.token;
  2713. logStatus.success();
  2714. return true;
  2715. }
  2716. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2717. return false;
  2718. }
  2719. logStatus.error(`${result}:${statusText}(${status})`);
  2720. return false;
  2721. } catch (error) {
  2722. throwError(error, 'Twitch.integrity');
  2723. return false;
  2724. }
  2725. }
  2726. async #updateAuth(isFirst = true) {
  2727. try {
  2728. const logStatus = scripts_echoLog({
  2729. text: i18n('updatingAuth', 'Twitch')
  2730. });
  2731. return await new Promise(resolve => {
  2732. const newTab = GM_openInTab('https://www.twitch.tv/', {
  2733. active: true,
  2734. insert: true,
  2735. setParent: true
  2736. });
  2737. newTab.name = 'ATv4_twitchAuth';
  2738. newTab.onclose = async () => {
  2739. const auth = GM_getValue('twitchAuth');
  2740. if (auth) {
  2741. this.#auth = auth;
  2742. logStatus.success();
  2743. resolve(await this.#verifyAuth(isFirst));
  2744. } else {
  2745. logStatus.error('Error: Update twitch auth failed!');
  2746. resolve(false);
  2747. }
  2748. };
  2749. });
  2750. } catch (error) {
  2751. throwError(error, 'Twitch.updateAuth');
  2752. return false;
  2753. }
  2754. }
  2755. async #toggleChannel({
  2756. name,
  2757. doTask = true
  2758. }) {
  2759. try {
  2760. if (!doTask && this.whiteList.channels.includes(name)) {
  2761. scripts_echoLog({
  2762. type: 'whiteList',
  2763. text: 'Twitch.unfollowChannel',
  2764. id: name
  2765. });
  2766. return true;
  2767. }
  2768. const channelId = await this.#getChannelId(name);
  2769. if (!channelId) {
  2770. return false;
  2771. }
  2772. const logStatus = scripts_echoLog({
  2773. type: `${doTask ? '' : 'un'}followingTwitchChannel`,
  2774. text: name
  2775. });
  2776. const followData = `[{"operationName":"FollowButton_FollowUser","variables":{"input":{"disableNotifications":false,"targetID":"${channelId}` + '"}},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"800e7346bdf7e5278a3c1d3f21b2b56e2639928f86815677a7126b093b2fdd08"}}}]';
  2777. const unfollowData = `[{"operationName":"FollowButton_UnfollowUser","variables":{"input":{"targetID":"${channelId}"}},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"f7dae976ebf41c755ae2d758546bfd176b4eeb856656098bb40e0a672ca0d880"}}}]';
  2778. const {
  2779. result,
  2780. statusText,
  2781. status,
  2782. data
  2783. } = await tools_httpRequest({
  2784. url: 'https://gql.twitch.tv/gql',
  2785. method: 'POST',
  2786. dataType: 'json',
  2787. anonymous: true,
  2788. headers: {
  2789. Origin: 'https://www.twitch.tv',
  2790. Referer: 'https://www.twitch.tv/',
  2791. Authorization: `OAuth ${this.#auth.authToken}`,
  2792. 'Client-Id': this.#auth.clientId,
  2793. 'Client-Version': this.#auth.clientVersion,
  2794. 'X-Device-Id': this.#auth.deviceId,
  2795. 'Client-Session-Id': this.#auth.clientSessionId,
  2796. 'Client-Integrity': this.#integrityToken
  2797. },
  2798. data: doTask ? followData : unfollowData
  2799. });
  2800. if (result === 'Success') {
  2801. if (data?.status === 200 && data.response?.[0] && !data.response[0].errors) {
  2802. logStatus.success();
  2803. if (doTask) {
  2804. this.tasks.channels = unique([ ...this.tasks.channels, name ]);
  2805. }
  2806. return true;
  2807. }
  2808. logStatus.error(`Error:${data?.response?.[0].errors?.[0]?.message || `${data?.statusText}(${data?.status})`}`);
  2809. return false;
  2810. }
  2811. logStatus.error(`${result}:${statusText}(${status})`);
  2812. return false;
  2813. } catch (error) {
  2814. throwError(error, 'Twitch.toggleChannel');
  2815. return false;
  2816. }
  2817. }
  2818. async #getChannelId(name) {
  2819. try {
  2820. const logStatus = scripts_echoLog({
  2821. type: 'gettingTwitchChannelId',
  2822. text: name
  2823. });
  2824. const channelId = this.#cache[name];
  2825. if (channelId) {
  2826. logStatus.success();
  2827. return channelId;
  2828. }
  2829. const {
  2830. result,
  2831. statusText,
  2832. status,
  2833. data
  2834. } = await tools_httpRequest({
  2835. url: 'https://gql.twitch.tv/gql',
  2836. method: 'POST',
  2837. headers: {
  2838. Authorization: `OAuth ${this.#auth.authToken}`,
  2839. 'Client-Id': this.#auth.clientId
  2840. },
  2841. responseType: 'json',
  2842. data: `[{"operationName":"ActiveWatchParty","variables":{"channelLogin":"${name}"},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"4a8156c97b19e3a36e081cf6d6ddb5dbf9f9b02ae60e4d2ff26ed70aebc80a30"}}}]'
  2843. });
  2844. if (result === 'Success') {
  2845. if (data?.status === 200) {
  2846. const channelId = data.response?.[0]?.data?.user?.id;
  2847. if (channelId) {
  2848. this.#setCache(name, String(channelId));
  2849. logStatus.success();
  2850. return channelId;
  2851. }
  2852. logStatus.error(`Error:${data.statusText}(${data.status})`);
  2853. return false;
  2854. }
  2855. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2856. return false;
  2857. }
  2858. logStatus.error(`${result}:${statusText}(${status})`);
  2859. return false;
  2860. } catch (error) {
  2861. throwError(error, 'Twitch.getChannelId');
  2862. return false;
  2863. }
  2864. }
  2865. async toggle({
  2866. doTask = true,
  2867. channelLinks = []
  2868. }) {
  2869. try {
  2870. if (!this.#initialized) {
  2871. scripts_echoLog({
  2872. text: i18n('needInit')
  2873. });
  2874. return false;
  2875. }
  2876. const prom = [];
  2877. if (doTask && !globalOptions.doTask.twitch.channels || !doTask && !globalOptions.undoTask.twitch.channels) {
  2878. scripts_echoLog({
  2879. type: 'globalOptionsSkip',
  2880. text: 'twitch.channels'
  2881. });
  2882. } else {
  2883. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2]);
  2884. if (realChannels.length > 0) {
  2885. for (const channel of realChannels) {
  2886. prom.push(this.#toggleChannel({
  2887. name: channel,
  2888. doTask: doTask
  2889. }));
  2890. await delay(1e3);
  2891. }
  2892. }
  2893. }
  2894. return Promise.all(prom).then(() => true);
  2895. } catch (error) {
  2896. throwError(error, 'Twitch.toggle');
  2897. return false;
  2898. }
  2899. }
  2900. #setCache(name, id) {
  2901. try {
  2902. this.#cache[name] = id;
  2903. GM_setValue('twitchCache', this.#cache);
  2904. } catch (error) {
  2905. throwError(error, 'Twitch.setCache');
  2906. }
  2907. }
  2908. }
  2909. const social_Twitch = Twitch;
  2910. class Twitter extends social_Social {
  2911. tasks;
  2912. whiteList;
  2913. #verifyId = globalOptions.other.twitterVerifyId;
  2914. #auth = GM_getValue('twitterAuth') || {};
  2915. #cache = GM_getValue('twitterCache') || {};
  2916. #initialized = false;
  2917. constructor() {
  2918. super();
  2919. const defaultTasksTemplate = {
  2920. users: [],
  2921. retweets: [],
  2922. likes: []
  2923. };
  2924. this.tasks = defaultTasksTemplate;
  2925. this.whiteList = {
  2926. ...defaultTasksTemplate,
  2927. ...GM_getValue('whiteList')?.twitter || {}
  2928. };
  2929. }
  2930. async init() {
  2931. try {
  2932. if (this.#initialized) {
  2933. return true;
  2934. }
  2935. if (!this.#auth.ct0) {
  2936. if (await this.#updateAuth()) {
  2937. this.#initialized = true;
  2938. return true;
  2939. }
  2940. return false;
  2941. }
  2942. const isVerified = await this.#verifyAuth();
  2943. if (isVerified) {
  2944. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  2945. this.#initialized = true;
  2946. return true;
  2947. }
  2948. GM_setValue('twitterAuth', null);
  2949. if (await this.#updateAuth()) {
  2950. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  2951. this.#initialized = true;
  2952. return true;
  2953. }
  2954. scripts_echoLog({}).error(i18n('initFailed', 'Twitter'));
  2955. return false;
  2956. } catch (error) {
  2957. throwError(error, 'Twitter.init');
  2958. return false;
  2959. }
  2960. }
  2961. async #verifyAuth() {
  2962. try {
  2963. return await this.#toggleUser({
  2964. name: 'verify',
  2965. doTask: true,
  2966. verify: true
  2967. });
  2968. } catch (error) {
  2969. throwError(error, 'Twitter.verifyAuth');
  2970. return false;
  2971. }
  2972. }
  2973. async #updateAuth() {
  2974. try {
  2975. const logStatus = scripts_echoLog({
  2976. text: i18n('updatingAuth', 'Twitter')
  2977. });
  2978. return await new Promise(resolve => {
  2979. GM_cookie.list({
  2980. url: 'https://x.com/settings/account'
  2981. }, async (cookies, error) => {
  2982. if (!error) {
  2983. const [ ct0, isLogin ] = cookies.map(cookie => [ 'ct0', 'twid' ].includes(cookie.name) ? cookie.value : null).filter(cookie => cookie);
  2984. if (isLogin && ct0) {
  2985. GM_setValue('twitterAuth', {
  2986. ct0: ct0
  2987. });
  2988. this.#auth = {
  2989. ct0: ct0
  2990. };
  2991. logStatus.success();
  2992. resolve(await this.#verifyAuth());
  2993. } else {
  2994. logStatus.error(i18n('needLogin'));
  2995. resolve(false);
  2996. }
  2997. } else {
  2998. logStatus.error('Error: Update twitter auth failed!');
  2999. resolve(false);
  3000. }
  3001. });
  3002. });
  3003. } catch (error) {
  3004. throwError(error, 'Twitter.updateToken');
  3005. return false;
  3006. }
  3007. }
  3008. async #toggleUser({
  3009. name,
  3010. doTask = true,
  3011. verify = false,
  3012. retry = false
  3013. }) {
  3014. try {
  3015. if (!doTask && !verify && this.whiteList.users.includes(name)) {
  3016. scripts_echoLog({
  3017. type: 'whiteList',
  3018. text: 'Twitter.unfollowUser',
  3019. id: name
  3020. });
  3021. return true;
  3022. }
  3023. const userId = verify ? this.#verifyId : await this.userName2id(name);
  3024. if (!userId) {
  3025. return false;
  3026. }
  3027. const logStatus = verify ? scripts_echoLog({
  3028. text: i18n('verifyingAuth', 'Twitter')
  3029. }) : scripts_echoLog({
  3030. type: `${doTask ? '' : 'un'}followingTwitterUser`,
  3031. text: name
  3032. });
  3033. const {
  3034. result,
  3035. statusText,
  3036. status,
  3037. data
  3038. } = await tools_httpRequest({
  3039. url: `https://x.com/i/api/1.1/friendships/${doTask ? 'create' : 'destroy'}.json`,
  3040. method: 'POST',
  3041. headers: {
  3042. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3043. 'Content-Type': 'application/x-www-form-urlencoded',
  3044. 'x-csrf-token': this.#auth.ct0,
  3045. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3046. 'X-Twitter-Active-User': 'yes'
  3047. },
  3048. responseType: 'json',
  3049. data: $.param({
  3050. include_profile_interstitial_type: 1,
  3051. include_blocking: 1,
  3052. include_blocked_by: 1,
  3053. include_followed_by: 1,
  3054. include_want_retweets: 1,
  3055. include_mute_edge: 1,
  3056. include_can_dm: 1,
  3057. include_can_media_tag: 1,
  3058. skip_status: 1,
  3059. id: userId
  3060. })
  3061. });
  3062. if (result === 'Success') {
  3063. if (data?.status === 200) {
  3064. logStatus.success();
  3065. if (doTask && !verify) {
  3066. this.tasks.users = unique([ ...this.tasks.users, name ]);
  3067. }
  3068. return true;
  3069. }
  3070. if (verify && data?.status === 403) {
  3071. if (data.response?.errors?.[0]?.code === 158) {
  3072. logStatus.success();
  3073. return true;
  3074. }
  3075. if (data.response?.errors?.[0]?.code === 353 && !retry && data.responseHeaders?.['set-cookie']) {
  3076. this.#auth.ct0 = data.responseHeaders['set-cookie']?.find(cookie => cookie.includes('ct0='))?.split(';')?.at(0)?.split('=')?.at(-1) || this.#auth.ct0;
  3077. logStatus.warning(i18n('retry'));
  3078. return this.#toggleUser({
  3079. name: name,
  3080. doTask: doTask,
  3081. verify: verify,
  3082. retry: true
  3083. });
  3084. }
  3085. }
  3086. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3087. return false;
  3088. }
  3089. logStatus.error(`${result}:${statusText}(${status})`);
  3090. return false;
  3091. } catch (error) {
  3092. throwError(error, 'Twitter.toggleUser');
  3093. return false;
  3094. }
  3095. }
  3096. async userName2id(name) {
  3097. try {
  3098. const logStatus = scripts_echoLog({
  3099. type: 'gettingTwitterUserId',
  3100. text: name
  3101. });
  3102. const userId = this.#cache[name];
  3103. if (userId) {
  3104. logStatus.success();
  3105. return userId;
  3106. }
  3107. const {
  3108. result,
  3109. statusText,
  3110. status,
  3111. data
  3112. } = await tools_httpRequest({
  3113. 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`,
  3114. method: 'GET',
  3115. headers: {
  3116. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3117. 'content-type': 'application/json',
  3118. referer: `https://x.com/${name}`,
  3119. 'x-csrf-token': this.#auth.ct0,
  3120. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3121. 'X-Twitter-Active-User': 'yes'
  3122. },
  3123. responseType: 'json'
  3124. });
  3125. if (result === 'Success') {
  3126. if (data?.status === 200) {
  3127. let response = data.response || (typeof data.responseText === 'object' ? data.responseText : null);
  3128. if (!response) {
  3129. try {
  3130. response = JSON.parse(data.responseText);
  3131. } catch (error) {
  3132. response = null;
  3133. }
  3134. }
  3135. const userId = String(response?.data?.user?.result?.rest_id);
  3136. if (userId) {
  3137. this.#setCache(name, userId);
  3138. logStatus.success();
  3139. return userId;
  3140. }
  3141. logStatus.error(`Error:${data.statusText}(${data.status})`);
  3142. return false;
  3143. }
  3144. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3145. return false;
  3146. }
  3147. logStatus.error(`${result}:${statusText}(${status})`);
  3148. return false;
  3149. } catch (error) {
  3150. throwError(error, 'Twitter.getUserId');
  3151. return false;
  3152. }
  3153. }
  3154. async #toggleRetweet({
  3155. retweetId,
  3156. doTask = true
  3157. }) {
  3158. try {
  3159. if (!doTask && this.whiteList.retweets.includes(retweetId)) {
  3160. scripts_echoLog({
  3161. type: 'whiteList',
  3162. text: 'Twitter.unretweet',
  3163. id: retweetId
  3164. });
  3165. return true;
  3166. }
  3167. const logStatus = scripts_echoLog({
  3168. type: `${doTask ? '' : 'un'}retweetting`,
  3169. text: retweetId
  3170. });
  3171. const {
  3172. result,
  3173. statusText,
  3174. status,
  3175. data
  3176. } = await tools_httpRequest({
  3177. url: `https://x.com/i/api/graphql/${doTask ? 'ojPdsZsimiJrUGLR1sjUtA/CreateRetweet' : 'iQtK4dl5hBmXewYZuEOKVw/DeleteRetweet'}`,
  3178. method: 'POST',
  3179. headers: {
  3180. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3181. 'Content-Type': 'application/json',
  3182. 'x-csrf-token': this.#auth.ct0,
  3183. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3184. 'X-Twitter-Active-User': 'yes'
  3185. },
  3186. data: `{"variables":{"tweet_id":"${retweetId}","dark_request":false},"queryId":"${doTask ? 'ojPdsZsimiJrUGLR1sjUtA' : 'iQtK4dl5hBmXewYZuEOKVw'}"}`,
  3187. responseType: 'json'
  3188. });
  3189. if (result === 'Success') {
  3190. if (data?.status === 200 || data?.status === 403 && data.response?.errors?.[0]?.code === 327) {
  3191. logStatus.success();
  3192. if (doTask) {
  3193. this.tasks.retweets = unique([ ...this.tasks.retweets, retweetId ]);
  3194. }
  3195. return true;
  3196. }
  3197. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3198. return false;
  3199. }
  3200. logStatus.error(`${result}:${statusText}(${status})`);
  3201. return false;
  3202. } catch (error) {
  3203. throwError(error, 'Twitter.toggleRetweet');
  3204. return false;
  3205. }
  3206. }
  3207. async toggle({
  3208. doTask = true,
  3209. userLinks = [],
  3210. retweetLinks = []
  3211. }) {
  3212. try {
  3213. if (!this.#initialized) {
  3214. scripts_echoLog({
  3215. text: i18n('needInit')
  3216. });
  3217. return false;
  3218. }
  3219. const prom = [];
  3220. if (doTask && !globalOptions.doTask.twitter.users || !doTask && !globalOptions.undoTask.twitter.users) {
  3221. scripts_echoLog({
  3222. type: 'globalOptionsSkip',
  3223. text: 'twitter.users'
  3224. });
  3225. } else {
  3226. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/x\.com\/(.+)/)?.[1] || link.match(/https:\/\/twitter\.com\/(.+)/)?.[1]);
  3227. if (realUsers.length > 0) {
  3228. for (const user of realUsers) {
  3229. prom.push(this.#toggleUser({
  3230. name: user,
  3231. doTask: doTask
  3232. }));
  3233. await delay(1e3);
  3234. }
  3235. }
  3236. }
  3237. if (doTask && !globalOptions.doTask.twitter.retweets || !doTask && !globalOptions.undoTask.twitter.retweets) {
  3238. scripts_echoLog({
  3239. type: 'globalOptionsSkip',
  3240. text: 'twitter.retweets'
  3241. });
  3242. } else {
  3243. const realRetweets = this.getRealParams('retweets', retweetLinks, doTask, link => link.match(/https:\/\/x\.com\/.*?\/status\/([\d]+)/)?.[1] || link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1]);
  3244. if (realRetweets.length > 0) {
  3245. for (const retweet of realRetweets) {
  3246. prom.push(this.#toggleRetweet({
  3247. retweetId: retweet,
  3248. doTask: doTask
  3249. }));
  3250. await delay(1e3);
  3251. }
  3252. }
  3253. }
  3254. return Promise.all(prom).then(() => true);
  3255. } catch (error) {
  3256. throwError(error, 'Twitter.toggle');
  3257. return false;
  3258. }
  3259. }
  3260. #setCache(name, id) {
  3261. try {
  3262. this.#cache[name] = id;
  3263. GM_setValue('twitterCache', this.#cache);
  3264. } catch (error) {
  3265. throwError(error, 'Twitter.setCache');
  3266. }
  3267. }
  3268. }
  3269. const social_Twitter = Twitter;
  3270. class Vk extends social_Social {
  3271. tasks;
  3272. whiteList;
  3273. #username = '';
  3274. #cache = GM_getValue('vkCache') || {};
  3275. #initialized = false;
  3276. constructor() {
  3277. super();
  3278. const defaultTasksTemplate = {
  3279. names: []
  3280. };
  3281. this.tasks = defaultTasksTemplate;
  3282. this.whiteList = {
  3283. ...defaultTasksTemplate,
  3284. ...GM_getValue('whiteList')?.vk || {}
  3285. };
  3286. }
  3287. async init() {
  3288. try {
  3289. if (this.#initialized) {
  3290. return true;
  3291. }
  3292. const isVerified = await this.#verifyAuth();
  3293. if (isVerified) {
  3294. scripts_echoLog({}).success(i18n('initSuccess', 'Vk'));
  3295. this.#initialized = true;
  3296. return true;
  3297. }
  3298. scripts_echoLog({}).error(i18n('initFailed', 'Vk'));
  3299. return false;
  3300. } catch (error) {
  3301. throwError(error, 'Vk.init');
  3302. return false;
  3303. }
  3304. }
  3305. async #verifyAuth() {
  3306. try {
  3307. const logStatus = scripts_echoLog({
  3308. text: i18n('verifyAuth', 'Vk')
  3309. });
  3310. const {
  3311. result,
  3312. statusText,
  3313. status,
  3314. data
  3315. } = await tools_httpRequest({
  3316. url: 'https://vk.com/im',
  3317. method: 'GET'
  3318. });
  3319. if (result === 'Success') {
  3320. if (data?.finalUrl.includes('vk.com/login')) {
  3321. logStatus.error(`Error:${i18n('loginVk')}`, true);
  3322. return false;
  3323. }
  3324. if (data?.status === 200) {
  3325. this.#username = data.responseText.match(/TopNavBtn__profileLink" href="\/(.*?)"/)?.[1] || '';
  3326. logStatus.success();
  3327. return true;
  3328. }
  3329. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3330. return false;
  3331. }
  3332. logStatus.error(`${result}:${statusText}(${status})`);
  3333. return false;
  3334. } catch (error) {
  3335. throwError(error, 'Vk.verifyAuth');
  3336. return false;
  3337. }
  3338. }
  3339. async #toggleGroup(name, dataParam, doTask = true) {
  3340. try {
  3341. const logStatus = scripts_echoLog({
  3342. type: doTask ? 'joiningVkGroup' : 'leavingVkGroup',
  3343. text: name
  3344. });
  3345. if (dataParam.groupAct === 'enter' && !doTask || dataParam.groupAct === 'leave' && doTask) {
  3346. logStatus.success();
  3347. return true;
  3348. }
  3349. const reqData = {
  3350. act: doTask ? 'enter' : 'leave',
  3351. al: 1,
  3352. gid: dataParam.groupId,
  3353. hash: dataParam.groupHash
  3354. };
  3355. if (doTask) {
  3356. reqData.context = '_';
  3357. }
  3358. const {
  3359. result,
  3360. statusText,
  3361. status,
  3362. data
  3363. } = await tools_httpRequest({
  3364. url: 'https://vk.com/al_groups.php',
  3365. method: 'POST',
  3366. headers: {
  3367. origin: 'https://vk.com',
  3368. referer: `https://vk.com/${name}`,
  3369. 'content-type': 'application/x-www-form-urlencoded'
  3370. },
  3371. data: $.param(reqData)
  3372. });
  3373. if (result === 'Success') {
  3374. if (data?.status === 200) {
  3375. logStatus.success();
  3376. if (doTask) {
  3377. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3378. }
  3379. return true;
  3380. }
  3381. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3382. return false;
  3383. }
  3384. logStatus.error(`${result}:${statusText}(${status})`);
  3385. return false;
  3386. } catch (error) {
  3387. throwError(error, 'Vk.toggleGroup');
  3388. return false;
  3389. }
  3390. }
  3391. async #togglePublic(name, dataParam, doTask = true) {
  3392. try {
  3393. const logStatus = scripts_echoLog({
  3394. type: doTask ? 'joiningVkPublic' : 'leavingVkPublic',
  3395. text: name
  3396. });
  3397. if (dataParam.publicJoined && doTask || !dataParam.publicJoined && !doTask) {
  3398. logStatus.success();
  3399. return true;
  3400. }
  3401. const {
  3402. result,
  3403. statusText,
  3404. status,
  3405. data
  3406. } = await tools_httpRequest({
  3407. url: 'https://vk.com/al_public.php',
  3408. method: 'POST',
  3409. headers: {
  3410. origin: 'https://vk.com',
  3411. referer: `https://vk.com/${name}`,
  3412. 'content-type': 'application/x-www-form-urlencoded'
  3413. },
  3414. data: $.param({
  3415. act: doTask ? 'a_enter' : 'a_leave',
  3416. al: 1,
  3417. pid: dataParam.publicPid,
  3418. hash: dataParam.publicHash
  3419. })
  3420. });
  3421. if (result === 'Success') {
  3422. if (data?.status === 200) {
  3423. logStatus.success();
  3424. if (doTask) {
  3425. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3426. }
  3427. return true;
  3428. }
  3429. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3430. return false;
  3431. }
  3432. logStatus.error(`${result}:${statusText}(${status})`);
  3433. return false;
  3434. } catch (error) {
  3435. throwError(error, 'Vk.togglePublic');
  3436. return false;
  3437. }
  3438. }
  3439. async #toggleLikeWall(name, dataParam, doTask = true) {
  3440. try {
  3441. const logStatus = scripts_echoLog({
  3442. type: doTask ? 'likingVkPublic' : 'unlikingVkPublic',
  3443. text: name
  3444. });
  3445. const postData = {
  3446. act: 'a_set_reaction',
  3447. al: 1,
  3448. event_subtype: 'post_modal',
  3449. from: 'wall_page',
  3450. hash: dataParam.hash,
  3451. object: dataParam.object,
  3452. track_code: dataParam.trackCode,
  3453. wall: 2
  3454. };
  3455. if (doTask) {
  3456. postData.reaction_id = 0;
  3457. }
  3458. const {
  3459. result: resultR,
  3460. statusText: statusTextR,
  3461. status: statusR,
  3462. data: dataR
  3463. } = await tools_httpRequest({
  3464. url: 'https://vk.com/like.php?act=a_set_reaction',
  3465. method: 'POST',
  3466. headers: {
  3467. origin: 'https://vk.com',
  3468. referer: `https://vk.com/${name}`,
  3469. 'content-type': 'application/x-www-form-urlencoded'
  3470. },
  3471. data: $.param(postData)
  3472. });
  3473. if (resultR === 'Success') {
  3474. if (dataR?.status === 200) {
  3475. if (dataR.response?.payload?.[1]?.[1]?.like_my === true) {
  3476. logStatus.success();
  3477. return true;
  3478. }
  3479. }
  3480. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  3481. return false;
  3482. }
  3483. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  3484. return false;
  3485. } catch (error) {
  3486. throwError(error, 'Vk.sendWall');
  3487. return false;
  3488. }
  3489. }
  3490. async #sendWall(name) {
  3491. try {
  3492. const logStatus = scripts_echoLog({
  3493. type: 'sendingVkWall',
  3494. text: name
  3495. });
  3496. const {
  3497. result,
  3498. statusText,
  3499. status,
  3500. data
  3501. } = await tools_httpRequest({
  3502. url: 'https://vk.com/like.php',
  3503. method: 'POST',
  3504. headers: {
  3505. origin: 'https://vk.com',
  3506. referer: `https://vk.com/${name}`,
  3507. 'content-type': 'application/x-www-form-urlencoded'
  3508. },
  3509. data: $.param({
  3510. act: 'publish_box',
  3511. al: 1,
  3512. object: name
  3513. })
  3514. });
  3515. if (result === 'Success') {
  3516. if (data?.status === 200) {
  3517. const hash = data.responseText.match(/shHash:[\s]*'(.*?)'/)?.[1];
  3518. if (hash) {
  3519. const {
  3520. result: resultR,
  3521. statusText: statusTextR,
  3522. status: statusR,
  3523. data: dataR
  3524. } = await tools_httpRequest({
  3525. url: 'https://vk.com/like.php',
  3526. method: 'POST',
  3527. headers: {
  3528. origin: 'https://vk.com',
  3529. referer: `https://vk.com/${name}`,
  3530. 'content-type': 'application/x-www-form-urlencoded'
  3531. },
  3532. data: $.param({
  3533. Message: '',
  3534. act: 'a_do_publish',
  3535. al: 1,
  3536. close_comments: 0,
  3537. friends_only: 0,
  3538. from: 'box',
  3539. hash: hash,
  3540. list: '',
  3541. mark_as_ads: 0,
  3542. mute_notifications: 0,
  3543. object: name,
  3544. ret_data: 1,
  3545. to: 0
  3546. })
  3547. });
  3548. if (resultR === 'Success') {
  3549. if (dataR?.status === 200) {
  3550. const jsonData = JSON.parse(dataR.responseText?.replace('\x3c!--', '') || '{}');
  3551. if (jsonData?.payload?.[1]?.[1]?.share_my === true) {
  3552. logStatus.success();
  3553. const postId = String(jsonData?.payload?.[1]?.[1]?.post_id);
  3554. const ownerId = String(jsonData?.payload?.[1]?.[1]?.owner_id);
  3555. if (postId && ownerId) {
  3556. this.#setCache(name, `${ownerId}_${postId}`);
  3557. }
  3558. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3559. return true;
  3560. }
  3561. }
  3562. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  3563. return false;
  3564. }
  3565. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  3566. return false;
  3567. }
  3568. logStatus.error('Error: Get "hash" failed');
  3569. return false;
  3570. }
  3571. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3572. return false;
  3573. }
  3574. logStatus.error(`${result}:${statusText}(${status})`);
  3575. return false;
  3576. } catch (error) {
  3577. throwError(error, 'Vk.sendWall');
  3578. return false;
  3579. }
  3580. }
  3581. async #deleteWall(name, dataParams) {
  3582. try {
  3583. const logStatus = scripts_echoLog({
  3584. type: 'deletingVkWall',
  3585. text: name
  3586. });
  3587. const {
  3588. result,
  3589. statusText,
  3590. status,
  3591. data
  3592. } = await tools_httpRequest({
  3593. url: 'https://vk.com/al_wall.php?act=delete',
  3594. method: 'POST',
  3595. headers: {
  3596. origin: 'https://vk.com',
  3597. referer: `https://vk.com/${this.#username}?w=wall${this.#cache[name]}%2Fall`,
  3598. 'content-type': 'application/x-www-form-urlencoded'
  3599. },
  3600. data: $.param({
  3601. act: 'delete',
  3602. al: 1,
  3603. confirm: 0,
  3604. from: 'wkview',
  3605. hash: dataParams.wallHash,
  3606. post: this.#cache[name]
  3607. })
  3608. });
  3609. if (result === 'Success') {
  3610. if (data?.status === 200) {
  3611. const jsonData = JSON.parse(data.responseText?.replace('\x3c!--', '') || '{}');
  3612. if (jsonData?.payload?.[1]?.[1]) {
  3613. logStatus.success();
  3614. return true;
  3615. }
  3616. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3617. return false;
  3618. }
  3619. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3620. return false;
  3621. }
  3622. logStatus.error(`${result}:${statusText}(${status})`);
  3623. return false;
  3624. } catch (error) {
  3625. throwError(error, 'Vk.deleteWall');
  3626. return false;
  3627. }
  3628. }
  3629. async #getId(name, doTask) {
  3630. try {
  3631. let url = `https://vk.com/${name}`;
  3632. if (/^wall-/.test(name)) {
  3633. if (doTask) {
  3634. return {
  3635. type: 'sendWall'
  3636. };
  3637. }
  3638. if (!this.#cache[name]) {
  3639. return {
  3640. type: 'unSupport'
  3641. };
  3642. }
  3643. url = `https://vk.com/${this.#username}?w=wall${this.#cache[name]}`;
  3644. }
  3645. const logStatus = scripts_echoLog({
  3646. type: 'gettingVkId',
  3647. text: name
  3648. });
  3649. const {
  3650. result,
  3651. statusText,
  3652. status,
  3653. data
  3654. } = await tools_httpRequest({
  3655. url: url,
  3656. method: 'GET'
  3657. });
  3658. if (result === 'Success') {
  3659. if (data?.status === 200) {
  3660. const [ , groupAct, groupId, , groupHash ] = data.responseText.match(/Groups.(enter|leave)\(.*?,.*?([\d]+?), (&#39;|')(.*?)(&#39;|')/) || [];
  3661. const publicHash = data.responseText.match(/"enterHash":"(.*?)"/)?.[1];
  3662. const publicPid = data.responseText.match(/"public_id":([\d]+?),/)?.[1];
  3663. const publicJoined = !data.responseText.includes('Public.subscribe');
  3664. if (groupAct && groupId && groupHash) {
  3665. logStatus.success();
  3666. return {
  3667. groupAct: groupAct,
  3668. groupId: groupId,
  3669. groupHash: groupHash,
  3670. type: 'group'
  3671. };
  3672. } else if (publicHash && publicPid) {
  3673. logStatus.success();
  3674. return {
  3675. publicHash: publicHash,
  3676. publicPid: publicPid,
  3677. publicJoined: publicJoined,
  3678. type: 'public'
  3679. };
  3680. } else if (name.includes('action=like')) {
  3681. const hash = data.responseText.match(/data-reaction-hash="(.*?)"/)?.[1];
  3682. const trackCode = data.responseText.match(/data-post-track-code="(.*?)"/)?.[1];
  3683. const object = name.match(/wall-[\w_]+/)?.[0];
  3684. if (hash && trackCode && object) {
  3685. logStatus.success();
  3686. return {
  3687. type: 'likeWall',
  3688. hash: hash,
  3689. trackCode: trackCode,
  3690. object: object
  3691. };
  3692. }
  3693. } else if (data.responseText.includes('wall.deletePost') && !doTask) {
  3694. const wallHash = data.responseText.match(/wall\.deletePost\(this, '.*?', '(.*?)'\)/)?.[1];
  3695. if (wallHash) {
  3696. logStatus.success();
  3697. return {
  3698. type: 'deleteWall',
  3699. wallHash: wallHash
  3700. };
  3701. }
  3702. } else if (name.includes('wall') && doTask) {
  3703. logStatus.success();
  3704. return {
  3705. type: 'sendWall'
  3706. };
  3707. }
  3708. logStatus.error('Error: Parameters not found!');
  3709. return false;
  3710. }
  3711. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3712. return false;
  3713. }
  3714. logStatus.error(`${result}:${statusText}(${status})`);
  3715. return false;
  3716. } catch (error) {
  3717. throwError(error, 'Vk.getId');
  3718. return false;
  3719. }
  3720. }
  3721. async #toggleVk({
  3722. name,
  3723. doTask = true
  3724. }) {
  3725. try {
  3726. if (!doTask && this.whiteList.names.includes(name)) {
  3727. scripts_echoLog({
  3728. type: 'whiteList',
  3729. text: 'Vk.undoTask',
  3730. id: name
  3731. });
  3732. return true;
  3733. }
  3734. const formatName = name.replace(/\/$/, '');
  3735. const data = await this.#getId(formatName, doTask);
  3736. if (!data) {
  3737. return false;
  3738. }
  3739. switch (data.type) {
  3740. case 'group':
  3741. return await this.#toggleGroup(formatName, data, doTask);
  3742.  
  3743. case 'public':
  3744. return await this.#togglePublic(formatName, data, doTask);
  3745.  
  3746. case 'likeWall':
  3747. return await this.#toggleLikeWall(formatName, data, doTask);
  3748.  
  3749. case 'sendWall':
  3750. return doTask ? await this.#sendWall(formatName) : true;
  3751.  
  3752. case 'deleteWall':
  3753. return doTask ? true : await this.#deleteWall(formatName, data);
  3754.  
  3755. default:
  3756. return false;
  3757. }
  3758. } catch (error) {
  3759. throwError(error, 'Vk.toggleVk');
  3760. return false;
  3761. }
  3762. }
  3763. async toggle({
  3764. doTask = true,
  3765. nameLinks = []
  3766. }) {
  3767. try {
  3768. if (!this.#initialized) {
  3769. scripts_echoLog({
  3770. text: i18n('needInit')
  3771. });
  3772. return false;
  3773. }
  3774. const prom = [];
  3775. if (doTask && !globalOptions.doTask.vk.names || !doTask && !globalOptions.undoTask.vk.names) {
  3776. scripts_echoLog({
  3777. type: 'globalOptionsSkip',
  3778. text: 'vk.names'
  3779. });
  3780. } else {
  3781. const realNames = this.getRealParams('names', nameLinks, doTask, link => link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1]);
  3782. if (realNames.length > 0) {
  3783. for (const name of realNames) {
  3784. prom.push(this.#toggleVk({
  3785. name: name,
  3786. doTask: doTask
  3787. }));
  3788. await delay(1e3);
  3789. }
  3790. }
  3791. }
  3792. return Promise.all(prom).then(() => true);
  3793. } catch (error) {
  3794. throwError(error, 'Vk.toggle');
  3795. return false;
  3796. }
  3797. }
  3798. #setCache(name, postId) {
  3799. try {
  3800. this.#cache[name] = postId;
  3801. GM_setValue('vkCache', this.#cache);
  3802. } catch (error) {
  3803. throwError(error, 'Vk.setCache');
  3804. }
  3805. }
  3806. }
  3807. const social_Vk = Vk;
  3808. const getInfo = async function(link, type) {
  3809. try {
  3810. const logStatus = scripts_echoLog({
  3811. text: i18n('gettingYtbToken')
  3812. });
  3813. const {
  3814. result,
  3815. statusText,
  3816. status,
  3817. data
  3818. } = await tools_httpRequest({
  3819. url: link,
  3820. method: 'GET'
  3821. });
  3822. if (result === 'Success') {
  3823. if (data?.status === 200) {
  3824. if (data.responseText.includes('accounts.google.com/ServiceLogin?service=youtube')) {
  3825. logStatus.error(`Error:${i18n('loginYtb')}`, true);
  3826. return {
  3827. needLogin: true
  3828. };
  3829. }
  3830. const apiKey = data.responseText.match(/"INNERTUBE_API_KEY":"(.*?)"/)?.[1];
  3831. const context = (data.responseText.match(/\(\{"INNERTUBE_CONTEXT":([\w\W]*?)\}\)/) || data.responseText.match(/"INNERTUBE_CONTEXT":([\w\W]*?\}),"INNERTUBE/))?.[1] || '{}';
  3832. const {
  3833. client,
  3834. request
  3835. } = JSON.parse(context);
  3836. if (apiKey && client && request) {
  3837. client.hl = 'en';
  3838. if (type === 'channel') {
  3839. const channelId = data.responseText.match(/"channelId":"(.+?)"/)?.[1];
  3840. if (channelId) {
  3841. logStatus.success();
  3842. return {
  3843. params: {
  3844. apiKey: apiKey,
  3845. client: client,
  3846. request: request,
  3847. channelId: channelId
  3848. }
  3849. };
  3850. }
  3851. logStatus.error('Error: Get "channelId" failed!');
  3852. return {};
  3853. } else if (type === 'likeVideo') {
  3854. const videoId = data.responseText.match(/<link rel="shortlinkUrl" href="https:\/\/youtu\.be\/(.*?)">/)?.[1];
  3855. const likeParams = data.responseText.match(/"likeParams":"(.*?)"/)?.[1];
  3856. if (videoId) {
  3857. logStatus.success();
  3858. return {
  3859. params: {
  3860. apiKey: apiKey,
  3861. client: client,
  3862. request: request,
  3863. videoId: videoId,
  3864. likeParams: likeParams
  3865. }
  3866. };
  3867. }
  3868. logStatus.error('Error: Get "videoId" failed!');
  3869. return {};
  3870. }
  3871. logStatus.error('Error: Unknown type');
  3872. return {};
  3873. }
  3874. logStatus.error('Error: Parameter "apiKey" not found!');
  3875. return {};
  3876. }
  3877. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3878. return {};
  3879. }
  3880. logStatus.error(`${result}:${statusText}(${status})`);
  3881. return {};
  3882. } catch (error) {
  3883. throwError(error, 'Youtube.getInfo');
  3884. return {};
  3885. }
  3886. };
  3887. class Youtube extends social_Social {
  3888. tasks;
  3889. whiteList;
  3890. #auth = GM_getValue('youtubeAuth') || {};
  3891. #initialized = false;
  3892. #verifyChannel = `https://www.youtube.com/channel/${globalOptions.other.youtubeVerifyChannel}`;
  3893. constructor() {
  3894. super();
  3895. const defaultTasksTemplate = {
  3896. channels: [],
  3897. likes: []
  3898. };
  3899. this.tasks = defaultTasksTemplate;
  3900. this.whiteList = {
  3901. ...defaultTasksTemplate,
  3902. ...GM_getValue('whiteList')?.youtube || {}
  3903. };
  3904. }
  3905. async init() {
  3906. try {
  3907. if (this.#initialized) {
  3908. return true;
  3909. }
  3910. if (!this.#auth.PAPISID) {
  3911. if (await this.#updateAuth()) {
  3912. this.#initialized = true;
  3913. return true;
  3914. }
  3915. return false;
  3916. }
  3917. const isVerified = await this.#verifyAuth();
  3918. if (isVerified) {
  3919. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  3920. this.#initialized = true;
  3921. return true;
  3922. }
  3923. GM_setValue('youtubeAuth', null);
  3924. if (await this.#updateAuth()) {
  3925. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  3926. this.#initialized = true;
  3927. return true;
  3928. }
  3929. scripts_echoLog({}).error(i18n('initFailed', 'Youtube'));
  3930. return false;
  3931. } catch (error) {
  3932. throwError(error, 'Youtube.init');
  3933. return false;
  3934. }
  3935. }
  3936. async #verifyAuth() {
  3937. try {
  3938. return await this.#toggleChannel({
  3939. link: this.#verifyChannel,
  3940. doTask: true,
  3941. verify: true
  3942. });
  3943. } catch (error) {
  3944. throwError(error, 'Youtube.verifyAuth');
  3945. return false;
  3946. }
  3947. }
  3948. async #updateAuth() {
  3949. try {
  3950. const logStatus = scripts_echoLog({
  3951. text: i18n('updatingAuth', 'Youtube')
  3952. });
  3953. return await new Promise(resolve => {
  3954. GM_cookie.list({
  3955. url: 'https://www.youtube.com/@YouTube'
  3956. }, async (cookies, error) => {
  3957. if (!error) {
  3958. const PAPISID = cookies.find(cookie => cookie.name === '__Secure-3PAPISID')?.value;
  3959. if (PAPISID) {
  3960. GM_setValue('youtubeAuth', {
  3961. PAPISID: PAPISID
  3962. });
  3963. this.#auth = {
  3964. PAPISID: PAPISID
  3965. };
  3966. logStatus.success();
  3967. resolve(await this.#verifyAuth());
  3968. } else {
  3969. logStatus.error(i18n('needLogin'));
  3970. resolve(false);
  3971. }
  3972. } else {
  3973. logStatus.error('Error: Update youtube auth failed!');
  3974. resolve(false);
  3975. }
  3976. });
  3977. });
  3978. } catch (error) {
  3979. throwError(error, 'Youtube.updateAuth');
  3980. return false;
  3981. }
  3982. }
  3983. #getInfo(link, type) {
  3984. return getInfo(link, type);
  3985. }
  3986. async #toggleChannel({
  3987. link,
  3988. doTask = true,
  3989. verify = false
  3990. }) {
  3991. try {
  3992. const {
  3993. params,
  3994. needLogin
  3995. } = await this.#getInfo(link, 'channel');
  3996. const {
  3997. apiKey,
  3998. client,
  3999. request,
  4000. channelId
  4001. } = params || {};
  4002. if (needLogin) {
  4003. scripts_echoLog({
  4004. html: i18n('loginYtb')
  4005. });
  4006. return false;
  4007. }
  4008. if (!(apiKey && client && request && channelId)) {
  4009. scripts_echoLog({
  4010. text: '"getYtbToken" failed'
  4011. });
  4012. return false;
  4013. }
  4014. if (!doTask && !verify && this.whiteList.channels.includes(channelId)) {
  4015. scripts_echoLog({
  4016. type: 'whiteList',
  4017. text: 'Youtube.unfollowChannel',
  4018. id: channelId
  4019. });
  4020. return true;
  4021. }
  4022. const logStatus = verify ? scripts_echoLog({
  4023. text: i18n('verifyingAuth', 'Youtube')
  4024. }) : scripts_echoLog({
  4025. type: doTask ? 'followingYtbChannel' : 'unfollowingYtbChannel',
  4026. text: channelId
  4027. });
  4028. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  4029. const {
  4030. result,
  4031. statusText,
  4032. status,
  4033. data
  4034. } = await tools_httpRequest({
  4035. url: `https://www.youtube.com/youtubei/v1/subscription/${doTask ? '' : 'un'}subscribe?key=${apiKey}&prettyPrint=false`,
  4036. method: 'POST',
  4037. headers: {
  4038. origin: 'https://www.youtube.com',
  4039. referer: `https://www.youtube.com/channel/${channelId}`,
  4040. 'content-type': 'application/json',
  4041. 'x-goog-authuser': '0',
  4042. 'x-goog-visitor-id': client?.visitorData,
  4043. 'x-origin': 'https://www.youtube.com',
  4044. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  4045. },
  4046. data: JSON.stringify({
  4047. context: {
  4048. client: client,
  4049. request: {
  4050. sessionId: request?.sessionId,
  4051. internalExperimentFlags: [],
  4052. consistencyTokenJars: []
  4053. },
  4054. user: {}
  4055. },
  4056. channelIds: [ channelId ],
  4057. params: doTask ? 'EgIIAhgA' : 'CgIIAhgA'
  4058. })
  4059. });
  4060. if (result === 'Success') {
  4061. if (data?.status === 200) {
  4062. if (doTask && (/"subscribed":true/.test(data.responseText) || data.responseText.includes('The subscription already exists')) || !doTask && /"subscribed":false/.test(data.responseText)) {
  4063. logStatus.success();
  4064. if (doTask && !verify) {
  4065. this.tasks.channels = unique([ ...this.tasks.channels, link ]);
  4066. }
  4067. return true;
  4068. }
  4069. if (verify && data.responseText.includes('You may not subscribe to yourself')) {
  4070. logStatus.success();
  4071. return true;
  4072. }
  4073. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4074. return false;
  4075. }
  4076. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4077. return false;
  4078. }
  4079. logStatus.error(`${result}:${statusText}(${status})`);
  4080. return false;
  4081. } catch (error) {
  4082. throwError(error, 'Youtube.toggleChannel');
  4083. return false;
  4084. }
  4085. }
  4086. async #toggleLikeVideo({
  4087. link,
  4088. doTask = true
  4089. }) {
  4090. try {
  4091. const {
  4092. params,
  4093. needLogin
  4094. } = await this.#getInfo(link, 'likeVideo');
  4095. const {
  4096. apiKey,
  4097. client,
  4098. request,
  4099. videoId,
  4100. likeParams
  4101. } = params || {};
  4102. if (needLogin) {
  4103. scripts_echoLog({
  4104. html: `${i18n('loginYtb')}`
  4105. });
  4106. return false;
  4107. }
  4108. if (!(apiKey && client && request && videoId && likeParams)) {
  4109. scripts_echoLog({
  4110. text: '"getYtbToken" failed'
  4111. });
  4112. return false;
  4113. }
  4114. if (!doTask && this.whiteList.likes.includes(videoId)) {
  4115. scripts_echoLog({
  4116. type: 'whiteList',
  4117. text: 'Youtube.unlikeVideo',
  4118. id: videoId
  4119. });
  4120. return true;
  4121. }
  4122. const logStatus = scripts_echoLog({
  4123. type: doTask ? 'likingYtbVideo' : 'unlikingYtbVideo',
  4124. text: videoId
  4125. });
  4126. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  4127. const likeVideoData = {
  4128. context: {
  4129. client: client,
  4130. request: {
  4131. sessionId: request.sessionId,
  4132. internalExperimentFlags: [],
  4133. consistencyTokenJars: []
  4134. },
  4135. user: {}
  4136. },
  4137. target: {
  4138. videoId: videoId
  4139. }
  4140. };
  4141. if (doTask) {
  4142. if (likeParams) {
  4143. likeVideoData.params = likeParams;
  4144. } else {
  4145. logStatus.error('Empty likeParams');
  4146. return false;
  4147. }
  4148. }
  4149. const {
  4150. result,
  4151. statusText,
  4152. status,
  4153. data
  4154. } = await tools_httpRequest({
  4155. url: `https://www.youtube.com/youtubei/v1/like/${doTask ? '' : 'remove'}like?key=${apiKey}`,
  4156. method: 'POST',
  4157. headers: {
  4158. origin: 'https://www.youtube.com',
  4159. referer: `https://www.youtube.com/watch?v=${videoId}`,
  4160. 'content-type': 'application/json',
  4161. 'x-goog-authuser': '0',
  4162. 'x-goog-visitor-id': client.visitorData,
  4163. 'x-origin': 'https://www.youtube.com',
  4164. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  4165. },
  4166. data: JSON.stringify(likeVideoData)
  4167. });
  4168. if (result === 'Success') {
  4169. if (data?.status === 200) {
  4170. if (doTask && data.responseText.includes('Added to Liked videos') || !doTask && (data.responseText.includes('Removed from Liked videos') || data.responseText.includes('Dislike removed'))) {
  4171. logStatus.success();
  4172. if (doTask) {
  4173. this.tasks.likes = unique([ ...this.tasks.likes, link ]);
  4174. }
  4175. return true;
  4176. }
  4177. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4178. return false;
  4179. }
  4180. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4181. return false;
  4182. }
  4183. logStatus.error(`${result}:${statusText}(${status})`);
  4184. return false;
  4185. } catch (error) {
  4186. throwError(error, 'Youtube.toggleLikeVideo');
  4187. return false;
  4188. }
  4189. }
  4190. async toggle({
  4191. doTask = true,
  4192. channelLinks = [],
  4193. videoLinks = []
  4194. }) {
  4195. try {
  4196. if (!this.#initialized) {
  4197. scripts_echoLog({
  4198. text: i18n('needInit')
  4199. });
  4200. return false;
  4201. }
  4202. const prom = [];
  4203. if (doTask && !globalOptions.doTask.youtube.channels || !doTask && !globalOptions.undoTask.youtube.channels) {
  4204. scripts_echoLog({
  4205. type: 'globalOptionsSkip',
  4206. text: 'youtube.channels'
  4207. });
  4208. } else {
  4209. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => {
  4210. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4211. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4212. }
  4213. return link;
  4214. });
  4215. if (realChannels.length > 0) {
  4216. for (const channel of realChannels) {
  4217. prom.push(this.#toggleChannel({
  4218. link: channel,
  4219. doTask: doTask
  4220. }));
  4221. await delay(1e3);
  4222. }
  4223. }
  4224. }
  4225. if (doTask && !globalOptions.doTask.youtube.likes || !doTask && !globalOptions.undoTask.youtube.likes) {
  4226. scripts_echoLog({
  4227. type: 'globalOptionsSkip',
  4228. text: 'youtube.likes'
  4229. });
  4230. } else {
  4231. const realLikes = this.getRealParams('likes', videoLinks, doTask, link => {
  4232. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4233. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4234. }
  4235. return link;
  4236. });
  4237. if (realLikes.length > 0) {
  4238. for (const video of realLikes) {
  4239. prom.push(this.#toggleLikeVideo({
  4240. link: video,
  4241. doTask: doTask
  4242. }));
  4243. await delay(1e3);
  4244. }
  4245. }
  4246. }
  4247. return Promise.all(prom).then(() => true);
  4248. } catch (error) {
  4249. throwError(error, 'Youtube.toggle');
  4250. return false;
  4251. }
  4252. }
  4253. }
  4254. class SteamASF {
  4255. #asfOptions;
  4256. #botName = 'asf';
  4257. #groupInfo;
  4258. async init() {
  4259. try {
  4260. const asfCommandsUrl = new URL('/Api/Command/', globalOptions.ASF.AsfIpcUrl);
  4261. this.#asfOptions = {
  4262. url: asfCommandsUrl.href,
  4263. method: 'POST',
  4264. responseType: 'json',
  4265. headers: {
  4266. accept: 'application/json',
  4267. 'Content-Type': 'application/json',
  4268. Host: asfCommandsUrl.host,
  4269. Origin: asfCommandsUrl.origin,
  4270. Referer: asfCommandsUrl.href,
  4271. Authentication: globalOptions.ASF.AsfIpcPassword
  4272. }
  4273. };
  4274. if (globalOptions.ASF.AsfBotname) {
  4275. this.#botName = globalOptions.ASF.AsfBotname;
  4276. }
  4277. const logStatus = scripts_echoLog({
  4278. text: i18n('initingASF')
  4279. });
  4280. const {
  4281. result,
  4282. statusText,
  4283. status,
  4284. data
  4285. } = await tools_httpRequest({
  4286. ...this.#asfOptions,
  4287. data: '{"Command":"!stats"}'
  4288. });
  4289. if (result === 'Success') {
  4290. if (data?.response?.Success === true && data.response.Message === 'OK' && data.response.Result) {
  4291. logStatus.success();
  4292. return true;
  4293. }
  4294. if (data?.response?.Result || data?.response?.Message) {
  4295. logStatus.error(data?.response?.Result || data.response.Message);
  4296. return false;
  4297. }
  4298. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4299. return false;
  4300. }
  4301. logStatus.error(`${result}:${statusText}(${status})`);
  4302. return false;
  4303. } catch (error) {
  4304. throwError(error, 'SteamASF.init');
  4305. return false;
  4306. }
  4307. }
  4308. async joinGroup(groupName) {
  4309. try {
  4310. const logStatus = scripts_echoLog({
  4311. type: 'joiningSteamGroup',
  4312. text: groupName
  4313. });
  4314. const {
  4315. result,
  4316. statusText,
  4317. status,
  4318. data
  4319. } = await tools_httpRequest({
  4320. ...this.#asfOptions,
  4321. data: JSON.stringify({
  4322. Command: `!JOINGROUP ${this.#botName} ${groupName}`
  4323. })
  4324. });
  4325. if (result === 'Success') {
  4326. if (data?.status === 200 && [ '已加入', '已申请', 'Joined', 'Applied', 'Присоединился', 'costs' ].find(text => data.response?.Result?.includes(text))) {
  4327. logStatus.success();
  4328. return true;
  4329. }
  4330. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4331. return false;
  4332. }
  4333. logStatus.error(`${result}:${statusText}(${status})`);
  4334. return false;
  4335. } catch (error) {
  4336. throwError(error, 'SteamASF.joinGroup');
  4337. return false;
  4338. }
  4339. }
  4340. async leaveGroup(groupName) {
  4341. try {
  4342. if (!this.#groupInfo) {
  4343. if (!await this.#getGroupId()) {
  4344. return false;
  4345. }
  4346. }
  4347. const groupId = await this.#groupInfo[groupName];
  4348. if (!groupId) {
  4349. return false;
  4350. }
  4351. const logStatus = scripts_echoLog({
  4352. type: 'leavingSteamGroup',
  4353. text: groupName
  4354. });
  4355. const {
  4356. result,
  4357. statusText,
  4358. status,
  4359. data
  4360. } = await tools_httpRequest({
  4361. ...this.#asfOptions,
  4362. data: JSON.stringify({
  4363. Command: `!LEAVEGROUP ${this.#botName} ${groupId}`
  4364. })
  4365. });
  4366. if (result === 'Success') {
  4367. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4368. logStatus.success();
  4369. return true;
  4370. }
  4371. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4372. return false;
  4373. }
  4374. logStatus.error(`${result}:${statusText}(${status})`);
  4375. return false;
  4376. } catch (error) {
  4377. throwError(error, 'SteamASF.leaveGroup');
  4378. return false;
  4379. }
  4380. }
  4381. async #getGroupId() {
  4382. try {
  4383. const logStatus = scripts_echoLog({
  4384. type: 'gettingSteamGroupId',
  4385. text: 'All'
  4386. });
  4387. const {
  4388. result,
  4389. statusText,
  4390. status,
  4391. data
  4392. } = await tools_httpRequest({
  4393. ...this.#asfOptions,
  4394. data: JSON.stringify({
  4395. Command: `!GROUPLIST ${this.#botName}`
  4396. })
  4397. });
  4398. if (result === 'Success') {
  4399. if (data?.status === 200 && data.response?.Result?.includes('|')) {
  4400. this.#groupInfo = Object.fromEntries(data.response.Result.split('\n').map(line => {
  4401. const [ , name, id ] = line.trim().split('|');
  4402. if (name && id) {
  4403. return [ name, id ];
  4404. }
  4405. return null;
  4406. }).filter(ele => ele));
  4407. logStatus.success();
  4408. return true;
  4409. }
  4410. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4411. return false;
  4412. }
  4413. logStatus.error(`${result}:${statusText}(${status})`);
  4414. return false;
  4415. } catch (error) {
  4416. throwError(error, 'SteamASF.getGroupID');
  4417. return false;
  4418. }
  4419. }
  4420. async addToWishlist(gameId) {
  4421. try {
  4422. const logStatus = scripts_echoLog({
  4423. type: 'addingToWishlist',
  4424. text: gameId
  4425. });
  4426. if ((await this.#checkGame(gameId)).wishlist === true) {
  4427. logStatus.success();
  4428. return true;
  4429. }
  4430. const {
  4431. result,
  4432. statusText,
  4433. status,
  4434. data
  4435. } = await tools_httpRequest({
  4436. ...this.#asfOptions,
  4437. data: JSON.stringify({
  4438. Command: `!ADDWISHLIST ${this.#botName} ${gameId}`
  4439. })
  4440. });
  4441. if (result === 'Success') {
  4442. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4443. logStatus.success();
  4444. return true;
  4445. }
  4446. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4447. return false;
  4448. }
  4449. logStatus.error(`${result}:${statusText}(${status})`);
  4450. return false;
  4451. } catch (error) {
  4452. throwError(error, 'SteamASF.addToWishlist');
  4453. return false;
  4454. }
  4455. }
  4456. async removeFromWishlist(gameId) {
  4457. try {
  4458. const logStatus = scripts_echoLog({
  4459. type: 'removingFromWishlist',
  4460. text: gameId
  4461. });
  4462. if ((await this.#checkGame(gameId)).wishlist === false) {
  4463. logStatus.success();
  4464. return true;
  4465. }
  4466. const {
  4467. result,
  4468. statusText,
  4469. status,
  4470. data
  4471. } = await tools_httpRequest({
  4472. ...this.#asfOptions,
  4473. data: JSON.stringify({
  4474. Command: `!REMOVEWISHLIST ${this.#botName} ${gameId}`
  4475. })
  4476. });
  4477. if (result === 'Success') {
  4478. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4479. logStatus.success();
  4480. return true;
  4481. }
  4482. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4483. return false;
  4484. }
  4485. logStatus.error(`${result}:${statusText}(${status})`);
  4486. return false;
  4487. } catch (error) {
  4488. throwError(error, 'SteamASF.removeFromWishlist');
  4489. return false;
  4490. }
  4491. }
  4492. async toggleFollowGame(gameId, doTask) {
  4493. try {
  4494. const logStatus = scripts_echoLog({
  4495. type: `${doTask ? '' : 'un'}followingGame`,
  4496. text: gameId
  4497. });
  4498. if (doTask && (await this.#checkGame(gameId)).followed === true || !doTask && (await this.#checkGame(gameId)).followed === false) {
  4499. logStatus.success();
  4500. return true;
  4501. }
  4502. const {
  4503. result,
  4504. statusText,
  4505. status,
  4506. data
  4507. } = await tools_httpRequest({
  4508. ...this.#asfOptions,
  4509. data: JSON.stringify({
  4510. Command: `!${doTask ? '' : 'UN'}FOLLOWGAME ${this.#botName} ${gameId}`
  4511. })
  4512. });
  4513. if (result === 'Success') {
  4514. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4515. logStatus.success();
  4516. return true;
  4517. }
  4518. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4519. return false;
  4520. }
  4521. logStatus.error(`${result}:${statusText}(${status})`);
  4522. return false;
  4523. } catch (error) {
  4524. throwError(error, 'SteamASF.toggleFollowGame');
  4525. return false;
  4526. }
  4527. }
  4528. async #checkGame(gameId) {
  4529. try {
  4530. const {
  4531. result,
  4532. data
  4533. } = await tools_httpRequest({
  4534. ...this.#asfOptions,
  4535. data: JSON.stringify({
  4536. Command: `!CHECK ${this.#botName} ${gameId}`
  4537. })
  4538. });
  4539. if (result === 'Success') {
  4540. if (data?.status === 200 && data.response?.Result?.includes(gameId)) {
  4541. const matchedResult = data.response.Result.split('\n').find(result => result.includes(gameId))?.split('|');
  4542. if (matchedResult?.length > 3) {
  4543. return {
  4544. wishlist: matchedResult.at(-3).trim() === '√' || matchedResult.at(-2).trim() === '√',
  4545. followed: matchedResult.at(-1).trim() === '√'
  4546. };
  4547. }
  4548. return {};
  4549. }
  4550. return {};
  4551. }
  4552. return {};
  4553. } catch (error) {
  4554. throwError(error, 'SteamASF.checkGame');
  4555. return {};
  4556. }
  4557. }
  4558. async toggleCurator(curatorId, doTask = true) {
  4559. try {
  4560. const logStatus = scripts_echoLog({
  4561. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  4562. text: curatorId
  4563. });
  4564. const {
  4565. result,
  4566. statusText,
  4567. status,
  4568. data
  4569. } = await tools_httpRequest({
  4570. ...this.#asfOptions,
  4571. data: JSON.stringify({
  4572. Command: `!${doTask ? '' : 'UN'}FOLLOWCURATOR ${this.#botName} ${curatorId}`
  4573. })
  4574. });
  4575. if (result === 'Success') {
  4576. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4577. logStatus.success();
  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. } catch (error) {
  4586. throwError(error, 'Steam.toggleCurator');
  4587. return false;
  4588. }
  4589. }
  4590. async addLicense(id) {
  4591. try {
  4592. const [ type, ids ] = id.split('-');
  4593. if (type === 'appid') {
  4594. const logStatus = scripts_echoLog({
  4595. type: 'addingFreeLicense',
  4596. text: ids
  4597. });
  4598. const {
  4599. result,
  4600. statusText,
  4601. status,
  4602. data
  4603. } = await tools_httpRequest({
  4604. ...this.#asfOptions,
  4605. data: JSON.stringify({
  4606. Command: `!addlicense ${this.#botName} app/${ids}`
  4607. })
  4608. });
  4609. if (result === 'Success') {
  4610. if (data?.status === 200 && [ 'AlreadyPurchased', 'OK' ].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. } else if (type === 'subid') {
  4620. const idsArr = ids.split(',');
  4621. const logStatus = scripts_echoLog({
  4622. type: 'addingFreeLicenseSubid',
  4623. text: ids
  4624. });
  4625. const {
  4626. result,
  4627. statusText,
  4628. status,
  4629. data
  4630. } = await tools_httpRequest({
  4631. ...this.#asfOptions,
  4632. data: JSON.stringify({
  4633. Command: `!addlicense ${this.#botName} ${idsArr.map(id => `sub/${id}`).join(',')}`
  4634. })
  4635. });
  4636. if (result === 'Success') {
  4637. if (data?.status === 200 && data.response?.Result) {
  4638. const resultLines = data.response.Result.split('\n');
  4639. idsArr.forEach(subid => {
  4640. const targetLine = resultLines.find(text => text.includes(subid));
  4641. if (targetLine && [ '成功', 'Success', 'Успех' ].find(text => targetLine.includes(text))) {
  4642. scripts_echoLog({}).success(targetLine);
  4643. } else {
  4644. scripts_echoLog({}).error(targetLine);
  4645. }
  4646. });
  4647. return true;
  4648. }
  4649. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4650. return false;
  4651. }
  4652. logStatus.error(`${result}:${statusText}(${status})`);
  4653. return false;
  4654. }
  4655. return false;
  4656. } catch (error) {
  4657. throwError(error, 'SteamASF.addLicense');
  4658. return false;
  4659. }
  4660. }
  4661. async requestPlayTestAccess(id) {
  4662. try {
  4663. const logStatus = scripts_echoLog({
  4664. type: 'requestingPlayTestAccess',
  4665. text: id
  4666. });
  4667. const {
  4668. result,
  4669. statusText,
  4670. status,
  4671. data
  4672. } = await tools_httpRequest({
  4673. ...this.#asfOptions,
  4674. data: JSON.stringify({
  4675. Command: `!REQUESTACCESS ${this.#botName} ${id}`
  4676. })
  4677. });
  4678. if (result === 'Success') {
  4679. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4680. logStatus.success();
  4681. return true;
  4682. }
  4683. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4684. return false;
  4685. }
  4686. logStatus.error(`${result}:${statusText}(${status})`);
  4687. return false;
  4688. } catch (error) {
  4689. throwError(error, 'Steam.requestPlayTestAccess');
  4690. return false;
  4691. }
  4692. }
  4693. }
  4694. const social_SteamASF = SteamASF;
  4695. class Steam extends social_Social {
  4696. tasks;
  4697. whiteList;
  4698. #cache = {
  4699. ...{
  4700. group: {},
  4701. officialGroup: {},
  4702. forum: {},
  4703. workshop: {},
  4704. curator: {}
  4705. },
  4706. ...GM_getValue('steamCache')
  4707. };
  4708. #auth = {};
  4709. #storeInitialized = false;
  4710. #communityInitialized = false;
  4711. #area = 'CN';
  4712. #oldArea;
  4713. #areaStatus = 'end';
  4714. #ASF;
  4715. constructor() {
  4716. super();
  4717. const defaultTasksTemplate = {
  4718. groups: [],
  4719. officialGroups: [],
  4720. wishlists: [],
  4721. follows: [],
  4722. forums: [],
  4723. workshops: [],
  4724. workshopVotes: [],
  4725. curators: [],
  4726. curatorLikes: [],
  4727. announcements: [],
  4728. licenses: [],
  4729. playtests: []
  4730. };
  4731. this.tasks = defaultTasksTemplate;
  4732. this.whiteList = {
  4733. ...defaultTasksTemplate,
  4734. ...GM_getValue('whiteList')?.steam || {}
  4735. };
  4736. }
  4737. async init(type = 'all') {
  4738. try {
  4739. if (globalOptions.ASF.AsfEnabled && globalOptions.ASF.AsfIpcUrl && globalOptions.ASF.AsfIpcPassword) {
  4740. this.#ASF = new social_SteamASF();
  4741. if (await this.#ASF.init()) {
  4742. this.#storeInitialized = true;
  4743. this.#communityInitialized = true;
  4744. return true;
  4745. }
  4746. return false;
  4747. }
  4748. if (type === 'store') {
  4749. if (this.#storeInitialized) {
  4750. return true;
  4751. }
  4752. let storeInitialized = await this.#updateStoreAuth();
  4753. if (!storeInitialized) {
  4754. storeInitialized = await this.#updateStoreAuthTab();
  4755. }
  4756. this.#storeInitialized = storeInitialized;
  4757. if (!this.#storeInitialized) {
  4758. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4759. return false;
  4760. }
  4761. scripts_echoLog({}).success(i18n('initSuccess', 'SteamStore'));
  4762. return true;
  4763. }
  4764. if (type === 'community') {
  4765. if (this.#communityInitialized) {
  4766. return true;
  4767. }
  4768. let communityInitialized = await this.#updateCommunityAuth();
  4769. if (!communityInitialized) {
  4770. communityInitialized = await this.#updateCommunityAuthTab();
  4771. GM_setValue('steamCommunityAuth', null);
  4772. }
  4773. this.#communityInitialized = communityInitialized;
  4774. if (!this.#communityInitialized) {
  4775. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4776. return false;
  4777. }
  4778. scripts_echoLog({}).success(i18n('initSuccess', 'SteamCommunity'));
  4779. return true;
  4780. }
  4781. if (this.#storeInitialized && this.#communityInitialized) {
  4782. scripts_echoLog({}).success(i18n('initSuccess', 'Steam'));
  4783. return true;
  4784. }
  4785. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4786. return false;
  4787. } catch (error) {
  4788. throwError(error, 'Steam.init');
  4789. return false;
  4790. }
  4791. }
  4792. async #refreshToken(type = 'steamStore') {
  4793. try {
  4794. const host = {
  4795. steamStore: 'store.steampowered.com',
  4796. steamCommunity: 'steamcommunity.com'
  4797. };
  4798. const logStatus = scripts_echoLog({
  4799. text: i18n('refreshingToken', i18n(type))
  4800. });
  4801. const formData = new FormData();
  4802. formData.append('redir', `https://${host[type]}/`);
  4803. const {
  4804. result,
  4805. statusText,
  4806. status,
  4807. data
  4808. } = await tools_httpRequest({
  4809. url: 'https://login.steampowered.com/jwt/ajaxrefresh',
  4810. method: 'POST',
  4811. responseType: 'json',
  4812. headers: {
  4813. Host: 'login.steampowered.com',
  4814. Origin: `https://${host[type]}`,
  4815. Referer: `https://${host[type]}/`
  4816. },
  4817. data: formData
  4818. });
  4819. if (result === 'Success') {
  4820. if (data?.response?.success) {
  4821. if (await this.#setStoreToken(data.response, type)) {
  4822. logStatus.success();
  4823. return true;
  4824. }
  4825. logStatus.error('Error');
  4826. return false;
  4827. }
  4828. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4829. return false;
  4830. }
  4831. logStatus.error(`${result}:${statusText}(${status})`);
  4832. return false;
  4833. } catch (error) {
  4834. throwError(error, 'Steam.refreshToken');
  4835. return false;
  4836. }
  4837. }
  4838. async #setStoreToken(param, type) {
  4839. try {
  4840. const host = {
  4841. steamStore: 'store.steampowered.com',
  4842. steamCommunity: 'steamcommunity.com'
  4843. };
  4844. const logStatus = scripts_echoLog({
  4845. text: i18n('settingToken', i18n(type))
  4846. });
  4847. const formData = new FormData();
  4848. formData.append('steamID', param.steamID);
  4849. formData.append('nonce', param.nonce);
  4850. formData.append('redir', param.redir);
  4851. formData.append('auth', param.auth);
  4852. const {
  4853. result,
  4854. statusText,
  4855. status,
  4856. data
  4857. } = await tools_httpRequest({
  4858. url: `https://${host[type]}/login/settoken`,
  4859. method: 'POST',
  4860. headers: {
  4861. Accept: 'application/json, text/plain, */*',
  4862. Host: host[type],
  4863. Origin: `https://${host[type]}`
  4864. },
  4865. data: formData
  4866. });
  4867. if (result === 'Success') {
  4868. if (data?.status === 200) {
  4869. logStatus.success();
  4870. return true;
  4871. }
  4872. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4873. return false;
  4874. }
  4875. logStatus.error(`${result}:${statusText}(${status})`);
  4876. return false;
  4877. } catch (error) {
  4878. throwError(error, 'Steam.setStoreToken');
  4879. return false;
  4880. }
  4881. }
  4882. async #updateStoreAuth(retry = false) {
  4883. try {
  4884. const logStatus = scripts_echoLog({
  4885. text: i18n('updatingAuth', i18n('steamStore'))
  4886. });
  4887. const {
  4888. result,
  4889. statusText,
  4890. status,
  4891. data
  4892. } = await tools_httpRequest({
  4893. url: 'https://store.steampowered.com/',
  4894. method: 'GET',
  4895. headers: {
  4896. 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',
  4897. 'Sec-Fetch-Dest': 'document',
  4898. 'Sec-Fetch-Mode': 'navigate',
  4899. 'Upgrade-Insecure-Requests': '1'
  4900. },
  4901. fetch: false,
  4902. redirect: 'manual'
  4903. });
  4904. if (data?.status === 200) {
  4905. if (!data.responseText.includes('data-miniprofile=')) {
  4906. if (await this.#refreshToken('steamStore')) {
  4907. logStatus.warning(i18n('retry'));
  4908. if (retry) {
  4909. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4910. return false;
  4911. }
  4912. return this.#updateStoreAuth(true);
  4913. }
  4914. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4915. return false;
  4916. }
  4917. const storeSessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  4918. if (storeSessionID) {
  4919. this.#auth.storeSessionID = storeSessionID;
  4920. logStatus.success();
  4921. return true;
  4922. }
  4923. logStatus.error('Error: Get "sessionID" failed');
  4924. return false;
  4925. }
  4926. if ([ 301, 302 ].includes(data?.status)) {
  4927. if (await this.#refreshToken('steamStore')) {
  4928. logStatus.warning(i18n('retry'));
  4929. if (retry) {
  4930. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4931. return false;
  4932. }
  4933. return this.#updateStoreAuth(true);
  4934. }
  4935. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4936. return false;
  4937. }
  4938. logStatus.error(`${result}:${statusText}(${status})`);
  4939. return false;
  4940. } catch (error) {
  4941. throwError(error, 'Steam.updateStoreAuth');
  4942. return false;
  4943. }
  4944. }
  4945. async #updateStoreAuthTab() {
  4946. try {
  4947. const logStatus = scripts_echoLog({
  4948. text: i18n('updatingAuth', i18n('steamStoreTab'))
  4949. });
  4950. return await new Promise(resolve => {
  4951. GM_deleteValue('steamStoreAuth');
  4952. GM_setValue('ATv4_updateStoreAuth', true);
  4953. const newTab = GM_openInTab('https://store.steampowered.com/', {
  4954. active: true,
  4955. setParent: true
  4956. });
  4957. newTab.name = 'ATv4_updateStoreAuth';
  4958. const listenerId = GM_addValueChangeListener('steamStoreAuth', (key, oldValue, newValue) => {
  4959. GM_removeValueChangeListener(listenerId);
  4960. GM_deleteValue('ATv4_updateStoreAuth');
  4961. newTab?.close();
  4962. window.focus();
  4963. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  4964. this.#auth.storeSessionID = newValue.storeSessionID;
  4965. logStatus.success();
  4966. resolve(true);
  4967. return;
  4968. }
  4969. logStatus.error('Failed');
  4970. resolve(false);
  4971. });
  4972. newTab.onclose = () => {
  4973. GM_deleteValue('ATv4_updateStoreAuth');
  4974. };
  4975. });
  4976. } catch (error) {
  4977. throwError(error, 'Steam.updateStoreAuthTab');
  4978. return false;
  4979. }
  4980. }
  4981. async #updateCommunityAuthTab() {
  4982. try {
  4983. const logStatus = scripts_echoLog({
  4984. text: i18n('updatingAuth', i18n('steamCommunityTab'))
  4985. });
  4986. return await new Promise(resolve => {
  4987. GM_deleteValue('steamCommunityAuth');
  4988. GM_setValue('ATv4_updateCommunityAuth', true);
  4989. const newTab = GM_openInTab('https://steamcommunity.com/my', {
  4990. active: true,
  4991. setParent: true
  4992. });
  4993. newTab.name = 'ATv4_updateCommunityAuth';
  4994. const listenerId = GM_addValueChangeListener('steamCommunityAuth', (key, oldValue, newValue) => {
  4995. GM_removeValueChangeListener(listenerId);
  4996. GM_deleteValue('ATv4_updateCommunityAuth');
  4997. newTab?.close();
  4998. window.focus();
  4999. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  5000. this.#auth.steam64Id = newValue.steam64Id;
  5001. this.#auth.communitySessionID = newValue.communitySessionID;
  5002. logStatus.success();
  5003. resolve(true);
  5004. return;
  5005. }
  5006. logStatus.error('Failed');
  5007. resolve(false);
  5008. });
  5009. newTab.onclose = () => {
  5010. GM_deleteValue('ATv4_updateCommunityAuth');
  5011. };
  5012. });
  5013. } catch (error) {
  5014. throwError(error, 'Steam.updateCommunityAuthTab');
  5015. return false;
  5016. }
  5017. }
  5018. async #updateCommunityAuth() {
  5019. try {
  5020. const logStatus = scripts_echoLog({
  5021. text: i18n('gettingUserLink')
  5022. });
  5023. const {
  5024. result,
  5025. statusText,
  5026. status,
  5027. data
  5028. } = await tools_httpRequest({
  5029. url: 'https://steamcommunity.com/my',
  5030. method: 'GET',
  5031. headers: {
  5032. 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',
  5033. Host: 'steamcommunity.com',
  5034. 'Sec-Fetch-Dest': 'document',
  5035. 'Sec-Fetch-Mode': 'navigate'
  5036. },
  5037. fetch: false
  5038. });
  5039. if (data?.status === 200) {
  5040. if (data.finalUrl.includes('https://steamcommunity.com/login/home')) {
  5041. logStatus.error(`Error:${i18n('needLoginSteamCommunity')}`, true);
  5042. return false;
  5043. }
  5044. const steam64Id = data.responseText.match(/g_steamID = "(.+?)";/)?.[1];
  5045. const communitySessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  5046. if (steam64Id && communitySessionID) {
  5047. this.#auth.steam64Id = steam64Id;
  5048. this.#auth.communitySessionID = communitySessionID;
  5049. logStatus.success();
  5050. return true;
  5051. }
  5052. logStatus.error('Error: Get "sessionID" failed');
  5053. return false;
  5054. }
  5055. logStatus.error(`${result}:${statusText}(${status})`);
  5056. return false;
  5057. } catch (error) {
  5058. throwError(error, 'Steam.updateCommunityAuth');
  5059. return false;
  5060. }
  5061. }
  5062. async #getAreaInfo() {
  5063. try {
  5064. const logStatus = scripts_echoLog({
  5065. text: i18n('gettingAreaInfo')
  5066. });
  5067. const {
  5068. result,
  5069. statusText,
  5070. status,
  5071. data
  5072. } = await tools_httpRequest({
  5073. url: 'https://store.steampowered.com/cart/',
  5074. method: 'GET'
  5075. });
  5076. if (result === 'Success') {
  5077. if (data?.status === 200) {
  5078. const cartConfigRaw = data.responseText.match(/data-cart_config="(.*?)"/)?.[1];
  5079. const temp = document.createElement('div');
  5080. temp.innerHTML = cartConfigRaw || '{}';
  5081. const cartConfigStr = temp.textContent || temp.innerText;
  5082. let cartConfig;
  5083. try {
  5084. cartConfig = JSON.parse(cartConfigStr);
  5085. } catch (error) {
  5086. logStatus.error('Error: get country info filed');
  5087. console.error(error);
  5088. return {};
  5089. }
  5090. if (!cartConfig.rgUserCountryOptions) {
  5091. logStatus.warning('Warning: Area cannot be changed');
  5092. return {};
  5093. }
  5094. const userInfoRaw = data.responseText.match(/data-userinfo="(.*?)"/)?.[1];
  5095. const temp1 = document.createElement('div');
  5096. temp1.innerHTML = userInfoRaw || '{}';
  5097. const userInfoStr = temp1.textContent || temp1.innerText;
  5098. let userInfo;
  5099. try {
  5100. userInfo = JSON.parse(userInfoStr);
  5101. } catch (error) {
  5102. logStatus.error('Error: get country info filed');
  5103. console.error(error);
  5104. return {};
  5105. }
  5106. const currentArea = userInfo.country_code;
  5107. const areas = Object.keys(cartConfig.rgUserCountryOptions).filter(area => area !== 'help');
  5108. if (currentArea && areas.length > 0) {
  5109. this.#area = currentArea;
  5110. logStatus.success();
  5111. return {
  5112. currentArea: currentArea,
  5113. areas: areas
  5114. };
  5115. }
  5116. logStatus.error('Error: get country info filed');
  5117. return {};
  5118. }
  5119. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5120. return {};
  5121. }
  5122. logStatus.error(`${result}:${statusText}(${status})`);
  5123. return {};
  5124. } catch (error) {
  5125. throwError(error, 'Steam.getAreaInfo');
  5126. return {};
  5127. }
  5128. }
  5129. async #changeArea(area) {
  5130. try {
  5131. if (this.#areaStatus === 'waiting') {
  5132. await new Promise(resolve => {
  5133. const checker = setInterval(() => {
  5134. if (this.#areaStatus !== 'waiting') {
  5135. clearInterval(checker);
  5136. resolve(true);
  5137. }
  5138. });
  5139. });
  5140. }
  5141. if (this.#area === area || !area && this.#area !== 'CN') {
  5142. return true;
  5143. }
  5144. this.#areaStatus = 'waiting';
  5145. let aimedArea = area;
  5146. if (!aimedArea) {
  5147. const {
  5148. currentArea,
  5149. areas
  5150. } = await this.#getAreaInfo();
  5151. if (!currentArea || !areas) {
  5152. this.#areaStatus = 'error';
  5153. return false;
  5154. }
  5155. if (currentArea !== 'CN') {
  5156. this.#areaStatus = 'skip';
  5157. scripts_echoLog({
  5158. text: 'notNeededChangeArea'
  5159. });
  5160. return 'skip';
  5161. }
  5162. const anotherArea = areas.filter(area => area && area !== 'CN');
  5163. if (!anotherArea || anotherArea.length === 0) {
  5164. this.#areaStatus = 'noAnotherArea';
  5165. scripts_echoLog({
  5166. text: 'noAnotherArea'
  5167. });
  5168. return false;
  5169. }
  5170. [ aimedArea ] = anotherArea;
  5171. }
  5172. const logStatus = scripts_echoLog({
  5173. text: i18n('changingArea', aimedArea)
  5174. });
  5175. const {
  5176. result,
  5177. statusText,
  5178. status,
  5179. data
  5180. } = await tools_httpRequest({
  5181. url: 'https://store.steampowered.com/country/setcountry',
  5182. method: 'POST',
  5183. headers: {
  5184. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5185. },
  5186. data: $.param({
  5187. cc: aimedArea,
  5188. sessionid: this.#auth.storeSessionID
  5189. })
  5190. });
  5191. if (result === 'Success') {
  5192. if (data?.status === 200 && data.responseText === 'true') {
  5193. const {
  5194. currentArea
  5195. } = await this.#getAreaInfo();
  5196. if (currentArea) {
  5197. this.#area = currentArea;
  5198. if (!this.#oldArea) {
  5199. this.#oldArea = currentArea;
  5200. }
  5201. }
  5202. if (currentArea === aimedArea) {
  5203. this.#areaStatus = 'success';
  5204. logStatus.success();
  5205. return currentArea;
  5206. }
  5207. this.#areaStatus = 'error';
  5208. logStatus.error('Error: change country filed');
  5209. return 'CN';
  5210. }
  5211. this.#areaStatus = 'error';
  5212. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5213. return 'CN';
  5214. }
  5215. this.#areaStatus = 'error';
  5216. logStatus.error(`${result}:${statusText}(${status})`);
  5217. return 'CN';
  5218. } catch (error) {
  5219. this.#areaStatus = 'error';
  5220. throwError(error, 'Steam.changeArea');
  5221. return false;
  5222. }
  5223. }
  5224. async #joinGroup(groupName) {
  5225. try {
  5226. if (this.#ASF) {
  5227. if (await this.#ASF.joinGroup(groupName)) {
  5228. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5229. return true;
  5230. }
  5231. return false;
  5232. }
  5233. const logStatus = scripts_echoLog({
  5234. type: 'joiningSteamGroup',
  5235. text: groupName
  5236. });
  5237. const {
  5238. result,
  5239. statusText,
  5240. status,
  5241. data
  5242. } = await tools_httpRequest({
  5243. url: `https://steamcommunity.com/groups/${groupName}`,
  5244. method: 'POST',
  5245. headers: {
  5246. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5247. },
  5248. data: $.param({
  5249. action: 'join',
  5250. sessionID: this.#auth.communitySessionID
  5251. })
  5252. });
  5253. if (result === 'Success') {
  5254. if (data?.status === 200 && !data.responseText.includes('grouppage_join_area')) {
  5255. logStatus.success();
  5256. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5257. return true;
  5258. }
  5259. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5260. return false;
  5261. }
  5262. logStatus.error(`${result}:${statusText}(${status})`);
  5263. return false;
  5264. } catch (error) {
  5265. throwError(error, 'Steam.joinGroup');
  5266. return false;
  5267. }
  5268. }
  5269. async #leaveGroup(groupName) {
  5270. try {
  5271. if (this.whiteList.groups.includes(groupName)) {
  5272. scripts_echoLog({
  5273. type: 'whiteList',
  5274. text: 'Steam.leaveGroup',
  5275. id: groupName
  5276. });
  5277. return true;
  5278. }
  5279. if (this.#ASF) {
  5280. return await this.#ASF.leaveGroup(groupName);
  5281. }
  5282. const groupId = await this.#getGroupId(groupName);
  5283. if (!groupId) {
  5284. return false;
  5285. }
  5286. const logStatus = scripts_echoLog({
  5287. type: 'leavingSteamGroup',
  5288. text: groupName
  5289. });
  5290. const {
  5291. result,
  5292. statusText,
  5293. status,
  5294. data
  5295. } = await tools_httpRequest({
  5296. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5297. method: 'POST',
  5298. headers: {
  5299. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5300. },
  5301. data: $.param({
  5302. sessionID: this.#auth.communitySessionID,
  5303. action: 'leaveGroup',
  5304. groupId: groupId
  5305. })
  5306. });
  5307. if (result === 'Success') {
  5308. 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) {
  5309. logStatus.success();
  5310. return true;
  5311. }
  5312. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5313. return false;
  5314. }
  5315. logStatus.error(`${result}:${statusText}(${status})`);
  5316. return false;
  5317. } catch (error) {
  5318. throwError(error, 'Steam.leaveGroup');
  5319. return false;
  5320. }
  5321. }
  5322. async #getGroupId(groupName) {
  5323. try {
  5324. const logStatus = scripts_echoLog({
  5325. type: 'gettingSteamGroupId',
  5326. text: groupName
  5327. });
  5328. const groupId = this.#cache.group[groupName];
  5329. if (groupId) {
  5330. logStatus.success();
  5331. return groupId;
  5332. }
  5333. const {
  5334. result,
  5335. statusText,
  5336. status,
  5337. data
  5338. } = await tools_httpRequest({
  5339. url: `https://steamcommunity.com/groups/${groupName}`,
  5340. method: 'GET',
  5341. headers: {
  5342. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5343. }
  5344. });
  5345. if (result === 'Success') {
  5346. if (data?.status === 200) {
  5347. const groupId = data.responseText.match(/OpenGroupChat\( '([0-9]+)'/)?.[1];
  5348. if (groupId) {
  5349. this.#setCache('group', groupName, groupId);
  5350. logStatus.success();
  5351. return groupId;
  5352. }
  5353. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5354. return false;
  5355. }
  5356. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5357. return false;
  5358. }
  5359. logStatus.error(`${result}:${statusText}(${status})`);
  5360. return false;
  5361. } catch (error) {
  5362. throwError(error, 'Steam.getGroupID');
  5363. return false;
  5364. }
  5365. }
  5366. async #joinOfficialGroup(gameId) {
  5367. try {
  5368. if (this.#ASF) {
  5369. if (await this.#ASF.joinGroup(gameId)) {
  5370. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5371. return true;
  5372. }
  5373. return false;
  5374. }
  5375. const logStatus = scripts_echoLog({
  5376. type: 'joiningSteamOfficialGroup',
  5377. text: gameId
  5378. });
  5379. const {
  5380. result,
  5381. statusText,
  5382. status,
  5383. data
  5384. } = await tools_httpRequest({
  5385. url: `https://steamcommunity.com/games/${gameId}?action=join&sessionID=${this.#auth.communitySessionID}`,
  5386. method: 'GET',
  5387. headers: {
  5388. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5389. }
  5390. });
  5391. if (result === 'Success') {
  5392. if (data?.status === 200 && !data.responseText.includes('id="publicGroupJoin"')) {
  5393. logStatus.success();
  5394. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5395. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5396. if (groupId) {
  5397. this.#setCache('officialGroup', gameId, groupId);
  5398. }
  5399. return true;
  5400. }
  5401. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5402. return false;
  5403. }
  5404. logStatus.error(`${result}:${statusText}(${status})`);
  5405. return false;
  5406. } catch (error) {
  5407. throwError(error, 'Steam.joinOfficialGroup');
  5408. return false;
  5409. }
  5410. }
  5411. async #leaveOfficialGroup(gameId) {
  5412. try {
  5413. if (this.whiteList.officialGroups.includes(gameId)) {
  5414. scripts_echoLog({
  5415. type: 'whiteList',
  5416. text: 'Steam.leaveOfficialGroup',
  5417. id: gameId
  5418. });
  5419. return true;
  5420. }
  5421. if (this.#ASF) {
  5422. return await this.#ASF.leaveGroup(gameId);
  5423. }
  5424. const groupId = await this.#getOfficialGroupId(gameId);
  5425. if (!groupId) {
  5426. return false;
  5427. }
  5428. const logStatus = scripts_echoLog({
  5429. type: 'leavingSteamOfficialGroup',
  5430. text: gameId
  5431. });
  5432. const {
  5433. result,
  5434. statusText,
  5435. status,
  5436. data
  5437. } = await tools_httpRequest({
  5438. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5439. method: 'POST',
  5440. headers: {
  5441. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5442. },
  5443. data: $.param({
  5444. sessionID: this.#auth.communitySessionID,
  5445. action: 'leaveGroup',
  5446. groupId: groupId
  5447. })
  5448. });
  5449. if (result === 'Success') {
  5450. if (data?.status === 200) {
  5451. const {
  5452. result: resultR,
  5453. statusText: statusTextR,
  5454. status: statusR,
  5455. data: dataR
  5456. } = await tools_httpRequest({
  5457. url: `https://steamcommunity.com/games/${gameId}`,
  5458. method: 'GET',
  5459. headers: {
  5460. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5461. }
  5462. });
  5463. if (resultR === 'Success') {
  5464. if (dataR?.status === 200 && dataR.responseText.includes('id="publicGroupJoin"')) {
  5465. logStatus.success();
  5466. return true;
  5467. }
  5468. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5469. return false;
  5470. }
  5471. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5472. return false;
  5473. }
  5474. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5475. return false;
  5476. }
  5477. logStatus.error(`${result}:${statusText}(${status})`);
  5478. return false;
  5479. } catch (error) {
  5480. throwError(error, 'Steam.leaveOfficialGroup');
  5481. return false;
  5482. }
  5483. }
  5484. async #getOfficialGroupId(gameId) {
  5485. try {
  5486. const logStatus = scripts_echoLog({
  5487. type: 'gettingSteamOfficialGroupId',
  5488. text: gameId
  5489. });
  5490. const groupId = this.#cache.officialGroup[gameId];
  5491. if (groupId) {
  5492. logStatus.success();
  5493. return groupId;
  5494. }
  5495. const {
  5496. result,
  5497. statusText,
  5498. status,
  5499. data
  5500. } = await tools_httpRequest({
  5501. url: `https://steamcommunity.com/games/${gameId}`,
  5502. method: 'GET',
  5503. headers: {
  5504. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5505. }
  5506. });
  5507. if (result === 'Success') {
  5508. if (data?.status === 200) {
  5509. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5510. if (groupId) {
  5511. this.#setCache('officialGroup', gameId, groupId);
  5512. logStatus.success();
  5513. return groupId;
  5514. }
  5515. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5516. return false;
  5517. }
  5518. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5519. return false;
  5520. }
  5521. logStatus.error(`${result}:${statusText}(${status})`);
  5522. return false;
  5523. } catch (error) {
  5524. throwError(error, 'Steam.getGroupID');
  5525. return false;
  5526. }
  5527. }
  5528. async #addToWishlist(gameId) {
  5529. try {
  5530. if (this.#ASF) {
  5531. if (await this.#ASF.addToWishlist(gameId)) {
  5532. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5533. return true;
  5534. }
  5535. return false;
  5536. }
  5537. const logStatus = scripts_echoLog({
  5538. type: 'addingToWishlist',
  5539. text: gameId
  5540. });
  5541. const {
  5542. result,
  5543. data
  5544. } = await tools_httpRequest({
  5545. url: 'https://store.steampowered.com/api/addtowishlist',
  5546. method: 'POST',
  5547. headers: {
  5548. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5549. },
  5550. data: $.param({
  5551. sessionid: this.#auth.storeSessionID,
  5552. appid: gameId
  5553. }),
  5554. dataType: 'json'
  5555. });
  5556. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  5557. logStatus.success();
  5558. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5559. return true;
  5560. }
  5561. const {
  5562. result: resultR,
  5563. statusText: statusTextR,
  5564. status: statusR,
  5565. data: dataR
  5566. } = await tools_httpRequest({
  5567. url: `https://store.steampowered.com/app/${gameId}`,
  5568. method: 'GET'
  5569. });
  5570. if (resultR === 'Success') {
  5571. if (dataR?.status === 200) {
  5572. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  5573. logStatus.warning(i18n('changeAreaNotice'));
  5574. if (!await this.#changeArea()) {
  5575. return false;
  5576. }
  5577. return await this.#addToWishlist(gameId);
  5578. }
  5579. if (dataR.responseText.includes('class="queue_actions_ctn"') && dataR.responseText.includes('class="already_in_library"')) {
  5580. logStatus.success();
  5581. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5582. return true;
  5583. } 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"')) {
  5584. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  5585. return false;
  5586. }
  5587. logStatus.success();
  5588. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5589. return true;
  5590. }
  5591. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5592. return false;
  5593. }
  5594. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5595. return false;
  5596. } catch (error) {
  5597. throwError(error, 'Steam.addToWishlist');
  5598. return false;
  5599. }
  5600. }
  5601. async #removeFromWishlist(gameId) {
  5602. try {
  5603. if (this.whiteList.wishlists.includes(gameId)) {
  5604. scripts_echoLog({
  5605. type: 'whiteList',
  5606. text: 'Steam.removeFromWishlist',
  5607. id: gameId
  5608. });
  5609. return true;
  5610. }
  5611. if (this.#ASF) {
  5612. return await this.#ASF.removeFromWishlist(gameId);
  5613. }
  5614. const logStatus = scripts_echoLog({
  5615. type: 'removingFromWishlist',
  5616. text: gameId
  5617. });
  5618. const {
  5619. result,
  5620. data
  5621. } = await tools_httpRequest({
  5622. url: 'https://store.steampowered.com/api/removefromwishlist',
  5623. method: 'POST',
  5624. headers: {
  5625. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5626. },
  5627. data: $.param({
  5628. sessionid: this.#auth.storeSessionID,
  5629. appid: gameId
  5630. }),
  5631. dataType: 'json'
  5632. });
  5633. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  5634. logStatus.success();
  5635. return true;
  5636. }
  5637. const {
  5638. result: resultR,
  5639. statusText: statusTextR,
  5640. status: statusR,
  5641. data: dataR
  5642. } = await tools_httpRequest({
  5643. url: `https://store.steampowered.com/app/${gameId}`,
  5644. method: 'GET'
  5645. });
  5646. if (resultR === 'Success') {
  5647. if (dataR?.status === 200) {
  5648. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  5649. logStatus.warning(i18n('changeAreaNotice'));
  5650. const result = await this.#changeArea();
  5651. if (!result || result === 'CN' || result === 'skip') {
  5652. return false;
  5653. }
  5654. return await this.#removeFromWishlist(gameId);
  5655. }
  5656. if (dataR.responseText.includes('class="queue_actions_ctn"') && (dataR.responseText.includes('ds_owned_flag ds_flag') || dataR.responseText.includes('add_to_wishlist_area'))) {
  5657. logStatus.success();
  5658. return true;
  5659. }
  5660. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  5661. return false;
  5662. }
  5663. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5664. return false;
  5665. }
  5666. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5667. return false;
  5668. } catch (error) {
  5669. throwError(error, 'Steam.removeFromWishlist');
  5670. return false;
  5671. }
  5672. }
  5673. async #toggleFollowGame(gameId, doTask) {
  5674. try {
  5675. if (!doTask && this.whiteList.follows.includes(gameId)) {
  5676. scripts_echoLog({
  5677. type: 'whiteList',
  5678. text: 'Steam.unfollowGame',
  5679. id: gameId
  5680. });
  5681. return true;
  5682. }
  5683. if (this.#ASF) {
  5684. if (await this.#ASF.toggleFollowGame(gameId, doTask)) {
  5685. if (doTask) {
  5686. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  5687. }
  5688. return true;
  5689. }
  5690. return false;
  5691. }
  5692. const logStatus = scripts_echoLog({
  5693. type: `${doTask ? '' : 'un'}followingGame`,
  5694. text: gameId
  5695. });
  5696. const requestData = {
  5697. sessionid: this.#auth.storeSessionID,
  5698. appid: gameId
  5699. };
  5700. if (!doTask) {
  5701. requestData.unfollow = '1';
  5702. }
  5703. const {
  5704. result,
  5705. data
  5706. } = await tools_httpRequest({
  5707. url: 'https://store.steampowered.com/explore/followgame/',
  5708. method: 'POST',
  5709. headers: {
  5710. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5711. },
  5712. data: $.param(requestData)
  5713. });
  5714. if (result === 'Success' && data?.status === 200 && data.responseText === 'true') {
  5715. logStatus.success();
  5716. return true;
  5717. }
  5718. const followed = await this.#isFollowedGame(gameId);
  5719. if (this.#area === 'CN' && followed === 'areaLocked') {
  5720. logStatus.warning(i18n('changeAreaNotice'));
  5721. if (!await this.#changeArea()) {
  5722. return false;
  5723. }
  5724. return await this.#toggleFollowGame(gameId, doTask);
  5725. }
  5726. if (doTask === followed) {
  5727. logStatus.success();
  5728. if (doTask) {
  5729. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  5730. }
  5731. return true;
  5732. }
  5733. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5734. return false;
  5735. } catch (error) {
  5736. throwError(error, 'Steam.toggleFollowGame');
  5737. return false;
  5738. }
  5739. }
  5740. async #isFollowedGame(gameId) {
  5741. try {
  5742. const {
  5743. result,
  5744. data
  5745. } = await tools_httpRequest({
  5746. url: `https://store.steampowered.com/app/${gameId}`,
  5747. method: 'GET'
  5748. });
  5749. if (result === 'Success') {
  5750. if (data?.status === 200) {
  5751. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  5752. return 'areaLocked';
  5753. }
  5754. if ($(data.responseText.replace(/<img.*?>/g, '')).find('.queue_control_button.queue_btn_follow>.btnv6_blue_hoverfade.btn_medium.queue_btn_active').css('display') !== 'none') {
  5755. return true;
  5756. }
  5757. return false;
  5758. }
  5759. return false;
  5760. }
  5761. return false;
  5762. } catch (error) {
  5763. throwError(error, 'Steam.isFollowedGame');
  5764. return false;
  5765. }
  5766. }
  5767. async #toggleForum(gameId, doTask = true) {
  5768. try {
  5769. if (!doTask && this.whiteList.forums.includes(gameId)) {
  5770. scripts_echoLog({
  5771. type: 'whiteList',
  5772. text: 'Steam.unsubscribeForum',
  5773. id: gameId
  5774. });
  5775. return true;
  5776. }
  5777. const forumId = await this.#getForumId(gameId);
  5778. if (!forumId) {
  5779. return false;
  5780. }
  5781. const logStatus = scripts_echoLog({
  5782. type: `${doTask ? '' : 'un'}subscribingForum`,
  5783. text: gameId
  5784. });
  5785. const [ id, feature ] = forumId.split('_');
  5786. const {
  5787. result,
  5788. statusText,
  5789. status,
  5790. data
  5791. } = await tools_httpRequest({
  5792. url: `https://steamcommunity.com/forum/${id}/General/${doTask ? '' : 'un'}subscribe/${feature || '0'}/`,
  5793. method: 'POST',
  5794. responseType: 'json',
  5795. headers: {
  5796. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5797. },
  5798. data: $.param({
  5799. sessionid: this.#auth.communitySessionID
  5800. })
  5801. });
  5802. if (result === 'Success') {
  5803. if (data?.status === 200 && (data.response?.success === 1 || data.response?.success === 29)) {
  5804. if (doTask) {
  5805. this.tasks.forums = unique([ ...this.tasks.forums, gameId ]);
  5806. }
  5807. logStatus.success();
  5808. return true;
  5809. }
  5810. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5811. return true;
  5812. }
  5813. logStatus.error(`${result}:${statusText}(${status})`);
  5814. return true;
  5815. } catch (error) {
  5816. throwError(error, 'Steam.toggleForum');
  5817. return true;
  5818. }
  5819. }
  5820. async #getForumId(gameId) {
  5821. try {
  5822. const logStatus = scripts_echoLog({
  5823. type: 'gettingForumId',
  5824. text: gameId
  5825. });
  5826. const forumId = this.#cache.forum[gameId];
  5827. if (forumId) {
  5828. logStatus.success();
  5829. return forumId;
  5830. }
  5831. const {
  5832. result,
  5833. statusText,
  5834. status,
  5835. data
  5836. } = await tools_httpRequest({
  5837. url: `https://steamcommunity.com/app/${gameId}/discussions/`,
  5838. method: 'GET'
  5839. });
  5840. if (result === 'Success') {
  5841. if (data?.status === 200) {
  5842. const forumId = data.responseText?.match(/General_([\d]+(_[\d]+)?)/)?.[1];
  5843. if (forumId) {
  5844. this.#setCache('forum', gameId, forumId);
  5845. logStatus.success();
  5846. return forumId;
  5847. }
  5848. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5849. return false;
  5850. }
  5851. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5852. return false;
  5853. }
  5854. logStatus.error(`${result}:${statusText}(${status})`);
  5855. return false;
  5856. } catch (error) {
  5857. throwError(error, 'Steam.getForumId');
  5858. return false;
  5859. }
  5860. }
  5861. async #toggleFavoriteWorkshop(id, doTask = true) {
  5862. try {
  5863. if (!doTask && this.whiteList.workshops.includes(id)) {
  5864. scripts_echoLog({
  5865. type: 'whiteList',
  5866. text: 'Steam.unfavoriteWorkshop',
  5867. id: id
  5868. });
  5869. return true;
  5870. }
  5871. const appid = await this.#getWorkshopAppId(id);
  5872. if (!appid) {
  5873. return false;
  5874. }
  5875. const logStatus = scripts_echoLog({
  5876. type: doTask ? 'favoritingWorkshop' : 'unfavoritingWorkshop',
  5877. text: id
  5878. });
  5879. const {
  5880. result,
  5881. statusText,
  5882. status,
  5883. data
  5884. } = await tools_httpRequest({
  5885. url: `https://steamcommunity.com/sharedfiles/${doTask ? '' : 'un'}favorite`,
  5886. method: 'POST',
  5887. headers: {
  5888. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5889. },
  5890. data: $.param({
  5891. id: id,
  5892. appid: appid,
  5893. sessionid: this.#auth.communitySessionID
  5894. })
  5895. });
  5896. if (result === 'Success') {
  5897. if (data?.status === 200 && !data.responseText) {
  5898. if (doTask) {
  5899. this.tasks.workshops = unique([ ...this.tasks.workshops, id ]);
  5900. }
  5901. logStatus.success();
  5902. return true;
  5903. }
  5904. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5905. return false;
  5906. }
  5907. logStatus.error(`${result}:${statusText}(${status})`);
  5908. return false;
  5909. } catch (error) {
  5910. throwError(error, 'Steam.toggleFavoriteWorkshop');
  5911. return false;
  5912. }
  5913. }
  5914. async #getWorkshopAppId(id) {
  5915. try {
  5916. const logStatus = scripts_echoLog({
  5917. type: 'gettingWorkshopAppId',
  5918. text: id
  5919. });
  5920. const appId = this.#cache.workshop[id];
  5921. if (appId) {
  5922. logStatus.success();
  5923. return appId;
  5924. }
  5925. const {
  5926. result,
  5927. statusText,
  5928. status,
  5929. data
  5930. } = await tools_httpRequest({
  5931. url: `https://steamcommunity.com/sharedfiles/filedetails/?id=${id}`,
  5932. method: 'GET'
  5933. });
  5934. if (result === 'Success') {
  5935. if (data?.status === 200) {
  5936. const appId = data.responseText.match(/<input type="hidden" name="appid" value="([\d]+?)" \/>/)?.[1];
  5937. if (appId) {
  5938. this.#setCache('workshop', id, appId);
  5939. logStatus.success();
  5940. return appId;
  5941. }
  5942. logStatus.error('Error: getWorkshopAppId failed');
  5943. return false;
  5944. }
  5945. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5946. return false;
  5947. }
  5948. logStatus.error(`${result}:${statusText}(${status})`);
  5949. return false;
  5950. } catch (error) {
  5951. throwError(error, 'Steam.getWorkshopAppId');
  5952. return false;
  5953. }
  5954. }
  5955. async #voteUpWorkshop(id) {
  5956. try {
  5957. const logStatus = scripts_echoLog({
  5958. type: 'votingUpWorkshop',
  5959. text: id
  5960. });
  5961. const {
  5962. result,
  5963. statusText,
  5964. status,
  5965. data
  5966. } = await tools_httpRequest({
  5967. url: 'https://steamcommunity.com/sharedfiles/voteup',
  5968. method: 'POST',
  5969. responseType: 'json',
  5970. headers: {
  5971. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5972. },
  5973. data: $.param({
  5974. id: id,
  5975. sessionid: this.#auth.communitySessionID
  5976. })
  5977. });
  5978. if (result === 'Success') {
  5979. if (data?.status === 200 && data.response?.success === 1) {
  5980. logStatus.success();
  5981. return true;
  5982. }
  5983. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5984. return true;
  5985. }
  5986. logStatus.error(`${result}:${statusText}(${status})`);
  5987. return true;
  5988. } catch (error) {
  5989. throwError(error, 'Steam.voteupWorkshop');
  5990. return true;
  5991. }
  5992. }
  5993. async #toggleCurator(curatorId, doTask = true) {
  5994. try {
  5995. if (!doTask && this.whiteList.curators.includes(curatorId)) {
  5996. scripts_echoLog({
  5997. type: 'whiteList',
  5998. text: 'Steam.unfollowCurator',
  5999. id: curatorId
  6000. });
  6001. return true;
  6002. }
  6003. if (this.#ASF) {
  6004. return await this.#ASF.toggleCurator(curatorId, doTask);
  6005. }
  6006. const logStatus = scripts_echoLog({
  6007. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  6008. text: curatorId
  6009. });
  6010. const {
  6011. result,
  6012. statusText,
  6013. status,
  6014. data
  6015. } = await tools_httpRequest({
  6016. url: 'https://store.steampowered.com/curators/ajaxfollow',
  6017. method: 'POST',
  6018. headers: {
  6019. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6020. },
  6021. data: $.param({
  6022. clanid: curatorId,
  6023. sessionid: this.#auth.storeSessionID,
  6024. follow: doTask
  6025. }),
  6026. dataType: 'json'
  6027. });
  6028. if (result === 'Success') {
  6029. if (data?.status === 200 && data.response?.success?.success === 1) {
  6030. logStatus.success();
  6031. return true;
  6032. }
  6033. logStatus.error(`Error:${data?.statusText}(${data?.response?.success}` || `${data?.status})`);
  6034. return false;
  6035. }
  6036. logStatus.error(`${result}:${statusText}(${status})`);
  6037. return false;
  6038. } catch (error) {
  6039. throwError(error, 'Steam.toggleCurator');
  6040. return false;
  6041. }
  6042. }
  6043. async getCuratorId(path, name) {
  6044. try {
  6045. const logStatus = scripts_echoLog({
  6046. type: 'gettingCuratorId',
  6047. text: `${path}/${name}`
  6048. });
  6049. const curatorId = this.#cache.curator[`${path}/${name}`];
  6050. if (curatorId) {
  6051. logStatus.success();
  6052. return curatorId;
  6053. }
  6054. const {
  6055. result,
  6056. statusText,
  6057. status,
  6058. data
  6059. } = await tools_httpRequest({
  6060. url: `https://store.steampowered.com/${path}/${name}`,
  6061. method: 'GET',
  6062. headers: {
  6063. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6064. }
  6065. });
  6066. if (result === 'Success') {
  6067. if (data?.status === 200) {
  6068. const curatorId = data.responseText.match(/g_pagingData.*?"clanid":([\d]+)/)?.[1];
  6069. if (curatorId) {
  6070. this.#setCache('curator', `${path}/${name}`, curatorId);
  6071. logStatus.success();
  6072. return curatorId;
  6073. }
  6074. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6075. return false;
  6076. }
  6077. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6078. return false;
  6079. }
  6080. logStatus.error(`${result}:${statusText}(${status})`);
  6081. return false;
  6082. } catch (error) {
  6083. throwError(error, 'Steam.getCuratorID');
  6084. return false;
  6085. }
  6086. }
  6087. async #toggleCuratorLike(link, doTask = true) {
  6088. try {
  6089. const [ path, name ] = link.split('/');
  6090. if (!(path && name)) {
  6091. scripts_echoLog({
  6092. text: i18n('errorLink', link)
  6093. });
  6094. return false;
  6095. }
  6096. const curatorId = await this.getCuratorId(path, name);
  6097. if (curatorId) {
  6098. return await this.#toggleCurator(curatorId, doTask);
  6099. }
  6100. return false;
  6101. } catch (error) {
  6102. throwError(error, 'Steam.toggleCuratorLike');
  6103. return false;
  6104. }
  6105. }
  6106. async #getAnnouncementParams(appId, viewId) {
  6107. try {
  6108. const logStatus = scripts_echoLog({
  6109. type: 'gettingAnnouncementParams',
  6110. text: appId,
  6111. id: viewId
  6112. });
  6113. const {
  6114. result,
  6115. statusText,
  6116. status,
  6117. data
  6118. } = await tools_httpRequest({
  6119. 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`,
  6120. method: 'GET',
  6121. responseType: 'json',
  6122. headers: {
  6123. Host: 'store.steampowered.com',
  6124. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6125. }
  6126. });
  6127. if (result === 'Success') {
  6128. if (data?.status === 200 && data?.response?.success === 1) {
  6129. const {
  6130. clanid,
  6131. gid
  6132. } = data.response.event?.announcement_body || {};
  6133. if (clanid) {
  6134. logStatus.success();
  6135. return {
  6136. clanId: clanid,
  6137. gid: gid
  6138. };
  6139. }
  6140. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6141. return {};
  6142. }
  6143. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6144. return {};
  6145. }
  6146. logStatus.error(`${result}:${statusText}(${status})`);
  6147. return {};
  6148. } catch (error) {
  6149. throwError(error, 'Steam.likeAnnouncement');
  6150. return {};
  6151. }
  6152. }
  6153. async #likeAnnouncement(id) {
  6154. try {
  6155. const [ appId, viewId ] = id.split('/');
  6156. if (!(appId && viewId)) {
  6157. scripts_echoLog({}).error(`${i18n('missParams')}(id)`);
  6158. return false;
  6159. }
  6160. const {
  6161. clanId,
  6162. gid
  6163. } = await this.#getAnnouncementParams(appId, viewId);
  6164. if (!clanId) {
  6165. return false;
  6166. }
  6167. const logStatus = scripts_echoLog({
  6168. type: 'likingAnnouncement',
  6169. text: appId,
  6170. id: viewId
  6171. });
  6172. const {
  6173. result,
  6174. statusText,
  6175. status,
  6176. data
  6177. } = await tools_httpRequest({
  6178. url: `https://store.steampowered.com/updated/ajaxrateupdate/${gid || viewId}`,
  6179. method: 'POST',
  6180. headers: {
  6181. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6182. Host: 'store.steampowered.com',
  6183. Origin: 'https://store.steampowered.com',
  6184. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6185. },
  6186. data: $.param({
  6187. sessionid: this.#auth.storeSessionID,
  6188. voteup: 1,
  6189. clanid: clanId,
  6190. ajax: 1
  6191. }),
  6192. dataType: 'json'
  6193. });
  6194. if (result === 'Success') {
  6195. if (data?.status === 200 && data.response.success === 1) {
  6196. logStatus.success();
  6197. return true;
  6198. }
  6199. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6200. return false;
  6201. }
  6202. logStatus.error(`${result}:${statusText}(${status})`);
  6203. return false;
  6204. } catch (error) {
  6205. throwError(error, 'Steam.likeAnnouncement');
  6206. return false;
  6207. }
  6208. }
  6209. async #appid2subid(id) {
  6210. try {
  6211. const logStatus = scripts_echoLog({
  6212. type: 'gettingSubid',
  6213. text: id
  6214. });
  6215. const {
  6216. result,
  6217. statusText,
  6218. status,
  6219. data
  6220. } = await tools_httpRequest({
  6221. url: `https://store.steampowered.com/app/${id}`,
  6222. method: 'GET',
  6223. headers: {
  6224. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6225. }
  6226. });
  6227. if (result === 'Success') {
  6228. if (data?.status === 200) {
  6229. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6230. logStatus.success(i18n('owned'));
  6231. return false;
  6232. }
  6233. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6234. logStatus.warning(i18n('changeAreaNotice'));
  6235. const result = await this.#changeArea();
  6236. if (!result || result === 'CN' || result === 'skip') {
  6237. return false;
  6238. }
  6239. return await this.#appid2subid(id);
  6240. }
  6241. let subid = data.responseText.match(/name="subid" value="([\d]+?)"/)?.[1];
  6242. if (subid) {
  6243. logStatus.success();
  6244. return subid;
  6245. }
  6246. subid = data.responseText.match(/AddFreeLicense\(\s*(\d+)/)?.[1];
  6247. if (subid) {
  6248. logStatus.success();
  6249. return subid;
  6250. }
  6251. logStatus.error(`Error:${i18n('noSubid')}`);
  6252. return false;
  6253. }
  6254. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6255. return false;
  6256. }
  6257. logStatus.error(`${result}:${statusText}(${status})`);
  6258. return false;
  6259. } catch (error) {
  6260. throwError(error, 'Steam.appid2subid');
  6261. return false;
  6262. }
  6263. }
  6264. async #getLicenses() {
  6265. try {
  6266. const logStatus = scripts_echoLog({
  6267. text: i18n('gettingLicenses')
  6268. });
  6269. const {
  6270. result,
  6271. statusText,
  6272. status,
  6273. data
  6274. } = await tools_httpRequest({
  6275. url: `https://store.steampowered.com/dynamicstore/userdata/?t=${new Date().getTime()}`,
  6276. method: 'GET',
  6277. responseType: 'json'
  6278. });
  6279. if (result === 'Success') {
  6280. if (data?.status === 200) {
  6281. logStatus.success();
  6282. return data.response?.rgOwnedPackages;
  6283. }
  6284. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6285. return false;
  6286. }
  6287. logStatus.error(`${result}:${statusText}(${status})`);
  6288. return false;
  6289. } catch (error) {
  6290. throwError(error, 'Steam.getLicenses');
  6291. return false;
  6292. }
  6293. }
  6294. async #addLicense(id) {
  6295. try {
  6296. if (this.#ASF) {
  6297. return await this.#ASF.addLicense(id);
  6298. }
  6299. const [ type, ids ] = id.split('-');
  6300. if (type === 'appid') {
  6301. const subid = await this.#appid2subid(ids);
  6302. if (!subid) {
  6303. return false;
  6304. }
  6305. const logStatus = scripts_echoLog({
  6306. type: 'addingFreeLicense',
  6307. text: ids
  6308. });
  6309. if (!await this.#addFreeLicense(subid, logStatus)) {
  6310. return false;
  6311. }
  6312. const {
  6313. result,
  6314. statusText,
  6315. status,
  6316. data
  6317. } = await tools_httpRequest({
  6318. url: `https://store.steampowered.com/app/${ids}`,
  6319. method: 'GET'
  6320. });
  6321. if (result === 'Success') {
  6322. if (data?.status === 200) {
  6323. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6324. logStatus.success();
  6325. return true;
  6326. }
  6327. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6328. return false;
  6329. }
  6330. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6331. return false;
  6332. }
  6333. logStatus.error(`${result}:${statusText}(${status})`);
  6334. return false;
  6335. } else if (type === 'subid') {
  6336. if (this.#area === 'CN') {
  6337. scripts_echoLog({}).success(i18n('tryChangeAreaNotice'));
  6338. await this.#changeArea();
  6339. }
  6340. const logStatusArr = {};
  6341. const idsArr = ids.split(',');
  6342. for (const subid of idsArr) {
  6343. const logStatus = scripts_echoLog({
  6344. type: 'addingFreeLicenseSubid',
  6345. text: subid
  6346. });
  6347. if (!await this.#addFreeLicense(subid, logStatus)) {
  6348. return false;
  6349. }
  6350. logStatusArr[subid] = logStatus;
  6351. }
  6352. const licenses = await this.#getLicenses();
  6353. if (!licenses) {
  6354. return false;
  6355. }
  6356. for (const subid of idsArr) {
  6357. if (licenses.includes(parseInt(subid, 10))) {
  6358. logStatusArr[subid].success();
  6359. } else {
  6360. logStatusArr[subid].error();
  6361. }
  6362. }
  6363. return true;
  6364. }
  6365. return false;
  6366. } catch (error) {
  6367. throwError(error, 'Steam.addLicense');
  6368. return false;
  6369. }
  6370. }
  6371. async #addFreeLicense(id, logStatusPre) {
  6372. try {
  6373. const logStatus = logStatusPre || scripts_echoLog({
  6374. type: 'addingFreeLicenseSubid',
  6375. text: id
  6376. });
  6377. const {
  6378. result,
  6379. statusText,
  6380. status,
  6381. data
  6382. } = await tools_httpRequest({
  6383. url: `https://store.steampowered.com/freelicense/addfreelicense/${id}`,
  6384. method: 'POST',
  6385. headers: {
  6386. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6387. Host: 'store.steampowered.com',
  6388. Origin: 'https://store.steampowered.com',
  6389. Referer: 'https://store.steampowered.com/account/licenses/'
  6390. },
  6391. data: $.param({
  6392. ajax: true,
  6393. sessionid: this.#auth.storeSessionID
  6394. }),
  6395. dataType: 'json'
  6396. });
  6397. if (result === 'Success') {
  6398. if (data?.status === 200) {
  6399. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6400. logStatus.warning(i18n('changeAreaNotice'));
  6401. const result = await this.#changeArea();
  6402. if (!result || [ 'CN', 'skip' ].includes(result)) {
  6403. return false;
  6404. }
  6405. return await this.#addFreeLicense(id);
  6406. }
  6407. logStatus.success();
  6408. return true;
  6409. }
  6410. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6411. return false;
  6412. }
  6413. logStatus.error(`${result}:${statusText}(${status})`);
  6414. return false;
  6415. } catch (error) {
  6416. throwError(error, 'Steam.addFreeLicense');
  6417. return false;
  6418. }
  6419. }
  6420. async #requestPlayTestAccess(id) {
  6421. try {
  6422. if (this.#ASF) {
  6423. return await this.#ASF.requestPlayTestAccess(id);
  6424. }
  6425. const logStatus = scripts_echoLog({
  6426. type: 'requestingPlayTestAccess',
  6427. text: id
  6428. });
  6429. const {
  6430. result,
  6431. statusText,
  6432. status,
  6433. data
  6434. } = await tools_httpRequest({
  6435. url: `https://store.steampowered.com/ajaxrequestplaytestaccess/${id}`,
  6436. method: 'POST',
  6437. headers: {
  6438. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6439. Host: 'store.steampowered.com',
  6440. Origin: 'https://store.steampowered.com',
  6441. Referer: `https://store.steampowered.com/app/${id}`
  6442. },
  6443. data: $.param({
  6444. sessionid: this.#auth.storeSessionID
  6445. }),
  6446. dataType: 'json'
  6447. });
  6448. if (result === 'Success') {
  6449. if (data?.status === 200 && data?.response?.success === 1) {
  6450. logStatus.success();
  6451. return true;
  6452. }
  6453. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6454. return false;
  6455. }
  6456. logStatus.error(`${result}:${statusText}(${status})`);
  6457. return false;
  6458. } catch (error) {
  6459. throwError(error, 'Steam.requestPlayTestAccess');
  6460. return false;
  6461. }
  6462. }
  6463. async toggle({
  6464. doTask = true,
  6465. groupLinks = [],
  6466. officialGroupLinks = [],
  6467. wishlistLinks = [],
  6468. followLinks = [],
  6469. forumLinks = [],
  6470. workshopLinks = [],
  6471. workshopVoteLinks = [],
  6472. curatorLinks = [],
  6473. curatorLikeLinks = [],
  6474. announcementLinks = [],
  6475. licenseLinks = [],
  6476. playtestLinks = []
  6477. }) {
  6478. try {
  6479. if ([ ...groupLinks, ...officialGroupLinks, ...forumLinks, ...workshopLinks, ...workshopVoteLinks ].length > 0 && !this.#communityInitialized) {
  6480. scripts_echoLog({
  6481. text: i18n('needInit')
  6482. });
  6483. return false;
  6484. }
  6485. if ([ ...wishlistLinks, ...followLinks, ...curatorLinks, ...curatorLikeLinks, ...announcementLinks, ...licenseLinks, ...playtestLinks ].length > 0 && !this.#storeInitialized) {
  6486. scripts_echoLog({
  6487. text: i18n('needInit')
  6488. });
  6489. return false;
  6490. }
  6491. const prom = [];
  6492. if (doTask && !globalOptions.doTask.steam.groups || !doTask && !globalOptions.undoTask.steam.groups) {
  6493. scripts_echoLog({
  6494. type: 'globalOptionsSkip',
  6495. text: 'steam.groups'
  6496. });
  6497. } else {
  6498. const realGroups = this.getRealParams('groups', groupLinks, doTask, link => link.match(/groups\/(.+)\/?/)?.[1]);
  6499. if (realGroups.length > 0) {
  6500. for (const group of realGroups) {
  6501. if (doTask) {
  6502. prom.push(this.#joinGroup(group));
  6503. } else {
  6504. prom.push(this.#leaveGroup(group));
  6505. }
  6506. await delay(1e3);
  6507. }
  6508. }
  6509. }
  6510. if (doTask && !globalOptions.doTask.steam.officialGroups || !doTask && !globalOptions.undoTask.steam.officialGroups) {
  6511. scripts_echoLog({
  6512. type: 'globalOptionsSkip',
  6513. text: 'steam.officialGroups'
  6514. });
  6515. } else {
  6516. const realOfficialGroups = this.getRealParams('officialGroups', officialGroupLinks, doTask, link => link.match(/games\/(.+)\/?/)?.[1]);
  6517. if (realOfficialGroups.length > 0) {
  6518. for (const officialGroup of realOfficialGroups) {
  6519. if (doTask) {
  6520. prom.push(this.#joinOfficialGroup(officialGroup));
  6521. } else {
  6522. prom.push(this.#leaveOfficialGroup(officialGroup));
  6523. }
  6524. await delay(1e3);
  6525. }
  6526. }
  6527. }
  6528. if (doTask && !globalOptions.doTask.steam.wishlists || !doTask && !globalOptions.undoTask.steam.wishlists) {
  6529. scripts_echoLog({
  6530. type: 'globalOptionsSkip',
  6531. text: 'steam.wishlists'
  6532. });
  6533. } else {
  6534. const realWishlists = this.getRealParams('wishlists', wishlistLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6535. if (realWishlists.length > 0) {
  6536. for (const game of realWishlists) {
  6537. if (doTask) {
  6538. prom.push(this.#addToWishlist(game));
  6539. } else {
  6540. prom.push(this.#removeFromWishlist(game));
  6541. }
  6542. await delay(1e3);
  6543. }
  6544. }
  6545. }
  6546. if (doTask && !globalOptions.doTask.steam.follows || !doTask && !globalOptions.undoTask.steam.follows) {
  6547. scripts_echoLog({
  6548. type: 'globalOptionsSkip',
  6549. text: 'steam.follows'
  6550. });
  6551. } else {
  6552. const realFollows = this.getRealParams('follows', followLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6553. if (realFollows.length > 0) {
  6554. for (const game of realFollows) {
  6555. prom.push(this.#toggleFollowGame(game, doTask));
  6556. await delay(1e3);
  6557. }
  6558. }
  6559. }
  6560. if (doTask && !globalOptions.doTask.steam.forums || !doTask && !globalOptions.undoTask.steam.forums) {
  6561. scripts_echoLog({
  6562. type: 'globalOptionsSkip',
  6563. text: 'steam.forums'
  6564. });
  6565. } else {
  6566. const realForums = this.getRealParams('forums', forumLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6567. if (realForums.length > 0) {
  6568. for (const forum of realForums) {
  6569. prom.push(this.#toggleForum(forum, doTask));
  6570. await delay(1e3);
  6571. }
  6572. }
  6573. }
  6574. if (doTask && !globalOptions.doTask.steam.workshops || !doTask && !globalOptions.undoTask.steam.workshops) {
  6575. scripts_echoLog({
  6576. type: 'globalOptionsSkip',
  6577. text: 'steam.workshops'
  6578. });
  6579. } else {
  6580. const realWorkshops = this.getRealParams('workshops', workshopLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  6581. if (realWorkshops.length > 0) {
  6582. for (const workshop of realWorkshops) {
  6583. prom.push(this.#toggleFavoriteWorkshop(workshop, doTask));
  6584. await delay(1e3);
  6585. }
  6586. }
  6587. }
  6588. if (doTask && !globalOptions.doTask.steam.workshopVotes) {
  6589. scripts_echoLog({
  6590. type: 'globalOptionsSkip',
  6591. text: 'steam.workshopVotes'
  6592. });
  6593. } else {
  6594. const realworkshopVotes = this.getRealParams('workshopVotes', workshopVoteLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  6595. if (doTask && realworkshopVotes.length > 0) {
  6596. for (const workshop of realworkshopVotes) {
  6597. prom.push(this.#voteUpWorkshop(workshop));
  6598. await delay(1e3);
  6599. }
  6600. }
  6601. }
  6602. if (doTask && !globalOptions.doTask.steam.curators || !doTask && !globalOptions.undoTask.steam.curators) {
  6603. scripts_echoLog({
  6604. type: 'globalOptionsSkip',
  6605. text: 'steam.curators'
  6606. });
  6607. } else {
  6608. const realCurators = this.getRealParams('curators', curatorLinks, doTask, link => link.match(/curator\/([\d]+)/)?.[1]);
  6609. const realCuratorLikes = this.getRealParams('curatorLikes', curatorLikeLinks, doTask, link => link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3).join('/'));
  6610. if (realCurators.length > 0) {
  6611. for (const curator of realCurators) {
  6612. prom.push(this.#toggleCurator(curator, doTask));
  6613. await delay(1e3);
  6614. }
  6615. }
  6616. if (realCuratorLikes.length > 0) {
  6617. for (const curatorLike of realCuratorLikes) {
  6618. prom.push(this.#toggleCuratorLike(curatorLike, doTask));
  6619. await delay(1e3);
  6620. }
  6621. }
  6622. }
  6623. if (doTask && !globalOptions.doTask.steam.announcements) {
  6624. scripts_echoLog({
  6625. type: 'globalOptionsSkip',
  6626. text: 'steam.announcements'
  6627. });
  6628. } else {
  6629. const realAnnouncements = this.getRealParams('announcements', announcementLinks, doTask, link => {
  6630. if (link.includes('store.steampowered.com')) {
  6631. return link.match(/store\.steampowered\.com\/news\/app\/([\d]+)\/view\/([\d]+)/)?.slice(1, 3).join('/');
  6632. }
  6633. return link.match(/steamcommunity\.com\/games\/([\d]+)\/announcements\/detail\/([\d]+)/)?.slice(1, 3).join('/');
  6634. });
  6635. if (doTask && realAnnouncements.length > 0) {
  6636. for (const id of realAnnouncements) {
  6637. prom.push(this.#likeAnnouncement(id));
  6638. await delay(1e3);
  6639. }
  6640. }
  6641. }
  6642. if (doTask && !globalOptions.doTask.steam.licenses) {
  6643. scripts_echoLog({
  6644. type: 'globalOptionsSkip',
  6645. text: 'steam.licenses'
  6646. });
  6647. } else if (doTask && globalOptions.doTask.steam.licenses && licenseLinks.length > 0) {
  6648. for (const ids of licenseLinks) {
  6649. const [ type, idsStr ] = ids.split('-');
  6650. const idsArr = idsStr.split(',');
  6651. for (const id of idsArr) {
  6652. prom.push(this.#addLicense(`${type}-${id}`));
  6653. await delay(1e3);
  6654. }
  6655. }
  6656. }
  6657. if (doTask && !globalOptions.doTask.steam.playtests) {
  6658. scripts_echoLog({
  6659. type: 'globalOptionsSkip',
  6660. text: 'steam.playtests'
  6661. });
  6662. } else {
  6663. const realPlaytests = this.getRealParams('playtests', playtestLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6664. if (doTask && globalOptions.doTask.steam.playtests && realPlaytests.length > 0) {
  6665. for (const id of realPlaytests) {
  6666. prom.push(this.#requestPlayTestAccess(id));
  6667. await delay(1e3);
  6668. }
  6669. }
  6670. }
  6671. return Promise.all(prom).then(async () => {
  6672. if (this.#oldArea && this.#area !== this.#oldArea) {
  6673. scripts_echoLog({}).warning(i18n('steamFinishNotice') + this.#oldArea);
  6674. await this.#changeArea(this.#oldArea);
  6675. }
  6676. return true;
  6677. });
  6678. } catch (error) {
  6679. throwError(error, 'Steam.toggle');
  6680. return false;
  6681. }
  6682. }
  6683. #setCache(type, name, id) {
  6684. try {
  6685. this.#cache[type][name] = id;
  6686. GM_setValue('steamCache', this.#cache);
  6687. } catch (error) {
  6688. throwError(error, 'Steam.setCache');
  6689. }
  6690. }
  6691. }
  6692. const social_Steam = Steam;
  6693. class Website {
  6694. undoneTasks;
  6695. socialTasks;
  6696. giveawayId;
  6697. socialInitialized = {
  6698. discord: false,
  6699. instagram: false,
  6700. reddit: false,
  6701. twitch: false,
  6702. twitter: false,
  6703. vk: false,
  6704. youtube: false,
  6705. steamStore: false,
  6706. steamCommunity: false
  6707. };
  6708. initialized = false;
  6709. steamTaskType = {
  6710. steamStore: false,
  6711. steamCommunity: false
  6712. };
  6713. social = {};
  6714. async #bind(name, init) {
  6715. try {
  6716. return {
  6717. name: name,
  6718. result: await init
  6719. };
  6720. } catch (error) {
  6721. throwError(error, 'Website.bind');
  6722. return {
  6723. name: name,
  6724. result: false
  6725. };
  6726. }
  6727. }
  6728. async initSocial(action) {
  6729. try {
  6730. const pro = [];
  6731. const tasks = action === 'do' ? this.undoneTasks : this.socialTasks;
  6732. if (tasks.discord) {
  6733. const hasDiscord = Object.values(tasks.discord).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6734. if (hasDiscord && (!this.socialInitialized.discord || !this.social.discord)) {
  6735. this.social.discord = new social_Discord();
  6736. pro.push(this.#bind('discord', this.social.discord.init(action)));
  6737. }
  6738. }
  6739. if (tasks.instagram) {
  6740. const hasInstagram = Object.values(tasks.instagram).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6741. if (hasInstagram && (!this.socialInitialized.instagram || !this.social.instagram)) {
  6742. this.social.instagram = new social_Instagram();
  6743. pro.push(this.#bind('instagram', this.social.instagram.init()));
  6744. }
  6745. }
  6746. if (tasks.reddit) {
  6747. const hasReddit = Object.values(tasks.reddit).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6748. if (hasReddit && (!this.socialInitialized.reddit || !this.social.reddit)) {
  6749. this.social.reddit = new social_Reddit();
  6750. pro.push(this.#bind('reddit', this.social.reddit.init()));
  6751. }
  6752. }
  6753. if (tasks.twitch) {
  6754. const hasTwitch = Object.values(tasks.twitch).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6755. if (hasTwitch && (!this.socialInitialized.twitch || !this.social.twitch)) {
  6756. this.social.twitch = new social_Twitch();
  6757. pro.push(this.#bind('twitch', this.social.twitch.init()));
  6758. }
  6759. }
  6760. if (tasks.twitter) {
  6761. const hasTwitter = Object.values(tasks.twitter).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6762. if (hasTwitter && (!this.socialInitialized.twitter || !this.social.twitter)) {
  6763. this.social.twitter = new social_Twitter();
  6764. pro.push(this.#bind('twitter', this.social.twitter.init()));
  6765. }
  6766. }
  6767. if (tasks.vk) {
  6768. const hasVk = Object.values(tasks.vk).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6769. if (hasVk && (!this.socialInitialized.vk || !this.social.vk)) {
  6770. this.social.vk = new social_Vk();
  6771. pro.push(this.#bind('vk', this.social.vk.init()));
  6772. }
  6773. }
  6774. if (tasks.youtube) {
  6775. const hasYoutube = Object.values(tasks.youtube).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6776. if (hasYoutube && (!this.socialInitialized.youtube || !this.social.youtube)) {
  6777. this.social.youtube = new Youtube();
  6778. pro.push(this.#bind('youtube', this.social.youtube.init()));
  6779. }
  6780. }
  6781. if (tasks.steam) {
  6782. const steamLength = Object.values(tasks.steam).reduce((total, arr) => [ ...total, ...arr ]).length;
  6783. if (steamLength > 0) {
  6784. if (!this.social.steam) {
  6785. this.social.steam = new social_Steam();
  6786. }
  6787. 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);
  6788. if (steamLength - steamCommunityLength > 0) {
  6789. this.steamTaskType.steamStore = true;
  6790. if (!this.socialInitialized.steamStore) {
  6791. pro.push(this.#bind('steamStore', this.social.steam.init('store')));
  6792. }
  6793. }
  6794. if (steamCommunityLength > 0) {
  6795. if (!this.socialInitialized.steamCommunity) {
  6796. this.steamTaskType.steamCommunity = true;
  6797. pro.push(this.#bind('steamCommunity', this.social.steam.init('community')));
  6798. }
  6799. }
  6800. }
  6801. }
  6802. if (tasks.links && tasks.links.length > 0) {
  6803. this.social.visitLink = visitLink;
  6804. }
  6805. return await Promise.all(pro).then(result => {
  6806. let checked = true;
  6807. for (const data of result) {
  6808. if (data.result) {
  6809. this.socialInitialized[data.name] = data.result;
  6810. } else {
  6811. checked = false;
  6812. }
  6813. }
  6814. return checked;
  6815. });
  6816. } catch (error) {
  6817. throwError(error, 'Website.initSocial');
  6818. return false;
  6819. }
  6820. }
  6821. uniqueTasks(allTasks) {
  6822. try {
  6823. const result = {};
  6824. for (const [ social, types ] of Object.entries(allTasks)) {
  6825. result[social] = {};
  6826. for (const [ type, tasks ] of Object.entries(types)) {
  6827. result[social][type] = unique(tasks);
  6828. }
  6829. }
  6830. return result;
  6831. } catch (error) {
  6832. throwError(error, 'Website.uniqueTasks');
  6833. return allTasks;
  6834. }
  6835. }
  6836. async toggleTask(action) {
  6837. try {
  6838. if (!this.initialized && !this.init()) {
  6839. return false;
  6840. }
  6841. if (!await this.classifyTask(action)) {
  6842. return false;
  6843. }
  6844. await this.initSocial(action);
  6845. const pro = [];
  6846. const doTask = action === 'do';
  6847. const tasks = doTask ? this.undoneTasks : this.socialTasks;
  6848. if (this.socialInitialized.discord === true && this.social.discord) {
  6849. pro.push(this.social.discord.toggle({
  6850. doTask: doTask,
  6851. ...tasks.discord
  6852. }));
  6853. }
  6854. if (this.socialInitialized.instagram === true && this.social.instagram) {
  6855. pro.push(this.social.instagram.toggle({
  6856. doTask: doTask,
  6857. ...tasks.instagram
  6858. }));
  6859. }
  6860. if (this.socialInitialized.reddit === true && this.social.reddit) {
  6861. pro.push(this.social.reddit.toggle({
  6862. doTask: doTask,
  6863. ...tasks.reddit
  6864. }));
  6865. }
  6866. if (this.socialInitialized.twitch === true && this.social.twitch) {
  6867. pro.push(this.social.twitch.toggle({
  6868. doTask: doTask,
  6869. ...tasks.twitch
  6870. }));
  6871. }
  6872. if (this.socialInitialized.twitter === true && this.social.twitter) {
  6873. pro.push(this.social.twitter.toggle({
  6874. doTask: doTask,
  6875. ...tasks.twitter
  6876. }));
  6877. }
  6878. if (this.socialInitialized.vk === true && this.social.vk) {
  6879. pro.push(this.social.vk.toggle({
  6880. doTask: doTask,
  6881. ...tasks.vk
  6882. }));
  6883. }
  6884. if (this.socialInitialized.youtube === true && this.social.youtube) {
  6885. pro.push(this.social.youtube.toggle({
  6886. doTask: doTask,
  6887. ...tasks.youtube
  6888. }));
  6889. }
  6890. if ((this.steamTaskType.steamCommunity ? this.socialInitialized.steamCommunity === true : true) && (this.steamTaskType.steamStore ? this.socialInitialized.steamStore === true : true) && this.social.steam) {
  6891. pro.push(this.social.steam.toggle({
  6892. doTask: doTask,
  6893. ...tasks.steam
  6894. }));
  6895. }
  6896. if (this.social.visitLink && tasks.links && doTask) {
  6897. for (const link of tasks.links) {
  6898. pro.push(this.social.visitLink(link));
  6899. }
  6900. }
  6901. if (doTask && tasks.extra && this.extraDoTask) {
  6902. const hasExtra = Object.values(tasks.extra).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6903. if (hasExtra) {
  6904. pro.push(this.extraDoTask(tasks.extra));
  6905. }
  6906. }
  6907. await Promise.all(pro);
  6908. scripts_echoLog({}).success(i18n('allTasksComplete'));
  6909. return true;
  6910. } catch (error) {
  6911. throwError(error, 'Website.toggleTask');
  6912. return false;
  6913. }
  6914. }
  6915. async doTask() {
  6916. try {
  6917. return await this.toggleTask('do');
  6918. } catch (error) {
  6919. throwError(error, 'Website.doTask');
  6920. return false;
  6921. }
  6922. }
  6923. async undoTask() {
  6924. try {
  6925. return await this.toggleTask('undo');
  6926. } catch (error) {
  6927. throwError(error, 'Website.undoTask');
  6928. return false;
  6929. }
  6930. }
  6931. }
  6932. const website_Website = Website;
  6933. const defaultTasksTemplate = {
  6934. steam: {
  6935. groupLinks: [],
  6936. wishlistLinks: [],
  6937. curatorLinks: [],
  6938. followLinks: []
  6939. },
  6940. discord: {
  6941. serverLinks: []
  6942. },
  6943. vk: {
  6944. nameLinks: []
  6945. },
  6946. extra: {
  6947. website: []
  6948. }
  6949. };
  6950. const defaultTasks = JSON.stringify(defaultTasksTemplate);
  6951. class FreeAnyWhere extends website_Website {
  6952. name = 'FreeAnyWhere';
  6953. tasks = [];
  6954. socialTasks = JSON.parse(defaultTasks);
  6955. undoneTasks = JSON.parse(defaultTasks);
  6956. buttons = [ 'doTask', 'undoTask', 'verifyTask', 'getKey' ];
  6957. static test() {
  6958. return window.location.host === 'freeanywhere.net';
  6959. }
  6960. async init() {
  6961. try {
  6962. const logStatus = scripts_echoLog({
  6963. text: i18n('initing')
  6964. });
  6965. debug('检测登录按钮');
  6966. if ($('div.header__login a[href*=logout]').length === 0) {
  6967. window.open('https://freeanywhere.net/game.php?steam_login', '_self');
  6968. logStatus.warning(i18n('needLogin'));
  6969. return false;
  6970. }
  6971. debug('检测是否为登录页面');
  6972. if (window.location.href.includes('/login')) {
  6973. logStatus.warning(i18n('needLogin'));
  6974. return false;
  6975. }
  6976. this.initialized = true;
  6977. logStatus.success();
  6978. return true;
  6979. } catch (error) {
  6980. throwError(error, 'Freeanywhere.init');
  6981. return false;
  6982. }
  6983. }
  6984. async classifyTask(action) {
  6985. try {
  6986. const logStatus = scripts_echoLog({
  6987. text: i18n('getTasksInfo')
  6988. });
  6989. if (action === 'undo') {
  6990. this.socialTasks = GM_getValue(`fawTasks-${this.giveawayId}`)?.tasks || JSON.parse(defaultTasks);
  6991. }
  6992. const tasks = $('div.game__content-tasks__task').map((index, element) => ({
  6993. id: $(element).attr('data-id'),
  6994. social: $(element).find('div.task-img img').attr('alt'),
  6995. link: $(element).find('div.task-link a').attr('href'),
  6996. title: $(element).find('div.task-link').text().trim(),
  6997. type: $(element).attr('data-type'),
  6998. isSuccess: $(element).hasClass('done')
  6999. })).toArray();
  7000. if (tasks.length === 0) {
  7001. logStatus.success();
  7002. return false;
  7003. }
  7004. if (action === 'verify') {
  7005. this.tasks = [];
  7006. }
  7007. for (const task of tasks) {
  7008. debug('任务分类', task);
  7009. const {
  7010. id,
  7011. social,
  7012. title,
  7013. type,
  7014. link,
  7015. isSuccess
  7016. } = task;
  7017. const taskInfo = {
  7018. id: id,
  7019. title: title,
  7020. social: social,
  7021. type: type
  7022. };
  7023. if (action === 'verify' && !isSuccess) {
  7024. this.tasks.push(taskInfo);
  7025. continue;
  7026. }
  7027. switch (type) {
  7028. case 'steam_account_verify':
  7029. break;
  7030.  
  7031. case 'steam_game_wishlist':
  7032. if (action === 'undo' && link) {
  7033. this.socialTasks.steam.wishlistLinks.push(link);
  7034. }
  7035. if (action === 'do' && !isSuccess && link) {
  7036. this.undoneTasks.steam.wishlistLinks.push(link);
  7037. }
  7038. break;
  7039.  
  7040. case 'steam_group_sub':
  7041. if (action === 'undo' && link) {
  7042. this.socialTasks.steam.groupLinks.push(link);
  7043. }
  7044. if (action === 'do' && !isSuccess && link) {
  7045. this.undoneTasks.steam.groupLinks.push(link);
  7046. }
  7047. break;
  7048.  
  7049. case 'site_visit':
  7050. if (action === 'do' && !isSuccess) {
  7051. this.undoneTasks.extra.website.push(`id=${id}&type=${type}&task=true`);
  7052. }
  7053. break;
  7054.  
  7055. case 'vk_community_sub':
  7056. if (action === 'undo' && link) {
  7057. this.socialTasks.vk.nameLinks.push(link);
  7058. }
  7059. if (action === 'do' && !isSuccess && link) {
  7060. this.undoneTasks.vk.nameLinks.push(link);
  7061. }
  7062. break;
  7063.  
  7064. case 'vk_post_like':
  7065. if (action === 'undo' && link) {
  7066. this.socialTasks.vk.nameLinks.push(`${link}&action=like`);
  7067. }
  7068. if (action === 'do' && !isSuccess && link) {
  7069. this.undoneTasks.vk.nameLinks.push(`${link}&action=like`);
  7070. }
  7071. break;
  7072.  
  7073. case 'discord_server_sub':
  7074. if (action === 'undo' && link) {
  7075. this.socialTasks.discord.serverLinks.push(link);
  7076. }
  7077. if (action === 'do' && !isSuccess && link) {
  7078. this.undoneTasks.discord.serverLinks.push(link);
  7079. }
  7080. break;
  7081.  
  7082. case 'none':
  7083. scripts_echoLog({}).warning(`${i18n('notConnect')}`);
  7084. break;
  7085.  
  7086. default:
  7087. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${type}`);
  7088. break;
  7089. }
  7090. }
  7091. logStatus.success();
  7092. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7093. this.socialTasks = this.uniqueTasks(this.socialTasks);
  7094. if (window.DEBUG) {
  7095. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7096. }
  7097. GM_setValue(`fawTasks-${this.giveawayId}`, {
  7098. tasks: this.socialTasks,
  7099. time: new Date().getTime()
  7100. });
  7101. return true;
  7102. } catch (error) {
  7103. throwError(error, 'Freeanywhere.classifyTask');
  7104. return false;
  7105. }
  7106. }
  7107. async verifyTask() {
  7108. try {
  7109. if (!this.initialized && !this.init()) {
  7110. debug('未初始化');
  7111. return false;
  7112. }
  7113. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  7114. debug('任务列表为空', this.tasks);
  7115. return false;
  7116. }
  7117. const pro = [];
  7118. for (const task of this.tasks) {
  7119. pro.push(this.#verify(task));
  7120. await delay(1e3);
  7121. }
  7122. await Promise.all(pro);
  7123. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7124. return !!await this.getKey(true);
  7125. } catch (error) {
  7126. throwError(error, 'Freeanywhere.verifyTask');
  7127. return false;
  7128. }
  7129. }
  7130. async extraDoTask({
  7131. website
  7132. }) {
  7133. try {
  7134. const pro = [];
  7135. for (const link of website) {
  7136. pro.push(this.#doVisitWebsite(link));
  7137. }
  7138. return Promise.all(pro).then(() => true);
  7139. } catch (error) {
  7140. throwError(error, 'FreeAnyWhere.extraDoTask');
  7141. return false;
  7142. }
  7143. }
  7144. async #doVisitWebsite(link) {
  7145. try {
  7146. const logStatus = scripts_echoLog({
  7147. text: i18n('visitingLink')
  7148. });
  7149. const {
  7150. result,
  7151. statusText,
  7152. status,
  7153. data
  7154. } = await tools_httpRequest({
  7155. url: 'https://freeanywhere.net/php/task_site_visit_done.php',
  7156. method: 'POST',
  7157. headers: {
  7158. 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  7159. },
  7160. data: link
  7161. });
  7162. if (result === 'Success') {
  7163. logStatus.success();
  7164. return true;
  7165. }
  7166. logStatus.error(`${result}:${statusText}(${status})`);
  7167. return false;
  7168. } catch (error) {
  7169. throwError(error, 'FreeAnyWhere.doVisitWebsite');
  7170. return false;
  7171. }
  7172. }
  7173. async getKey(initialized) {
  7174. try {
  7175. if (!initialized && !this.initialized && !this.init()) {
  7176. debug('未初始化');
  7177. return false;
  7178. }
  7179. const logStatus = scripts_echoLog({
  7180. text: i18n('gettingKey')
  7181. });
  7182. const {
  7183. result,
  7184. statusText,
  7185. status,
  7186. data
  7187. } = await tools_httpRequest({
  7188. url: 'https://freeanywhere.net/php/user_get_key.php',
  7189. method: 'POST'
  7190. });
  7191. if (result === 'Success') {
  7192. if (data?.responseText.indexOf('bad') !== -1 || data?.responseText.length > 50) {
  7193. logStatus.error(data?.responseText);
  7194. return false;
  7195. }
  7196. logStatus.success();
  7197. scripts_echoLog({}).success(data.responseText);
  7198. return data.responseText;
  7199. }
  7200. logStatus.error(`${result}:${statusText}(${status})`);
  7201. return false;
  7202. } catch (error) {
  7203. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7204. return false;
  7205. }
  7206. }
  7207. #getGiveawayId() {
  7208. try {
  7209. const giveawayId = new URLSearchParams(window.location.search).get('n');
  7210. if (giveawayId) {
  7211. this.giveawayId = giveawayId;
  7212. return true;
  7213. }
  7214. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  7215. return false;
  7216. } catch (error) {
  7217. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7218. return false;
  7219. }
  7220. }
  7221. async #verify(task) {
  7222. try {
  7223. const logStatus = scripts_echoLog({
  7224. html: `<li>${i18n('verifyingTask')}${task.title.trim()}...<font></font></li>`
  7225. });
  7226. const {
  7227. result,
  7228. statusText,
  7229. status,
  7230. data
  7231. } = await tools_httpRequest({
  7232. url: 'https://freeanywhere.net/php/user_task_update.php',
  7233. method: 'POST',
  7234. headers: {
  7235. 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  7236. },
  7237. data: `id=${task.id}&type=${task.type}`
  7238. });
  7239. if (result === 'Success') {
  7240. if (data?.responseText.trim() === 'good') {
  7241. logStatus.success();
  7242. return true;
  7243. }
  7244. debug('任务验证结果', data?.response);
  7245. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7246. return false;
  7247. }
  7248. logStatus.error(`${result}:${statusText}(${status})`);
  7249. return false;
  7250. } catch (error) {
  7251. throwError(error, 'Freeanywhere.verify');
  7252. return false;
  7253. }
  7254. }
  7255. async #checkLeftKey() {
  7256. try {
  7257. if (!globalOptions.other.checkLeftKey) {
  7258. return true;
  7259. }
  7260. debug('检测剩余Key');
  7261. const {
  7262. data
  7263. } = await tools_httpRequest({
  7264. url: 'https://freeanywhere.net/api/v1/widget/?format=json',
  7265. method: 'GET',
  7266. dataType: 'json',
  7267. headers: {
  7268. authorization: `Token ${window.localStorage.getItem('token')}`
  7269. }
  7270. });
  7271. if (data?.response?.giveaways.find(giveaway => `${giveaway?.id}` === this.giveawayId)) {
  7272. return true;
  7273. }
  7274. await external_Swal_default().fire({
  7275. icon: 'warning',
  7276. title: i18n('notice'),
  7277. text: i18n('noKeysLeft'),
  7278. confirmButtonText: i18n('confirm'),
  7279. cancelButtonText: i18n('cancel'),
  7280. showCancelButton: true
  7281. }).then(({
  7282. value
  7283. }) => {
  7284. if (value) {
  7285. window.close();
  7286. }
  7287. });
  7288. return true;
  7289. } catch (error) {
  7290. throwError(error, 'Giveawaysu.checkLeftKey');
  7291. return false;
  7292. }
  7293. }
  7294. }
  7295. const Freeanywhere = FreeAnyWhere;
  7296. const Giveawaysu_defaultTasks = {
  7297. steam: {
  7298. groupLinks: [],
  7299. wishlistLinks: [],
  7300. curatorLinks: [],
  7301. curatorLikeLinks: [],
  7302. followLinks: [],
  7303. forumLinks: [],
  7304. announcementLinks: [],
  7305. workshopVoteLinks: [],
  7306. playtestLinks: []
  7307. },
  7308. discord: {
  7309. serverLinks: []
  7310. },
  7311. instagram: {
  7312. userLinks: []
  7313. },
  7314. vk: {
  7315. nameLinks: []
  7316. },
  7317. twitch: {
  7318. channelLinks: []
  7319. },
  7320. reddit: {
  7321. redditLinks: []
  7322. },
  7323. youtube: {
  7324. channelLinks: [],
  7325. likeLinks: []
  7326. },
  7327. twitter: {
  7328. userLinks: [],
  7329. retweetLinks: []
  7330. }
  7331. };
  7332. class GiveawaySu extends website_Website {
  7333. name = 'GiveawaySu';
  7334. socialTasks = Giveawaysu_defaultTasks;
  7335. undoneTasks = Giveawaysu_defaultTasks;
  7336. buttons = [ 'doTask', 'undoTask' ];
  7337. static test() {
  7338. return /^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(window.location.href);
  7339. }
  7340. async after() {
  7341. try {
  7342. if (!this.#checkLogin()) {
  7343. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7344. }
  7345. if (!await this.#checkLeftKey()) {
  7346. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7347. }
  7348. scripts_echoLog({}).warning(i18n('gsNotice'));
  7349. } catch (error) {
  7350. throwError(error, 'Giveawaysu.after');
  7351. }
  7352. }
  7353. init() {
  7354. try {
  7355. const logStatus = scripts_echoLog({
  7356. text: i18n('initing')
  7357. });
  7358. if ($('a.steam-login').length > 0) {
  7359. window.open('/steam/redirect', '_self');
  7360. logStatus.warning(i18n('needLogin'));
  7361. return false;
  7362. }
  7363. if (!this.#getGiveawayId()) {
  7364. return false;
  7365. }
  7366. this.initialized = true;
  7367. logStatus.success();
  7368. return true;
  7369. } catch (error) {
  7370. throwError(error, 'Giveawaysu.init');
  7371. return false;
  7372. }
  7373. }
  7374. async classifyTask(action) {
  7375. try {
  7376. const logStatus = scripts_echoLog({
  7377. text: i18n('getTasksInfo')
  7378. });
  7379. if (action === 'undo') {
  7380. this.socialTasks = GM_getValue(`gasTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  7381. return true;
  7382. }
  7383. const pro = [];
  7384. const tasks = $('#actions tr');
  7385. if ($('div.bind-discord').is(':visible')) {
  7386. $('div.bind-discord a')[0].click();
  7387. }
  7388. if ($('div.bind-twitch').is(':visible')) {
  7389. $('div.bind-twitch a')[0].click();
  7390. }
  7391. for (const task of tasks) {
  7392. pro.push(new Promise(resolve => {
  7393. const td = $(task).find('td:not(".hidden")');
  7394. const colorfulTask = td.eq(1).find('a:not([data-trigger="link"])');
  7395. const colorlessTask = td.eq(2).find('a:not([data-trigger="link"])');
  7396. const taskDes = colorfulTask.length > 0 ? colorfulTask : colorlessTask;
  7397. const taskIcon = td.eq(0).find('i').attr('class') || '';
  7398. const taskName = taskDes.text().trim();
  7399. if (taskIcon.includes('ban') || /disable adblock/gi.test(taskName)) {
  7400. return resolve(true);
  7401. }
  7402. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  7403. if (!taskLink) {
  7404. return resolve(false);
  7405. }
  7406. if (taskIcon.includes('steam') && /join/gi.test(taskName)) {
  7407. this.undoneTasks.steam.groupLinks.push(taskLink);
  7408. } else if (/like.*announcement/gi.test(taskName)) {
  7409. this.undoneTasks.steam.announcementLinks.push(taskLink);
  7410. } else if (/(follow|subscribe).*curator/gim.test(taskName) && /^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  7411. this.undoneTasks.steam.curatorLinks.push(taskLink);
  7412. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  7413. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  7414. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  7415. this.undoneTasks.steam.forumLinks.push(taskLink);
  7416. } else if (taskIcon.includes('thumbs-up') && /^https?:\/\/steamcommunity\.com\/sharedfiles\/filedetails\/\?id=[\d]+/.test(taskLink)) {
  7417. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7418. } else if (taskIcon.includes('plus') && /request.*playtest/gim.test(taskName)) {
  7419. this.undoneTasks.steam.playtestLinks.push(taskLink);
  7420. } else if (taskIcon.includes('discord') || /join.*discord/gim.test(taskName)) {
  7421. this.undoneTasks.discord.serverLinks.push(taskLink);
  7422. } else if (taskIcon.includes('instagram') || /follow.*instagram/gim.test(taskName)) {
  7423. this.undoneTasks.instagram.userLinks.push(taskLink);
  7424. } else if (taskIcon.includes('twitch') || /follow.*twitch.*channel/gim.test(taskName)) {
  7425. this.undoneTasks.twitch.channelLinks.push(taskLink);
  7426. } else if (taskIcon.includes('reddit') || /subscribe.*subreddit/gim.test(taskName) || /follow.*reddit/gim.test(taskName)) {
  7427. this.undoneTasks.reddit.redditLinks.push(taskLink);
  7428. } else if (/watch.*art/gim.test(taskName)) {
  7429. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7430. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  7431. this.undoneTasks.youtube.channelLinks.push(taskLink);
  7432. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  7433. this.undoneTasks.youtube.likeLinks.push(taskLink);
  7434. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  7435. this.undoneTasks.vk.nameLinks.push(taskLink);
  7436. } else {
  7437. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  7438. if (/wishlist.*game|add.*wishlist/gim.test(taskName)) {
  7439. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  7440. }
  7441. if (/follow.*button/gim.test(taskName)) {
  7442. this.undoneTasks.steam.followLinks.push(taskLink);
  7443. }
  7444. }
  7445. }
  7446. resolve(true);
  7447. }).catch(error => {
  7448. throwError(error, 'Giveawaysu.classifyTask->getRedirectLink');
  7449. return false;
  7450. });
  7451. }));
  7452. }
  7453. await Promise.all(pro);
  7454. logStatus.success();
  7455. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7456. this.socialTasks = this.undoneTasks;
  7457. if (window.DEBUG) {
  7458. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7459. }
  7460. GM_setValue(`gasTasks-${this.giveawayId}`, {
  7461. tasks: this.socialTasks,
  7462. time: new Date().getTime()
  7463. });
  7464. return true;
  7465. } catch (error) {
  7466. throwError(error, 'Giveawaysu.classifyTask');
  7467. return false;
  7468. }
  7469. }
  7470. #checkLogin() {
  7471. try {
  7472. if (!globalOptions.other.checkLogin) {
  7473. return true;
  7474. }
  7475. if ($('a.steam-login').length > 0) {
  7476. window.open('/steam/redirect', '_self');
  7477. }
  7478. return true;
  7479. } catch (error) {
  7480. throwError(error, 'Giveawaysu.checkLogin');
  7481. return false;
  7482. }
  7483. }
  7484. async #checkLeftKey() {
  7485. try {
  7486. if (!globalOptions.other.checkLeftKey) {
  7487. return true;
  7488. }
  7489. if ($('.giveaway-ended').length > 0 && $('.giveaway-key').length === 0) {
  7490. await external_Swal_default().fire({
  7491. icon: 'warning',
  7492. title: i18n('notice'),
  7493. text: i18n('noKeysLeft'),
  7494. confirmButtonText: i18n('confirm'),
  7495. cancelButtonText: i18n('cancel'),
  7496. showCancelButton: true
  7497. }).then(({
  7498. value
  7499. }) => {
  7500. if (value) {
  7501. window.close();
  7502. }
  7503. });
  7504. }
  7505. return true;
  7506. } catch (error) {
  7507. throwError(error, 'Giveawaysu.checkLeftKey');
  7508. return false;
  7509. }
  7510. }
  7511. #getGiveawayId() {
  7512. try {
  7513. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  7514. if (giveawayId) {
  7515. this.giveawayId = giveawayId;
  7516. return true;
  7517. }
  7518. scripts_echoLog({
  7519. text: i18n('getFailed', 'GiveawayId')
  7520. });
  7521. return false;
  7522. } catch (error) {
  7523. throwError(error, 'Giveawaysu.getGiveawayId');
  7524. return false;
  7525. }
  7526. }
  7527. }
  7528. class Indiedb {
  7529. name = 'Indiedb';
  7530. buttons = [ 'doTask' ];
  7531. static test() {
  7532. return window.location.host === 'www.indiedb.com';
  7533. }
  7534. async after() {
  7535. try {
  7536. if (!this.#checkLogin()) {
  7537. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7538. }
  7539. if (!await this.#checkLeftKey()) {
  7540. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7541. }
  7542. } catch (error) {
  7543. throwError(error, 'Indiedb.after');
  7544. }
  7545. }
  7546. async doTask() {
  7547. try {
  7548. if (!await this.#join()) {
  7549. return false;
  7550. }
  7551. return await this.#do();
  7552. } catch (error) {
  7553. throwError(error, 'Indiedb.doTask');
  7554. return false;
  7555. }
  7556. }
  7557. async #join() {
  7558. try {
  7559. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7560. scripts_echoLog({}).error(i18n('needLogin'));
  7561. return false;
  7562. }
  7563. const currentoption = $('a.buttonenter.buttongiveaway');
  7564. if (/join giveaway/gim.test(currentoption.text())) {
  7565. const logStatus = scripts_echoLog({
  7566. text: `${i18n('joiningGiveaway')}...`
  7567. });
  7568. const {
  7569. result,
  7570. statusText,
  7571. status,
  7572. data
  7573. } = await tools_httpRequest({
  7574. url: currentoption.attr('href'),
  7575. method: 'POST',
  7576. data: 'ajax=t',
  7577. dataType: 'json',
  7578. headers: {
  7579. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  7580. Accept: 'application/json, text/javascript, */*; q=0.01',
  7581. Origin: window.location.origin,
  7582. referer: window.location.href
  7583. }
  7584. });
  7585. if (result === 'Success') {
  7586. if (data?.status === 200) {
  7587. if (data.response?.success) {
  7588. currentoption.addClass('buttonentered').text('Success - Giveaway joined');
  7589. $('#giveawaysjoined').slideDown();
  7590. $('#giveawaysrecommend').slideDown();
  7591. logStatus.success(`Success${data.response?.text ? `:${data.response?.text}` : ''}`);
  7592. return true;
  7593. }
  7594. logStatus.error(`Error${data.response?.text ? `:${data.response?.text}` : ''}`);
  7595. return false;
  7596. }
  7597. if (await this.#join2()) {
  7598. logStatus.success('Success');
  7599. return true;
  7600. }
  7601. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7602. return false;
  7603. }
  7604. logStatus.error(`${result}:${statusText}(${status})`);
  7605. return false;
  7606. } else if (/success/gim.test($('a.buttonenter.buttongiveaway').text())) {
  7607. return true;
  7608. }
  7609. scripts_echoLog({}).warning(i18n('needJoinGiveaway'));
  7610. return false;
  7611. } catch (error) {
  7612. throwError(error, 'Indiedb.join');
  7613. return false;
  7614. }
  7615. }
  7616. async #join2() {
  7617. try {
  7618. return await new Promise(resolve => {
  7619. const targetNode = document.getElementById('giveawaysjoined');
  7620. const config = {
  7621. attributes: true
  7622. };
  7623. const observer = new MutationObserver(() => {
  7624. if ($('#giveawaysjoined').is(':visible')) {
  7625. resolve(true);
  7626. observer.disconnect();
  7627. }
  7628. });
  7629. observer.observe(targetNode, config);
  7630. $('a.buttonenter.buttongiveaway')[0]?.click();
  7631. setTimeout(() => {
  7632. resolve(false);
  7633. observer.disconnect();
  7634. }, 3e4);
  7635. });
  7636. } catch (error) {
  7637. throwError(error, 'Indiedb.join2');
  7638. return false;
  7639. }
  7640. }
  7641. async #do() {
  7642. try {
  7643. const id = $('script').map((index, script) => {
  7644. if (/\$\(document\)/gim.test(script.innerHTML)) {
  7645. return [ script.innerHTML.match(/"\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0], script.innerHTML.match(/"\/newsletter\/ajax\/subscribeprofile\/optin\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0] ];
  7646. }
  7647. return null;
  7648. });
  7649. if (id.length === 2) {
  7650. const pro = [];
  7651. const tasks = $('#giveawaysjoined a[class*=promo]');
  7652. for (const task of tasks) {
  7653. const promo = $(task);
  7654. if (!promo.hasClass('buttonentered')) {
  7655. const status = scripts_echoLog({
  7656. text: `${i18n('doing')}:${promo.parents('p').text()}...`
  7657. });
  7658. if (/facebookpromo|twitterpromo|visitpromo/gim.test(task.className)) {
  7659. let text = '';
  7660. if (promo.hasClass('facebookpromo')) {
  7661. text = 'facebookpromo';
  7662. } else if (promo.hasClass('twitterpromo')) {
  7663. text = 'twitterpromo';
  7664. } else {
  7665. text = 'visitpromo';
  7666. }
  7667. pro.push(new Promise(resolve => {
  7668. $.ajax({
  7669. type: 'POST',
  7670. url: urlPath(`/giveaways/ajax/${text}/${id[0]}`),
  7671. timeout: 6e4,
  7672. dataType: 'json',
  7673. data: {
  7674. ajax: 't'
  7675. },
  7676. error(response, error, exception) {
  7677. if (window.DEBUG) {
  7678. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7679. response: response,
  7680. error: error,
  7681. exception: exception
  7682. });
  7683. }
  7684. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7685. resolve(true);
  7686. },
  7687. success(response) {
  7688. if (response.success) {
  7689. status.success(`Success:${response.text}`);
  7690. promo.addClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7691. resolve(true);
  7692. } else {
  7693. status.error(`Error:${response.text}`);
  7694. resolve(true);
  7695. }
  7696. }
  7697. });
  7698. }));
  7699. } else if (promo.hasClass('emailoptinpromo')) {
  7700. pro.push(new Promise(resolve => {
  7701. $.ajax({
  7702. type: 'POST',
  7703. url: urlPath(`/newsletter/ajax/subscribeprofile/optin/${id[1]}`),
  7704. timeout: 6e4,
  7705. dataType: 'json',
  7706. data: {
  7707. ajax: 't',
  7708. emailsystoggle: 4
  7709. },
  7710. error(response, error, exception) {
  7711. if (window.DEBUG) {
  7712. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7713. response: response,
  7714. error: error,
  7715. exception: exception
  7716. });
  7717. }
  7718. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7719. resolve(true);
  7720. },
  7721. success(response) {
  7722. if (response.success) {
  7723. status.success(`Success:${response.text}`);
  7724. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7725. resolve(true);
  7726. } else {
  7727. status.error(`Error:${response.text}`);
  7728. resolve(true);
  7729. }
  7730. }
  7731. });
  7732. }));
  7733. } else if (promo.hasClass('watchingpromo')) {
  7734. pro.push(new Promise(resolve => {
  7735. const data = getUrlQuery(promo.attr('href'));
  7736. data.ajax = 't';
  7737. $.ajax({
  7738. type: 'POST',
  7739. url: urlPath(promo.attr('href')?.split(/[?#]/)[0]),
  7740. timeout: 6e4,
  7741. dataType: 'json',
  7742. data: data,
  7743. error(response, error, exception) {
  7744. if (window.DEBUG) {
  7745. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7746. response: response,
  7747. error: error,
  7748. exception: exception
  7749. });
  7750. }
  7751. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7752. resolve(true);
  7753. },
  7754. success(response) {
  7755. if (response.success) {
  7756. status.success(`Success:${response.text}`);
  7757. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7758. resolve(true);
  7759. } else {
  7760. status.error(`Error:${response.text}`);
  7761. resolve(true);
  7762. }
  7763. }
  7764. });
  7765. }));
  7766. } else if (!/the-challenge-of-adblock/gim.test(promo.attr('href'))) {
  7767. pro.push(new Promise(resolve => {
  7768. $.ajax({
  7769. type: 'POST',
  7770. url: urlPath(promo.attr('href')),
  7771. timeout: 6e4,
  7772. dataType: 'json',
  7773. data: {
  7774. ajax: 't'
  7775. },
  7776. error(response, error, exception) {
  7777. if (window.DEBUG) {
  7778. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7779. response: response,
  7780. error: error,
  7781. exception: exception
  7782. });
  7783. }
  7784. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7785. resolve(true);
  7786. },
  7787. success(response) {
  7788. if (response.success) {
  7789. status.success(`Success:${response.text}`);
  7790. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7791. resolve(true);
  7792. } else {
  7793. status.error(`Error:${response.text}`);
  7794. resolve(true);
  7795. }
  7796. }
  7797. });
  7798. }));
  7799. } else {
  7800. status.error(`Error:${i18n('unKnownTaskType')}`);
  7801. }
  7802. }
  7803. }
  7804. await Promise.all(pro);
  7805. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7806. return true;
  7807. }
  7808. scripts_echoLog({}).error(i18n('getFailed', 'TaskId'));
  7809. return false;
  7810. } catch (error) {
  7811. throwError(error, 'Indiedb.classifyTask');
  7812. return false;
  7813. }
  7814. }
  7815. #checkLogin() {
  7816. try {
  7817. if (!globalOptions.other.checkLogin) {
  7818. return true;
  7819. }
  7820. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7821. window.open('/members/login', '_self');
  7822. }
  7823. return true;
  7824. } catch (error) {
  7825. throwError(error, 'Indiedb.checkLogin');
  7826. return false;
  7827. }
  7828. }
  7829. async #checkLeftKey() {
  7830. try {
  7831. if (!globalOptions.other.checkLeftKey) {
  7832. return true;
  7833. }
  7834. if ($('a.buttonenter:contains("next time"), a.buttonenter:contains("Giveaway is closed")').length > 0) {
  7835. await external_Swal_default().fire({
  7836. icon: 'warning',
  7837. title: i18n('notice'),
  7838. text: i18n('giveawayEnded'),
  7839. confirmButtonText: i18n('confirm'),
  7840. cancelButtonText: i18n('cancel'),
  7841. showCancelButton: true
  7842. }).then(({
  7843. value
  7844. }) => {
  7845. if (value) {
  7846. window.close();
  7847. }
  7848. });
  7849. }
  7850. return true;
  7851. } catch (error) {
  7852. throwError(error, 'Indiedb.checkLeftKey');
  7853. return false;
  7854. }
  7855. }
  7856. }
  7857. const website_Indiedb = Indiedb;
  7858. const Keyhub_defaultTasksTemplate = {
  7859. steam: {
  7860. groupLinks: [],
  7861. officialGroupLinks: [],
  7862. wishlistLinks: [],
  7863. curatorLinks: []
  7864. },
  7865. discord: {
  7866. serverLinks: []
  7867. },
  7868. extra: {
  7869. videoTasks: []
  7870. },
  7871. links: []
  7872. };
  7873. const Keyhub_defaultTasks = JSON.stringify(Keyhub_defaultTasksTemplate);
  7874. class Keyhub extends website_Website {
  7875. name = 'Keyhub';
  7876. socialTasks = JSON.parse(Keyhub_defaultTasks);
  7877. undoneTasks = JSON.parse(Keyhub_defaultTasks);
  7878. buttons = [ 'doTask', 'undoTask' ];
  7879. static test() {
  7880. return window.location.host === 'key-hub.eu';
  7881. }
  7882. async after() {
  7883. try {
  7884. if (!this.#checkLogin()) {
  7885. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7886. }
  7887. if (!await this.#checkLeftKey()) {
  7888. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7889. }
  7890. $('.NSFW').hide();
  7891. } catch (error) {
  7892. throwError(error, 'Keyhub.after');
  7893. }
  7894. }
  7895. init() {
  7896. try {
  7897. const logStatus = scripts_echoLog({
  7898. text: i18n('initing')
  7899. });
  7900. if ($('a[href*="/connect/steam"]').length > 0) {
  7901. window.open('/connect/steam', '_self');
  7902. logStatus.warning(i18n('needLogin'));
  7903. return false;
  7904. }
  7905. if (!this.#getGiveawayId()) {
  7906. return false;
  7907. }
  7908. $('#VPNoverlay').hide();
  7909. $('#mainArticleSection').show();
  7910. this.initialized = true;
  7911. logStatus.success();
  7912. return true;
  7913. } catch (error) {
  7914. throwError(error, 'Keyhub.init');
  7915. return false;
  7916. }
  7917. }
  7918. async classifyTask(action) {
  7919. try {
  7920. const logStatus = scripts_echoLog({
  7921. text: i18n('getTasksInfo')
  7922. });
  7923. if (action === 'undo') {
  7924. this.socialTasks = GM_getValue(`khTasks-${this.giveawayId}`)?.tasks || JSON.parse(Keyhub_defaultTasks);
  7925. }
  7926. const tasks = $('.task:not(".googleads")').filter((index, element) => action === 'do' ? $(element).find('i.fa-check-circle:visible').length === 0 : true).find('a');
  7927. for (const task of tasks) {
  7928. let link = $(task).attr('href');
  7929. const taskDes = $(task).text().trim();
  7930. if (!link) {
  7931. continue;
  7932. }
  7933. if (/\/away\?data=/.test(link) || /steamcommunity\.com\/gid\//.test(link)) {
  7934. link = await getRedirectLink(link) || link;
  7935. }
  7936. if (/https?:\/\/key-hub\.eu\/connect\/discord/.test(link)) {
  7937. GM_openInTab(link, {
  7938. active: true
  7939. });
  7940. } else if (/steamcommunity\.com\/groups\//.test(link)) {
  7941. if (action === 'undo') {
  7942. this.socialTasks.steam.groupLinks.push(link);
  7943. }
  7944. if (action === 'do') {
  7945. this.undoneTasks.steam.groupLinks.push(link);
  7946. }
  7947. } else if (/steamcommunity\.com\/games\/[\d]+/.test(link)) {
  7948. if (action === 'undo') {
  7949. this.socialTasks.steam.officialGroupLinks.push(link);
  7950. }
  7951. if (action === 'do') {
  7952. this.undoneTasks.steam.officialGroupLinks.push(link);
  7953. }
  7954. } else if (/store\.steampowered\.com\/app\//.test(link) && /wishlist/gim.test(taskDes)) {
  7955. if (action === 'undo') {
  7956. this.socialTasks.steam.wishlistLinks.push(link);
  7957. }
  7958. if (action === 'do') {
  7959. this.undoneTasks.steam.wishlistLinks.push(link);
  7960. }
  7961. } else if (/store\.steampowered\.com\/curator\//.test(link)) {
  7962. if (action === 'undo') {
  7963. this.socialTasks.steam.curatorLinks.push(link);
  7964. }
  7965. if (action === 'do') {
  7966. this.undoneTasks.steam.curatorLinks.push(link);
  7967. }
  7968. } else if (/^https?:\/\/discord\.com\/invite\//.test(link)) {
  7969. if (action === 'undo') {
  7970. this.socialTasks.discord.serverLinks.push(link);
  7971. }
  7972. if (action === 'do') {
  7973. this.undoneTasks.discord.serverLinks.push(link);
  7974. }
  7975. } else if (/^javascript:videoTask.+/.test(link)) {
  7976. if (action === 'do') {
  7977. const taskData = link.match(/javascript:videoTask\('.+?','(.+?)'/)?.[1];
  7978. if (taskData) {
  7979. this.undoneTasks.extra.videoTasks.push(taskData);
  7980. }
  7981. }
  7982. } 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 {
  7983. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  7984. }
  7985. }
  7986. logStatus.success();
  7987. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7988. this.socialTasks = this.uniqueTasks(this.socialTasks);
  7989. if (window.DEBUG) {
  7990. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7991. }
  7992. GM_setValue(`khTasks-${this.giveawayId}`, {
  7993. tasks: this.socialTasks,
  7994. time: new Date().getTime()
  7995. });
  7996. return true;
  7997. } catch (error) {
  7998. throwError(error, 'Keyhub.classifyTask');
  7999. return false;
  8000. }
  8001. }
  8002. async #doScriptTask(data) {
  8003. try {
  8004. const logStatus = scripts_echoLog({
  8005. text: i18n('doingKeyhubTask')
  8006. });
  8007. const {
  8008. result,
  8009. statusText,
  8010. status,
  8011. data: response
  8012. } = await tools_httpRequest({
  8013. url: `/away?data=${data}`,
  8014. method: 'GET',
  8015. headers: {
  8016. origin: 'https://key-hub.eu',
  8017. referer: 'https://key-hub.eu/'
  8018. }
  8019. });
  8020. if (result === 'Success') {
  8021. if (response?.status === 200) {
  8022. logStatus.success();
  8023. return true;
  8024. }
  8025. logStatus.error(`Error:${response?.statusText}(${response?.status})`);
  8026. return false;
  8027. }
  8028. logStatus.error(`${result}:${statusText}(${status})`);
  8029. return false;
  8030. } catch (error) {
  8031. throwError(error, 'Keyhub.doScriptTask');
  8032. return false;
  8033. }
  8034. }
  8035. async extraDoTask({
  8036. videoTasks
  8037. }) {
  8038. try {
  8039. const pro = [];
  8040. for (const data of videoTasks) {
  8041. pro.push(this.#doScriptTask(data));
  8042. }
  8043. return Promise.all(pro).then(() => true);
  8044. } catch (error) {
  8045. throwError(error, 'Keyhub.extraDoTask');
  8046. return false;
  8047. }
  8048. }
  8049. #getGiveawayId() {
  8050. try {
  8051. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  8052. if (giveawayId) {
  8053. this.giveawayId = giveawayId;
  8054. return true;
  8055. }
  8056. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  8057. return false;
  8058. } catch (error) {
  8059. throwError(error, 'Keyhub.getGiveawayId');
  8060. return false;
  8061. }
  8062. }
  8063. async #checkLeftKey() {
  8064. try {
  8065. if (!globalOptions.other.checkLeftKey) {
  8066. return true;
  8067. }
  8068. const leftKey = $('#keysleft').text().trim();
  8069. if (leftKey === '0') {
  8070. await external_Swal_default().fire({
  8071. icon: 'warning',
  8072. title: i18n('notice'),
  8073. text: i18n('noKeysLeft'),
  8074. confirmButtonText: i18n('confirm'),
  8075. cancelButtonText: i18n('cancel'),
  8076. showCancelButton: true
  8077. }).then(({
  8078. value
  8079. }) => {
  8080. if (value) {
  8081. window.close();
  8082. }
  8083. });
  8084. }
  8085. return true;
  8086. } catch (error) {
  8087. throwError(error, 'Keyhub.checkLeftKey');
  8088. return false;
  8089. }
  8090. }
  8091. #checkLogin() {
  8092. try {
  8093. if (!globalOptions.other.checkLogin) {
  8094. return true;
  8095. }
  8096. if ($('a[href*="/connect/steam"]').length > 0) {
  8097. window.open('/connect/steam', '_self');
  8098. }
  8099. return true;
  8100. } catch (error) {
  8101. throwError(error, 'Keyhub.checkLogin');
  8102. return false;
  8103. }
  8104. }
  8105. }
  8106. const website_Keyhub = Keyhub;
  8107. const Givekey_defaultTasksTemplate = {
  8108. steam: {
  8109. groupLinks: [],
  8110. wishlistLinks: [],
  8111. curatorLinks: [],
  8112. curatorLikeLinks: []
  8113. },
  8114. twitter: {
  8115. userLinks: []
  8116. },
  8117. vk: {
  8118. nameLinks: []
  8119. },
  8120. discord: {
  8121. serverLinks: []
  8122. }
  8123. };
  8124. const Givekey_defaultTasks = JSON.stringify(Givekey_defaultTasksTemplate);
  8125. class Givekey extends website_Website {
  8126. name = 'Givekey';
  8127. tasks = [];
  8128. socialTasks = JSON.parse(Givekey_defaultTasks);
  8129. undoneTasks = JSON.parse(Givekey_defaultTasks);
  8130. userId;
  8131. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8132. static test() {
  8133. return window.location.host === 'givekey.ru';
  8134. }
  8135. async after() {
  8136. try {
  8137. await new Promise(resolve => {
  8138. const checker = setInterval(() => {
  8139. if ($('#navbarDropdown').length > 0) {
  8140. clearInterval(checker);
  8141. resolve(true);
  8142. }
  8143. }, 500);
  8144. });
  8145. if (!await this.#checkLeftKey()) {
  8146. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8147. }
  8148. } catch (error) {
  8149. throwError(error, 'Givekey.after');
  8150. }
  8151. }
  8152. init() {
  8153. try {
  8154. const logStatus = scripts_echoLog({
  8155. text: i18n('initing')
  8156. });
  8157. if ($('a[href*="/auth/steam"]').length > 0) {
  8158. window.open('/auth/steam', '_self');
  8159. logStatus.warning(i18n('needLogin'));
  8160. return false;
  8161. }
  8162. if (!this.#getGiveawayId()) {
  8163. return false;
  8164. }
  8165. const userId = $('meta[name="user-id"]').attr('content');
  8166. if (!userId) {
  8167. logStatus.error(i18n('getFailed', i18n('userId')));
  8168. return false;
  8169. }
  8170. this.userId = userId;
  8171. this.initialized = true;
  8172. logStatus.success();
  8173. return true;
  8174. } catch (error) {
  8175. throwError(error, 'Givekey.init');
  8176. return false;
  8177. }
  8178. }
  8179. async classifyTask(action) {
  8180. try {
  8181. const logStatus = scripts_echoLog({
  8182. text: i18n('getTasksInfo')
  8183. });
  8184. if (action === 'undo') {
  8185. this.socialTasks = GM_getValue(`gkTasks-${this.giveawayId}`)?.tasks || JSON.parse(Givekey_defaultTasks);
  8186. }
  8187. const tasks = $('.card-body:has("button") .row');
  8188. for (const task of tasks) {
  8189. const taskEle = $(task);
  8190. const isSuccess = /Complete/i.test(taskEle.find('button').text().trim());
  8191. if (isSuccess && action !== 'undo') {
  8192. continue;
  8193. }
  8194. const checkButton = taskEle.find('#task_check');
  8195. const taskId = checkButton.attr('data-id');
  8196. if (taskId) {
  8197. this.tasks.push(taskId);
  8198. }
  8199. if (action === 'verify') {
  8200. continue;
  8201. }
  8202. let href = taskEle.find('a').attr('href') || null;
  8203. const text = taskEle.find('a').text().trim();
  8204. const icon = taskEle.find('i');
  8205. if (!href || !text) {
  8206. continue;
  8207. }
  8208. if (/^https?:\/\/givekey\.ru\/giveaway\/[\d]+\/execution_task/.test(href)) {
  8209. href = await getRedirectLink(href);
  8210. }
  8211. if (!href) {
  8212. continue;
  8213. }
  8214. if (/^https?:\/\/vk\.com\//.test(href)) {
  8215. this.socialTasks.vk.nameLinks.push(href);
  8216. if (action === 'do' && !isSuccess) {
  8217. this.undoneTasks.vk.nameLinks.push(href);
  8218. }
  8219. } else if (/^https?:\/\/steamcommunity\.com\/groups/.test(href)) {
  8220. this.socialTasks.steam.groupLinks.push(href);
  8221. if (action === 'do' && !isSuccess) {
  8222. this.undoneTasks.steam.groupLinks.push(href);
  8223. }
  8224. } else if (/^https?:\/\/store\.steampowered\.com\/app\//.test(href)) {
  8225. this.socialTasks.steam.wishlistLinks.push(href);
  8226. if (action === 'do' && !isSuccess) {
  8227. this.undoneTasks.steam.wishlistLinks.push(href);
  8228. }
  8229. } else if (/Subscribe/gi.test(text) && icon.hasClass('fa-steam-square')) {
  8230. if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(href)) {
  8231. this.socialTasks.steam.curatorLinks.push(href);
  8232. if (action === 'do' && !isSuccess) {
  8233. this.undoneTasks.steam.curatorLinks.push(href);
  8234. }
  8235. } else {
  8236. this.socialTasks.steam.curatorLikeLinks.push(href);
  8237. if (action === 'do' && !isSuccess) {
  8238. this.undoneTasks.steam.curatorLikeLinks.push(href);
  8239. }
  8240. }
  8241. } else if (/^https?:\/\/twitter\.com\//.test(href) && /Subscribe/gi.test(text)) {
  8242. this.socialTasks.twitter.userLinks.push(href);
  8243. if (action === 'do' && !isSuccess) {
  8244. this.undoneTasks.twitter.userLinks.push(href);
  8245. }
  8246. } else if (icon.hasClass('fa-discord') || /^https?:\/\/discord\.com\/invite\//.test(href)) {
  8247. this.socialTasks.discord.serverLinks.push(href);
  8248. if (action === 'do' && !isSuccess) {
  8249. this.undoneTasks.discord.serverLinks.push(href);
  8250. }
  8251. } else {
  8252. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${text}(${href})`);
  8253. }
  8254. }
  8255. logStatus.success();
  8256. this.tasks = unique(this.tasks);
  8257. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8258. this.socialTasks = this.uniqueTasks(this.socialTasks);
  8259. if (window.DEBUG) {
  8260. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8261. }
  8262. GM_setValue(`gkTasks-${this.giveawayId}`, {
  8263. tasks: this.socialTasks,
  8264. time: new Date().getTime()
  8265. });
  8266. return true;
  8267. } catch (error) {
  8268. throwError(error, 'Givekey.classifyTask');
  8269. return false;
  8270. }
  8271. }
  8272. async verifyTask() {
  8273. try {
  8274. if (!this.initialized && !this.init()) {
  8275. return false;
  8276. }
  8277. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  8278. return false;
  8279. }
  8280. scripts_echoLog({}).warning(i18n('giveKeyNoticeBefore'));
  8281. const taskLength = this.tasks.length;
  8282. for (let i = 0; i < taskLength; i++) {
  8283. await this.#verify(this.tasks[i]);
  8284. if (i < taskLength - 1) {
  8285. await delay(15e3);
  8286. }
  8287. }
  8288. scripts_echoLog({}).success(i18n('allTasksComplete'));
  8289. scripts_echoLog({
  8290. html: `<li><font class="warning">${i18n('giveKeyNoticeAfter')}</font></li>`
  8291. });
  8292. return true;
  8293. } catch (error) {
  8294. throwError(error, 'Givekey.verifyTask');
  8295. return false;
  8296. }
  8297. }
  8298. async #verify(task) {
  8299. try {
  8300. const logStatus = scripts_echoLog({
  8301. html: `<li>${i18n('verifyingTask')}${task}...<font></font></li>`
  8302. });
  8303. return await new Promise(resolve => {
  8304. $.ajax({
  8305. url: 'https://givekey.ru/giveaway/task',
  8306. method: 'POST',
  8307. data: `id=${task}&user_id=${this.userId}`,
  8308. dataType: 'json',
  8309. headers: {
  8310. 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  8311. },
  8312. success: data => {
  8313. if (data.btn) {
  8314. $(`button[data-id=${this.userId}]`).html(data.btn);
  8315. }
  8316. if (data.status === 'ok') {
  8317. $(`.task_check_${data.id}`).html(`<button class="btn btn-success mb-2 btn-block" disabled>${data.btn}</button>`);
  8318. logStatus.success();
  8319. resolve(true);
  8320. } else if (data.status === 'end') {
  8321. logStatus.success();
  8322. scripts_echoLog({}).success(data.key);
  8323. resolve(true);
  8324. } else {
  8325. logStatus.error(`Error:${data.msg}`);
  8326. resolve(false);
  8327. }
  8328. },
  8329. error: xhr => {
  8330. logStatus.error(`Error:${xhr.statusText}(${xhr.status})`);
  8331. resolve(false);
  8332. }
  8333. });
  8334. });
  8335. } catch (error) {
  8336. throwError(error, 'Givekey.verify');
  8337. return false;
  8338. }
  8339. }
  8340. #getGiveawayId() {
  8341. try {
  8342. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  8343. if (giveawayId) {
  8344. this.giveawayId = giveawayId;
  8345. return true;
  8346. }
  8347. scripts_echoLog({
  8348. text: i18n('getFailed', 'GiveawayId')
  8349. });
  8350. return false;
  8351. } catch (error) {
  8352. throwError(error, 'Givekey.getGiveawayId');
  8353. return false;
  8354. }
  8355. }
  8356. async #checkLeftKey() {
  8357. try {
  8358. if (!globalOptions.other.checkLeftKey) {
  8359. return true;
  8360. }
  8361. if (!$('#keys_count').text()) {
  8362. await external_Swal_default().fire({
  8363. icon: 'warning',
  8364. title: i18n('notice'),
  8365. text: i18n('noKeysLeft'),
  8366. confirmButtonText: i18n('confirm'),
  8367. cancelButtonText: i18n('cancel'),
  8368. showCancelButton: true
  8369. }).then(({
  8370. value
  8371. }) => {
  8372. if (value) {
  8373. window.close();
  8374. }
  8375. });
  8376. }
  8377. return true;
  8378. } catch (error) {
  8379. throwError(error, 'Givekey.checkLeftKey');
  8380. return false;
  8381. }
  8382. }
  8383. }
  8384. const website_Givekey = Givekey;
  8385. class GiveeClub extends GiveawaySu {
  8386. name = 'GiveeClub';
  8387. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8388. static test() {
  8389. return /^https?:\/\/givee\.club\/.*?\/event\/[\d]+/.test(window.location.href);
  8390. }
  8391. async after() {
  8392. try {
  8393. if (!this.#checkLogin()) {
  8394. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8395. }
  8396. if (!await this.#checkLeftKey()) {
  8397. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8398. }
  8399. } catch (error) {
  8400. throwError(error, 'GiveeClub.after');
  8401. }
  8402. }
  8403. init() {
  8404. try {
  8405. const logStatus = scripts_echoLog({
  8406. text: i18n('initing')
  8407. });
  8408. if (!this.#checkLogin()) {
  8409. logStatus.warning(i18n('needLogin'));
  8410. return false;
  8411. }
  8412. if (!this.#getGiveawayId()) {
  8413. return false;
  8414. }
  8415. this.initialized = true;
  8416. logStatus.success();
  8417. return true;
  8418. } catch (error) {
  8419. throwError(error, 'GiveeClub.init');
  8420. return false;
  8421. }
  8422. }
  8423. async classifyTask(action) {
  8424. try {
  8425. const logStatus = scripts_echoLog({
  8426. text: i18n('getTasksInfo')
  8427. });
  8428. if (action === 'undo') {
  8429. this.socialTasks = GM_getValue(`gcTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  8430. return true;
  8431. }
  8432. this.undoneTasks = Giveawaysu_defaultTasks;
  8433. const pro = [];
  8434. const tasks = $('.event-actions tr');
  8435. for (const task of tasks) {
  8436. pro.push(new Promise(resolve => {
  8437. const taskDes = $(task).find('.event-action-label a');
  8438. const taskIcon = $(task).find('.event-action-icon i').attr('class') || '';
  8439. const taskName = taskDes.text().trim();
  8440. const taskType = $(task).find('button[data-type]')?.attr('data-type');
  8441. const taskFinished = $(task).find('.event-action-buttons .btn-success')?.length;
  8442. if (taskIcon.includes('ban') || /AdBlock/i.test(taskName) || taskIcon.includes('envelope') || taskFinished) {
  8443. return resolve(true);
  8444. }
  8445. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  8446. if (!taskLink) {
  8447. return resolve(false);
  8448. }
  8449. if (taskType === 'steam.group.join' && /^https?:\/\/steamcommunity\.com\/groups/.test(taskLink)) {
  8450. this.undoneTasks.steam.groupLinks.push(taskLink);
  8451. } else if (/like.*announcement/gi.test(taskName)) {
  8452. this.undoneTasks.steam.announcementLinks.push(taskLink);
  8453. } else if (taskType === 'steam.game.wishlist' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8454. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  8455. } else if (taskType === 'steam.game.wishlist' && taskDes.attr('data-steam-wishlist-appid')) {
  8456. this.undoneTasks.steam.wishlistLinks.push(`https://store.steampowered.com/app/${taskDes.attr('data-steam-wishlist-appid')}`);
  8457. } else if (taskType === 'steam.game.follow' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8458. this.undoneTasks.steam.followLinks.push(taskLink);
  8459. } else if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  8460. this.undoneTasks.steam.curatorLinks.push(taskLink);
  8461. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  8462. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  8463. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  8464. this.undoneTasks.steam.forumLinks.push(taskLink);
  8465. } else if (taskIcon.includes('discord')) {
  8466. this.undoneTasks.discord.serverLinks.push(taskLink);
  8467. } else if (taskIcon.includes('instagram')) {
  8468. this.undoneTasks.instagram.userLinks.push(taskLink);
  8469. } else if (taskIcon.includes('twitch')) {
  8470. this.undoneTasks.twitch.channelLinks.push(taskLink);
  8471. } else if (taskIcon.includes('reddit')) {
  8472. this.undoneTasks.reddit.redditLinks.push(taskLink);
  8473. } else if (/watch.*art/gim.test(taskName)) {
  8474. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  8475. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  8476. this.undoneTasks.youtube.channelLinks.push(taskLink);
  8477. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  8478. this.undoneTasks.youtube.likeLinks.push(taskLink);
  8479. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  8480. this.undoneTasks.vk.nameLinks.push(taskLink);
  8481. } else if (taskIcon.includes('twitter')) {
  8482. if (/https?:\/\/(twitter|x)\.com\/[^/]+\/?$/gim.test(taskLink)) {
  8483. this.undoneTasks.twitter.userLinks.push(taskLink);
  8484. } else if (/https?:\/\/(twitter|x)\.com\/[^/]+?\/status\/[\d]+/gim.test(taskLink)) {
  8485. this.undoneTasks.twitter.retweetLinks.push(taskLink);
  8486. }
  8487. } else {
  8488. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  8489. if (/follow.*button/gim.test(taskName)) {
  8490. this.undoneTasks.steam.followLinks.push(taskLink);
  8491. }
  8492. }
  8493. }
  8494. resolve(true);
  8495. }).catch(error => {
  8496. throwError(error, 'GiveeClub.classifyTask->getRedirectLink');
  8497. return false;
  8498. });
  8499. }));
  8500. }
  8501. await Promise.all(pro);
  8502. logStatus.success();
  8503. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8504. this.socialTasks = this.undoneTasks;
  8505. if (window.DEBUG) {
  8506. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8507. }
  8508. GM_setValue(`gcTasks-${this.giveawayId}`, {
  8509. tasks: this.socialTasks,
  8510. time: new Date().getTime()
  8511. });
  8512. return true;
  8513. } catch (error) {
  8514. throwError(error, 'GiveeClub.classifyTask');
  8515. return false;
  8516. }
  8517. }
  8518. async verifyTask() {
  8519. try {
  8520. const logStatus = scripts_echoLog({
  8521. text: i18n('giveeClubVerifyNotice')
  8522. });
  8523. const taskButtons = $('.event-actions tr button').has('i.glyphicon-refresh').not('[data-type="user.adblock"]');
  8524. for (const button of taskButtons) {
  8525. button.click();
  8526. if ($(button).attr('data-type') !== 'steam.game.wishlist') {
  8527. await delay(1e3);
  8528. }
  8529. }
  8530. logStatus.warning(i18n('giveeClubVerifyFinished'));
  8531. return true;
  8532. } catch (error) {
  8533. throwError(error, 'Givekey.verifyTask');
  8534. return false;
  8535. }
  8536. }
  8537. #checkLogin() {
  8538. try {
  8539. if (!globalOptions.other.checkLogin) {
  8540. return true;
  8541. }
  8542. if ($('a[href*="/account/auth"]').length > 0) {
  8543. window.open($('a[href*="/account/auth"]').attr('href'), '_self');
  8544. }
  8545. return true;
  8546. } catch (error) {
  8547. throwError(error, 'GiveeClub.checkLogin');
  8548. return false;
  8549. }
  8550. }
  8551. #getGiveawayId() {
  8552. const giveawayId = window.location.href.match(/\/event\/([\d]+)/)?.[1];
  8553. if (giveawayId) {
  8554. this.giveawayId = giveawayId;
  8555. return true;
  8556. }
  8557. scripts_echoLog({
  8558. text: i18n('getFailed', 'GiveawayId')
  8559. });
  8560. return false;
  8561. }
  8562. async #checkLeftKey() {
  8563. try {
  8564. if (!globalOptions.other.checkLeftKey) {
  8565. return true;
  8566. }
  8567. if ($('.event-ended').length > 0 && $('.event-winner').length === 0) {
  8568. await external_Swal_default().fire({
  8569. icon: 'warning',
  8570. title: i18n('notice'),
  8571. text: i18n('giveawayEnded'),
  8572. confirmButtonText: i18n('confirm'),
  8573. cancelButtonText: i18n('cancel'),
  8574. showCancelButton: true
  8575. }).then(({
  8576. value
  8577. }) => {
  8578. if (value) {
  8579. window.close();
  8580. }
  8581. });
  8582. }
  8583. return true;
  8584. } catch (error) {
  8585. throwError(error, 'Giveawaysu.checkLeftKey');
  8586. return false;
  8587. }
  8588. }
  8589. }
  8590. const website_GiveeClub = GiveeClub;
  8591. const defaultOptions = {
  8592. maxPoint: '99999999'
  8593. };
  8594. class OpiumPulses {
  8595. name = 'OpiumPulses';
  8596. options = {
  8597. ...defaultOptions,
  8598. ...GM_getValue('OpiumPulsesOptions')
  8599. };
  8600. maxPoints = 99999999;
  8601. myPoints = 0;
  8602. buttons = [ 'doFreeTask', 'doPointTask' ];
  8603. static test() {
  8604. return window.location.host === 'www.opiumpulses.com';
  8605. }
  8606. async after() {
  8607. try {
  8608. if (!this.#checkLogin()) {
  8609. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8610. }
  8611. this.maxPoints = parseInt(this.options.maxPoint, 10);
  8612. } catch (error) {
  8613. throwError(error, 'OpiumPulses.after');
  8614. }
  8615. }
  8616. async doFreeTask() {
  8617. try {
  8618. this.#toggleTask('FREE');
  8619. } catch (error) {
  8620. throwError(error, 'OpiumPulses.doFreeTask');
  8621. }
  8622. }
  8623. async doPointTask() {
  8624. try {
  8625. this.myPoints = parseInt($('.page-header__nav-func-user-nav-items.points-items').text().match(/[\d]+/gim)?.[0] || '0', 10);
  8626. this.#toggleTask('points');
  8627. } catch (error) {
  8628. throwError(error, 'OpiumPulses.doPointTask');
  8629. }
  8630. }
  8631. async #toggleTask(type) {
  8632. try {
  8633. const items = $(`.giveaways-page-item:contains('${type}'):not(:contains('ENTERED'))`);
  8634. for (const item of items) {
  8635. const needPoints = parseInt($(item).find('.giveaways-page-item-header-points').text().match(/[\d]+/gim)?.[0] || '999999', 10);
  8636. const name = $(item).find('.giveaways-page-item-footer-name').text().trim();
  8637. if (type === 'points' && needPoints > this.myPoints) {
  8638. scripts_echoLog({}).warning(`${i18n('noPoints')}: ${name}`);
  8639. } else if (type === 'points' && !needPoints) {
  8640. scripts_echoLog({}).warning(`${i18n('getNeedPointsFailed')}: ${name}`);
  8641. } else if (!(type === 'points' && needPoints > this.maxPoints)) {
  8642. const logStatus = scripts_echoLog({
  8643. text: `${i18n('joiningLottery')}<a href="${$(item).find('a.giveaways-page-item-img-btn-more').attr('href')}" target="_blank">${name}</a>...`
  8644. });
  8645. const aElement = $(item).find('a.giveaways-page-item-img-btn-enter:contains(\'enter\')');
  8646. if (aElement?.attr('onclick')?.includes('checkUser')) {
  8647. const giveawayId = aElement.attr('onclick')?.match(/[\d]+/)?.[0];
  8648. if (giveawayId) {
  8649. checkUser(giveawayId);
  8650. }
  8651. }
  8652. if (!aElement.attr('href')) {
  8653. logStatus.error('Error: No "href".');
  8654. continue;
  8655. }
  8656. const {
  8657. result,
  8658. statusText,
  8659. status,
  8660. data
  8661. } = await tools_httpRequest({
  8662. url: aElement.attr('href'),
  8663. method: 'GET'
  8664. });
  8665. if (result === 'Success') {
  8666. const {
  8667. result: result0,
  8668. statusText: statusText0,
  8669. status: status0,
  8670. data: data0
  8671. } = await tools_httpRequest({
  8672. url: data?.finalUrl,
  8673. method: 'GET'
  8674. });
  8675. if (data0?.responseText && /You've entered this giveaway/gim.test(data0.responseText)) {
  8676. logStatus.success();
  8677. const points = data0.responseText.match(/Points:[\s]*?([\d]+)/)?.[1];
  8678. if (type === 'points' && points) {
  8679. this.myPoints = parseInt(points, 10);
  8680. }
  8681. } else if (data0?.responseText && /You're not eligible to enter/gim.test(data0.responseText)) {
  8682. logStatus.error('You\'re not eligible to enter');
  8683. } else {
  8684. logStatus.error(`${result0}:${statusText0}(${status0})`);
  8685. }
  8686. } else {
  8687. logStatus.error(`${result}:${statusText}(${status})`);
  8688. }
  8689. }
  8690. }
  8691. scripts_echoLog({
  8692. text: '-----END-----'
  8693. });
  8694. } catch (error) {
  8695. throwError(error, 'OpiumPulses.toggleTask');
  8696. }
  8697. }
  8698. init() {
  8699. return true;
  8700. }
  8701. classifyTask() {
  8702. return true;
  8703. }
  8704. #checkLogin() {
  8705. try {
  8706. if (!globalOptions.other.checkLogin) {
  8707. return true;
  8708. }
  8709. if ($('a[href*="/site/login"]').length > 1) {
  8710. window.open('/site/login', '_self');
  8711. }
  8712. return true;
  8713. } catch (error) {
  8714. throwError(error, 'OpiumPulses.checkLogin');
  8715. return false;
  8716. }
  8717. }
  8718. }
  8719. const website_OpiumPulses = OpiumPulses;
  8720. const external_dayjs_namespaceObject = dayjs;
  8721. var external_dayjs_default = __webpack_require__.n(external_dayjs_namespaceObject);
  8722. const leftKeyChecker = {
  8723. async classify(link) {
  8724. try {
  8725. if (/^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(link)) {
  8726. return await this.giveawaySu(link);
  8727. }
  8728. if (/^https?:\/\/givee\.club\/[\w]+?\/event\/[\d]+/.test(link)) {
  8729. return await this.giveeClub(link);
  8730. }
  8731. if (/^https?:\/\/gleam\.io\/.+?\/.+/.test(link)) {
  8732. return await this.gleam(link);
  8733. }
  8734. if (/^https?:\/\/www\.indiedb\.com\/giveaways\/.+/.test(link)) {
  8735. return await this.indieDb(link);
  8736. }
  8737. if (/^https?:\/\/key-hub\.eu\/giveaway\/[\d]+/.test(link)) {
  8738. return await this.keyhub(link);
  8739. }
  8740. if (/^https?:\/\/opquests\.com\/quests\/[\d]+/.test(link)) {
  8741. return await this.opquests(link);
  8742. }
  8743. if (/^https?:\/\/itch\.io\/s\/[\d]+?\/.*/.test(link)) {
  8744. return await this.itch(link);
  8745. }
  8746. return false;
  8747. } catch (error) {
  8748. throwError(error, 'leftKeyChecker.classify');
  8749. return false;
  8750. }
  8751. },
  8752. async giveawaySu(link) {
  8753. try {
  8754. const {
  8755. result,
  8756. data
  8757. } = await tools_httpRequest({
  8758. url: link,
  8759. method: 'GET'
  8760. });
  8761. if (result === 'Success' && data?.status === 200) {
  8762. if (data.responseText.includes('class="steam-login"')) {
  8763. return false;
  8764. }
  8765. if (data.responseText.includes('class="giveaway-ended"')) {
  8766. return 'Ended';
  8767. }
  8768. return 'Active';
  8769. }
  8770. return false;
  8771. } catch (error) {
  8772. throwError(error, 'leftKeyChecker.giveawaySu');
  8773. return false;
  8774. }
  8775. },
  8776. async giveeClub(link) {
  8777. try {
  8778. const {
  8779. result,
  8780. data
  8781. } = await tools_httpRequest({
  8782. url: link,
  8783. method: 'GET'
  8784. });
  8785. if (result === 'Success' && data?.status === 200) {
  8786. if (data.responseText.includes('class="event-winner"')) {
  8787. return 'Won';
  8788. }
  8789. if (data.responseText.includes('class="event-ended"')) {
  8790. return 'Ended';
  8791. }
  8792. return 'Active';
  8793. }
  8794. return false;
  8795. } catch (error) {
  8796. throwError(error, 'leftKeyChecker.giveeClub');
  8797. return false;
  8798. }
  8799. },
  8800. async gleam(link) {
  8801. try {
  8802. const {
  8803. result,
  8804. data
  8805. } = await tools_httpRequest({
  8806. url: link,
  8807. method: 'GET'
  8808. });
  8809. if (result === 'Success' && data?.status === 200) {
  8810. if (/incentives&quot;:{&quot;[\d]+?&quot;:\[&quot;.+?&quot;\]/.test(data.responseText)) {
  8811. return 'Won';
  8812. }
  8813. const campaignDiv = data.responseText.match(/<div class='popup-blocks-container'[\w\W]+?'>/)?.[0];
  8814. if (!campaignDiv) {
  8815. return false;
  8816. }
  8817. const campaignString = $(campaignDiv).attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  8818. if (!campaignString) {
  8819. return false;
  8820. }
  8821. const {
  8822. campaign
  8823. } = JSON.parse(campaignString);
  8824. if (campaign.banned) {
  8825. return 'Banned';
  8826. }
  8827. if (campaign.finished) {
  8828. return 'Ended';
  8829. }
  8830. if (campaign.paused) {
  8831. return 'Paused';
  8832. }
  8833. if (new Date().getTime() < campaign.starts_at * 1e3) {
  8834. return 'NotStart';
  8835. }
  8836. return 'Active';
  8837. }
  8838. return false;
  8839. } catch (error) {
  8840. throwError(error, 'leftKeyChecker.gleam');
  8841. return false;
  8842. }
  8843. },
  8844. async indieDb(link) {
  8845. try {
  8846. const {
  8847. result,
  8848. data
  8849. } = await tools_httpRequest({
  8850. url: link,
  8851. method: 'GET'
  8852. });
  8853. if (result === 'Success' && data?.status === 200) {
  8854. if (data.responseText.includes('Congrats you WON')) {
  8855. return 'Won';
  8856. }
  8857. if (data.responseText.includes('Giveaway is closed') || data.responseText.includes('next time')) {
  8858. return 'Ended';
  8859. }
  8860. return 'Active';
  8861. }
  8862. return false;
  8863. } catch (error) {
  8864. throwError(error, 'leftKeyChecker.indieDb');
  8865. return false;
  8866. }
  8867. },
  8868. async keyhub(link) {
  8869. try {
  8870. const {
  8871. result,
  8872. data
  8873. } = await tools_httpRequest({
  8874. url: link,
  8875. method: 'GET'
  8876. });
  8877. if (result === 'Success' && data?.status === 200) {
  8878. const keysleft = data.responseText.match(/<span id="keysleft">([\d]+?)<\/span>/)?.[1];
  8879. if (!keysleft) {
  8880. return false;
  8881. }
  8882. if (keysleft === '0') {
  8883. return 'Ended';
  8884. }
  8885. return `Active(${keysleft})`;
  8886. }
  8887. return false;
  8888. } catch (error) {
  8889. throwError(error, 'leftKeyChecker.keyhub');
  8890. return false;
  8891. }
  8892. },
  8893. async opquests(link) {
  8894. try {
  8895. const {
  8896. result,
  8897. data
  8898. } = await tools_httpRequest({
  8899. url: link,
  8900. method: 'GET'
  8901. });
  8902. if (result === 'Success' && data?.status === 200) {
  8903. const keysleft = data.responseText.match(/<div class="">[\s]*?([\d]+?)[\s]*?of/)?.[1];
  8904. if (!keysleft) {
  8905. return false;
  8906. }
  8907. if (keysleft === '0') {
  8908. return 'Ended';
  8909. }
  8910. return `Active(${keysleft})`;
  8911. } else if (data?.status === 404) {
  8912. return 'Ended';
  8913. }
  8914. return false;
  8915. } catch (error) {
  8916. throwError(error, 'leftKeyChecker.opquests');
  8917. return false;
  8918. }
  8919. },
  8920. async itch(link) {
  8921. try {
  8922. const {
  8923. result,
  8924. data
  8925. } = await tools_httpRequest({
  8926. url: link,
  8927. method: 'GET'
  8928. });
  8929. if (result === 'Success' && data?.status === 200) {
  8930. const endDate = data.responseText.match(/{"start_date":"[0-9A-Z-:]+?".*?"end_date":"([0-9A-Z-:]+?)".*?}/)?.[1];
  8931. if (!endDate) {
  8932. return false;
  8933. }
  8934. if (new Date().getTime() > new Date(endDate).getTime()) {
  8935. return 'Ended';
  8936. }
  8937. return `Active(${external_dayjs_default()(endDate).format('YYYY-MM-DD HH:mm:ss')})`;
  8938. }
  8939. return false;
  8940. } catch (error) {
  8941. throwError(error, 'leftKeyChecker.itch');
  8942. return false;
  8943. }
  8944. }
  8945. };
  8946. const website_leftKeyChecker = leftKeyChecker;
  8947. const Keylol_defaultTasksTemplate = {
  8948. steam: {
  8949. groupLinks: [],
  8950. wishlistLinks: [],
  8951. curatorLinks: [],
  8952. curatorLikeLinks: [],
  8953. followLinks: [],
  8954. forumLinks: [],
  8955. announcementLinks: [],
  8956. workshopVoteLinks: [],
  8957. licenseLinks: []
  8958. },
  8959. discord: {
  8960. serverLinks: []
  8961. },
  8962. instagram: {
  8963. userLinks: []
  8964. },
  8965. vk: {
  8966. nameLinks: []
  8967. },
  8968. twitch: {
  8969. channelLinks: []
  8970. },
  8971. reddit: {
  8972. redditLinks: []
  8973. },
  8974. twitter: {
  8975. userLinks: [],
  8976. retweetLinks: []
  8977. },
  8978. youtube: {
  8979. channelLinks: [],
  8980. likeLinks: []
  8981. }
  8982. };
  8983. const Keylol_defaultTasks = JSON.stringify(Keylol_defaultTasksTemplate);
  8984. class Keylol extends website_Website {
  8985. name = 'Keylol';
  8986. socialTasks = JSON.parse(Keylol_defaultTasks);
  8987. undoneTasks = JSON.parse(Keylol_defaultTasks);
  8988. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect' ];
  8989. static test() {
  8990. 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'));
  8991. }
  8992. init() {
  8993. return true;
  8994. }
  8995. after() {
  8996. try {
  8997. const selector = this.name === 'Keylol' ? '#postlist>div[id^="post_"]:first' : 'div.container';
  8998. const mainPost = $(selector);
  8999. const discordLinks = mainPost.find('a[href*="discord.com"]:visible');
  9000. const redditLinks = mainPost.find('a[href*="reddit.com"]:visible');
  9001. const insLinks = mainPost.find('a[href*="instagram.com"]:visible');
  9002. const twitterLinks = mainPost.find('a[href*="twitter.com"]:visible,a[href*="x.com"]:visible');
  9003. const twitchLinks = mainPost.find('a[href*="twitch.tv"]:visible');
  9004. const vkLinks = mainPost.find('a[href*="vk.com"]:visible');
  9005. const steamStoreLinks = mainPost.find('a[href*="store.steampowered.com"]:visible');
  9006. const steamCommunityLinks = mainPost.find('a[href*="steamcommunity.com"]:visible');
  9007. const ytbLinks = mainPost.find('a[href*="youtube.com"]:visible');
  9008. if (discordLinks.length > 0) {
  9009. for (const discordLink of discordLinks) {
  9010. const link = $(discordLink).attr('href');
  9011. if (!(link && /^https?:\/\/discord\.com\/invite\/.+/.test(link))) {
  9012. continue;
  9013. }
  9014. this.#addBtn(discordLink, 'discord', 'serverLinks', link);
  9015. }
  9016. }
  9017. if (redditLinks.length > 0) {
  9018. for (const redditLink of redditLinks) {
  9019. const link = $(redditLink).attr('href');
  9020. if (!(link && /^https?:\/\/www\.reddit\.com\/(r|user)\/.+/.test(link))) {
  9021. continue;
  9022. }
  9023. this.#addBtn(redditLink, 'reddit', 'redditLinks', link);
  9024. }
  9025. }
  9026. if (insLinks.length > 0) {
  9027. for (const insLink of insLinks) {
  9028. const link = $(insLink).attr('href');
  9029. if (!(link && /^https:\/\/www\.instagram\.com\/.+/.test(link))) {
  9030. continue;
  9031. }
  9032. this.#addBtn(insLink, 'instagram', 'userLinks', link);
  9033. }
  9034. }
  9035. if (twitterLinks.length > 0) {
  9036. for (const twitterLink of twitterLinks) {
  9037. const link = $(twitterLink).attr('href');
  9038. if (!(link && /^https:\/\/twitter\.com\/.+/.test(link))) {
  9039. continue;
  9040. }
  9041. if (/https:\/\/twitter\.com\/.*?\/status\/[\d]+/.test(link)) {
  9042. this.#addBtn(twitterLink, 'twitter', 'retweetLinks', link);
  9043. } else {
  9044. this.#addBtn(twitterLink, 'twitter', 'userLinks', link);
  9045. }
  9046. }
  9047. }
  9048. if (twitchLinks.length > 0) {
  9049. for (const twitchLink of twitchLinks) {
  9050. const link = $(twitchLink).attr('href');
  9051. if (!(link && /^https:\/\/(www\.)?twitch\.tv\/.+/.test(link))) {
  9052. continue;
  9053. }
  9054. this.#addBtn(twitchLink, 'twitch', 'channelLinks', link);
  9055. }
  9056. }
  9057. if (vkLinks.length > 0) {
  9058. for (const vkLink of vkLinks) {
  9059. const link = $(vkLink).attr('href');
  9060. if (!(link && /^https:\/\/vk\.com\/.+/.test(link))) {
  9061. continue;
  9062. }
  9063. this.#addBtn(vkLink, 'vk', 'nameLinks', link);
  9064. }
  9065. }
  9066. if (steamStoreLinks.length > 0) {
  9067. for (const steamStoreLink of steamStoreLinks) {
  9068. const link = $(steamStoreLink).attr('href');
  9069. if (!link) {
  9070. continue;
  9071. }
  9072. if (/curator\/[\d]+/.test(link)) {
  9073. this.#addBtn(steamStoreLink, 'steam', 'curatorLinks', link);
  9074. } else if (/(publisher|developer|franchise)\/.+/.test(link)) {
  9075. this.#addBtn(steamStoreLink, 'steam', 'curatorLikeLinks', link);
  9076. } else if (/news(hub)?\/app\/[\d]+\/view\/[\d]+/.test(link)) {
  9077. this.#addBtn(steamStoreLink, 'steam', 'announcementLinks', link);
  9078. } else if (/app\/[\d]+/.test(link)) {
  9079. this.#addBtn(steamStoreLink, 'steam', 'followLinks', link);
  9080. this.#addBtn(steamStoreLink, 'steam', 'wishlistLinks', link);
  9081. }
  9082. }
  9083. }
  9084. if (steamCommunityLinks.length > 0) {
  9085. for (const steamCommunityLink of steamCommunityLinks) {
  9086. const link = $(steamCommunityLink).attr('href');
  9087. if (!link) {
  9088. continue;
  9089. }
  9090. if (/groups\/.+/.test(link)) {
  9091. this.#addBtn(steamCommunityLink, 'steam', 'groupLinks', link);
  9092. } else if (/announcements\/detail\/[\d]+/.test(link)) {
  9093. this.#addBtn(steamCommunityLink, 'steam', 'announcementLinks', link);
  9094. }
  9095. }
  9096. }
  9097. if (ytbLinks.length > 0) {
  9098. for (const ytbLink of ytbLinks) {
  9099. const link = $(ytbLink).attr('href');
  9100. if (!link) {
  9101. continue;
  9102. }
  9103. this.#addBtn(ytbLink, 'youtube', 'channelLinks', link);
  9104. this.#addBtn(ytbLink, 'youtube', 'likeLinks', link);
  9105. }
  9106. }
  9107. 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');
  9108. if (giveawayLinks.length > 0) {
  9109. for (const giveawayLink of giveawayLinks) {
  9110. const link = $(giveawayLink).attr('href');
  9111. if (!link) {
  9112. continue;
  9113. }
  9114. website_leftKeyChecker.classify(link).then(status => {
  9115. if (!status) {
  9116. return;
  9117. }
  9118. if (/^Active/.test(status)) {
  9119. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status active" title="${i18n('Active')}">${status}</font>`);
  9120. return;
  9121. }
  9122. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status not-active" title="${i18n(status)}">${status}</font>`);
  9123. }).catch(error => {
  9124. throwError(error, 'keylol.after -> leftKeyChecker');
  9125. });
  9126. }
  9127. }
  9128. if (this.name === 'Keylol') {
  9129. const asfLinks = mainPost.find('a[href^="#asf"]:visible');
  9130. if (asfLinks.length > 0) {
  9131. for (const asfLink of asfLinks) {
  9132. const link = $(asfLink).attr('href');
  9133. if (!link) {
  9134. continue;
  9135. }
  9136. this.#addBtn($(`a[href="${link}"]`).after('<span style="color: #ccc; margin: 0 -5px 0 5px"> | </span>').next()[0], 'steam', 'licenseLinks', `appid-${link.replace('#asf', '')}`);
  9137. }
  9138. }
  9139. const subLinks = mainPost.find('a[href*="steamdb.info/sub/"]:visible');
  9140. if (subLinks.length > 0) {
  9141. for (const subLink of subLinks) {
  9142. const link = $(subLink).attr('href');
  9143. if (!link) {
  9144. continue;
  9145. }
  9146. const subid = link.match(/^https:\/\/steamdb\.info\/sub\/([\d]+)/)?.[1];
  9147. if (!subid) {
  9148. continue;
  9149. }
  9150. this.#addBtn(subLink, 'steam', 'licenseLinks', `subid-${subid}`);
  9151. }
  9152. }
  9153. const asfLinks2 = mainPost.find('.blockcode:contains("addlicense"):visible');
  9154. if (asfLinks2.length > 0) {
  9155. for (const asfLink of asfLinks2) {
  9156. const appid = [ ...asfLink.innerText.matchAll(/a(pp)?\/([\d]+)/g) ].map(matched => matched?.[2]).filter(id => id) || [];
  9157. if (appid.length > 0) {
  9158. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `appid-${appid.join(',')}`);
  9159. }
  9160. const subid = asfLink.innerText.match(/[\d]+/g)?.filter(matched => !appid.includes(matched));
  9161. if (!subid || subid.length === 0) {
  9162. continue;
  9163. }
  9164. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `subid-${subid.join(',')}`);
  9165. }
  9166. }
  9167. }
  9168. if ($('#threadindex').length > 0) {
  9169. const [ targetNode ] = $('#postlist').children('div[id^="post_"]');
  9170. const config = {
  9171. childList: true
  9172. };
  9173. const observer = new MutationObserver(() => {
  9174. observer.disconnect();
  9175. this.after();
  9176. });
  9177. observer.observe(targetNode, config);
  9178. }
  9179. } catch (error) {
  9180. throwError(error, 'keylol.after');
  9181. }
  9182. }
  9183. classifyTask(action) {
  9184. try {
  9185. this.socialTasks = JSON.parse(Keylol_defaultTasks);
  9186. this.undoneTasks = JSON.parse(Keylol_defaultTasks);
  9187. const selectedBtns = $('.auto-task-keylol[selected="selected"]:visible');
  9188. for (const btn of selectedBtns) {
  9189. const button = $(btn);
  9190. const social = button.attr('data-social');
  9191. const type = button.attr('data-type');
  9192. const link = button.attr('data-link');
  9193. if (!(social && type && link)) {
  9194. continue;
  9195. }
  9196. if (action === 'do') {
  9197. this.undoneTasks[social][type].push(link);
  9198. }
  9199. if (action === 'undo') {
  9200. this.socialTasks[social][type].push(link);
  9201. }
  9202. }
  9203. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9204. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9205. if (window.DEBUG) {
  9206. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9207. }
  9208. return true;
  9209. } catch (error) {
  9210. throwError(error, 'Keylol.classifyTask');
  9211. return false;
  9212. }
  9213. }
  9214. selectAll() {
  9215. try {
  9216. $('.auto-task-keylol:visible').attr('selected', 'selected');
  9217. } catch (error) {
  9218. throwError(error, 'Keylol.selectAll');
  9219. }
  9220. }
  9221. selectNone() {
  9222. try {
  9223. $('.auto-task-keylol:visible').removeAttr('selected');
  9224. } catch (error) {
  9225. throwError(error, 'Keylol.selectNone');
  9226. }
  9227. }
  9228. invertSelect() {
  9229. try {
  9230. $('.auto-task-keylol:visible').each((index, element) => {
  9231. element.getAttribute('selected') ? element.removeAttribute('selected') : element.setAttribute('selected', 'selected');
  9232. });
  9233. } catch (error) {
  9234. throwError(error, 'Keylol.invertSelect');
  9235. }
  9236. }
  9237. #addBtn(before, social, linkType, link) {
  9238. try {
  9239. $(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>`);
  9240. } catch (error) {
  9241. throwError(error, 'keylol.addBtn');
  9242. }
  9243. }
  9244. }
  9245. const website_Keylol = Keylol;
  9246. const Opquests_defaultTasks = {
  9247. steam: {
  9248. groupLinks: [],
  9249. wishlistLinks: [],
  9250. followLinks: [],
  9251. curatorLikeLinks: []
  9252. }
  9253. };
  9254. class Opquests extends website_Website {
  9255. name = 'Opquests';
  9256. undoneTasks = {
  9257. ...Opquests_defaultTasks
  9258. };
  9259. buttons = [ 'doTask', 'verifyTask', 'getKey' ];
  9260. static test() {
  9261. return window.location.host === 'opquests.com';
  9262. }
  9263. async after() {
  9264. try {
  9265. if (!this.#checkLogin()) {
  9266. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9267. }
  9268. const opquestsVerifyTasks = GM_getValue('opquestsVerifyTasks') || [];
  9269. if (opquestsVerifyTasks.length > 0) {
  9270. const taskId = opquestsVerifyTasks.pop();
  9271. GM_setValue('opquestsVerifyTasks', opquestsVerifyTasks);
  9272. const [ verifyBtn ] = $(`#task_id[value="${taskId}"]`).parent().find('button[type="button"]').has('i.fa-check');
  9273. if (verifyBtn) {
  9274. verifyBtn.click();
  9275. return;
  9276. }
  9277. this.after();
  9278. return;
  9279. }
  9280. if (GM_getValue('opquestsVerifyTasks')) {
  9281. GM_deleteValue('opquestsVerifyTasks');
  9282. }
  9283. } catch (error) {
  9284. throwError(error, 'Opquests.after');
  9285. }
  9286. }
  9287. init() {
  9288. try {
  9289. const logStatus = scripts_echoLog({
  9290. text: i18n('initing')
  9291. });
  9292. if ($('a[href*="/auth/redirect"]').length > 0) {
  9293. window.open('/auth/redirect', '_self');
  9294. logStatus.warning(i18n('needLogin'));
  9295. return false;
  9296. }
  9297. if (!this.#getGiveawayId()) {
  9298. return false;
  9299. }
  9300. this.initialized = true;
  9301. logStatus.success();
  9302. return true;
  9303. } catch (error) {
  9304. throwError(error, 'Opquests.init');
  9305. return false;
  9306. }
  9307. }
  9308. async classifyTask(action) {
  9309. try {
  9310. if (action === 'undo') {
  9311. scripts_echoLog({
  9312. text: i18n('cannotUndo')
  9313. });
  9314. return false;
  9315. }
  9316. const logStatus = scripts_echoLog({
  9317. text: i18n('getTasksInfo')
  9318. });
  9319. const tasks = $('.w-full:contains("Validate") .items-center');
  9320. for (const task of tasks) {
  9321. const link = $(task).find('a:contains("Open")').attr('href');
  9322. const taskDes = $(task).find('div').eq(1).text().trim();
  9323. if (!link) {
  9324. continue;
  9325. }
  9326. if (/steamcommunity\.com\/groups\//.test(link)) {
  9327. this.undoneTasks.steam.groupLinks.push(link);
  9328. } else if (/store\.steampowered\.com\/app\//.test(link)) {
  9329. if (/wishlist/gim.test(taskDes)) {
  9330. this.undoneTasks.steam.wishlistLinks.push(link);
  9331. } else if (/follow/gim.test(taskDes)) {
  9332. this.undoneTasks.steam.followLinks.push(link);
  9333. }
  9334. } else if (/store\.steampowered\.com\/(publisher|developer|curator)\//.test(link) && /follow/gim.test(taskDes)) {
  9335. this.undoneTasks.steam.curatorLikeLinks.push(link);
  9336. } else {
  9337. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  9338. }
  9339. }
  9340. logStatus.success();
  9341. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9342. if (window.DEBUG) {
  9343. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9344. }
  9345. return true;
  9346. } catch (error) {
  9347. throwError(error, 'Opquests.classifyTask');
  9348. return false;
  9349. }
  9350. }
  9351. async verifyTask() {
  9352. try {
  9353. if (!this.initialized) {
  9354. this.init();
  9355. }
  9356. const tasks = $.makeArray($('.items-center').has('input[name="task_id"]')).map(ele => $(ele).find('input[name="task_id"]').val());
  9357. GM_setValue('opquestsVerifyTasks', tasks);
  9358. await this.#confirm();
  9359. this.after();
  9360. return true;
  9361. } catch (error) {
  9362. throwError(error, 'Opquests.verifyTask');
  9363. return false;
  9364. }
  9365. }
  9366. async #confirm() {
  9367. try {
  9368. const logStatus = scripts_echoLog({
  9369. html: `<li>${i18n('confirmingTask')}...<font></font></li>`
  9370. });
  9371. const {
  9372. result,
  9373. statusText,
  9374. status,
  9375. data
  9376. } = await tools_httpRequest({
  9377. url: `https://opquests.com/quests/${this.giveawayId}?confirm=1`,
  9378. method: 'GET',
  9379. nochche: true,
  9380. headers: {
  9381. origin: 'https://opquests.com',
  9382. referer: `https://opquests.com/warning?id=${this.giveawayId}`
  9383. }
  9384. });
  9385. if (result === 'Success') {
  9386. if (data?.status === 200) {
  9387. logStatus.success();
  9388. return true;
  9389. }
  9390. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9391. return false;
  9392. }
  9393. logStatus.error(`${result}:${statusText}(${status})`);
  9394. return false;
  9395. } catch (error) {
  9396. throwError(error, 'Opquests.confirm');
  9397. return false;
  9398. }
  9399. }
  9400. async getKey(isButton) {
  9401. try {
  9402. const logStatus = scripts_echoLog({
  9403. text: i18n('gettingKey')
  9404. });
  9405. const {
  9406. result,
  9407. statusText,
  9408. status,
  9409. data
  9410. } = await tools_httpRequest({
  9411. url: 'https://opquests.com/keys',
  9412. method: 'GET'
  9413. });
  9414. if (result === 'Success') {
  9415. if (data?.responseText) {
  9416. const key = $(data?.responseText).find(`div.items-center:contains("${$('h1.font-bold').text().trim().replace(' Quest', '')}")`).find('div.font-bold').next().text();
  9417. if (!key) {
  9418. logStatus.error('Error: Key was not found');
  9419. if (isButton) {
  9420. window.open('https://opquests.com/keys', '_self');
  9421. }
  9422. return false;
  9423. }
  9424. logStatus.success();
  9425. scripts_echoLog({}).success(key);
  9426. return true;
  9427. }
  9428. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9429. return false;
  9430. }
  9431. logStatus.error(`${result}:${statusText}(${status})`);
  9432. return false;
  9433. } catch (error) {
  9434. throwError(error, 'Opquests.getGiveawayId');
  9435. return false;
  9436. }
  9437. }
  9438. #getGiveawayId() {
  9439. try {
  9440. const giveawayId = window.location.href.match(/quests\/([\d]+)/)?.[1];
  9441. if (giveawayId) {
  9442. this.giveawayId = giveawayId;
  9443. return true;
  9444. }
  9445. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  9446. return false;
  9447. } catch (error) {
  9448. throwError(error, 'Opquests.getGiveawayId');
  9449. return false;
  9450. }
  9451. }
  9452. #checkLogin() {
  9453. try {
  9454. if (!globalOptions.other.checkLogin) {
  9455. return true;
  9456. }
  9457. if ($('a[href*="/auth/redirect"]').length > 0) {
  9458. window.open('/auth/redirect', '_self');
  9459. }
  9460. return true;
  9461. } catch (error) {
  9462. throwError(error, 'Opquests.checkLogin');
  9463. return false;
  9464. }
  9465. }
  9466. }
  9467. const website_Opquests = Opquests;
  9468. const Gleam_defaultTasksTemplate = {
  9469. steam: {
  9470. groupLinks: [],
  9471. wishlistLinks: [],
  9472. followLinks: [],
  9473. curatorLinks: [],
  9474. curatorLikeLinks: []
  9475. },
  9476. twitter: {
  9477. userLinks: [],
  9478. retweetLinks: []
  9479. },
  9480. twitch: {
  9481. channelLinks: []
  9482. },
  9483. discord: {
  9484. serverLinks: []
  9485. },
  9486. youtube: {
  9487. channelLinks: []
  9488. },
  9489. extra: {
  9490. gleam: []
  9491. }
  9492. };
  9493. const Gleam_defaultTasks = JSON.stringify(Gleam_defaultTasksTemplate);
  9494. class Gleam extends website_Website {
  9495. name = 'Gleam';
  9496. undoneTasks = JSON.parse(Gleam_defaultTasks);
  9497. socialTasks = JSON.parse(Gleam_defaultTasks);
  9498. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  9499. static test() {
  9500. return window.location.host === 'gleam.io';
  9501. }
  9502. before() {
  9503. try {
  9504. unsafeWindow.confirm = () => {};
  9505. unsafeWindow.alert = () => {};
  9506. unsafeWindow.prompt = () => {};
  9507. } catch (error) {
  9508. throwError(error, 'Gleam.before');
  9509. }
  9510. }
  9511. async after() {
  9512. try {
  9513. if (window.location.search.includes('8b07d23f4bfa65f9')) {
  9514. const checkComplete = setInterval(() => {
  9515. if ($('.entry-content .entry-method i.fa-check').length > 0) {
  9516. clearInterval(checkComplete);
  9517. window.close();
  9518. }
  9519. });
  9520. for (const task of $('.entry-content .entry-method')) {
  9521. const taskInfo = $(task).find('.user-links');
  9522. const expandInfo = $(task).find('.expandable');
  9523. const aElements = expandInfo.find('a.btn,a:contains(Continue),button:contains(Continue)');
  9524. if (aElements.length > 0) {
  9525. for (const element of aElements) {
  9526. const $element = $(element);
  9527. const href = $element.attr('href');
  9528. $element.removeAttr('href')[0].click();
  9529. $element.attr('href', href);
  9530. await delay(1e3);
  9531. }
  9532. }
  9533. taskInfo[0].click();
  9534. await delay(1e3);
  9535. }
  9536. scripts_echoLog({}).warning(i18n('gleamTaskNotice'));
  9537. } else if (!await this.#checkLeftKey()) {
  9538. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  9539. }
  9540. } catch (error) {
  9541. throwError(error, 'Gleam.after');
  9542. }
  9543. }
  9544. init() {
  9545. try {
  9546. const logStatus = scripts_echoLog({
  9547. text: i18n('initing')
  9548. });
  9549. if (!this.#getGiveawayId()) {
  9550. return false;
  9551. }
  9552. this.initialized = true;
  9553. logStatus.success();
  9554. return true;
  9555. } catch (error) {
  9556. throwError(error, 'Gleam.init');
  9557. return false;
  9558. }
  9559. }
  9560. async classifyTask(action) {
  9561. try {
  9562. const logStatus = scripts_echoLog({
  9563. text: i18n('getTasksInfo')
  9564. });
  9565. if (action === 'undo') {
  9566. this.socialTasks = GM_getValue(`gleamTasks-${this.giveawayId}`)?.tasks || JSON.parse(Gleam_defaultTasks);
  9567. }
  9568. const tasks = $('.entry-content .entry-method');
  9569. for (const task of tasks) {
  9570. const $task = $(task);
  9571. if (action === 'do' && $task.find('i.fa-question').length === 0) {
  9572. continue;
  9573. }
  9574. const socialIcon = $task.find('.icon-wrapper i');
  9575. const taskInfo = $task.find('.user-links');
  9576. const taskText = taskInfo.text().trim();
  9577. const expandInfo = $task.find('.expandable');
  9578. const aElements = expandInfo.find('a.btn');
  9579. if (aElements.length > 0) {
  9580. for (const element of aElements) {
  9581. const $element = $(element);
  9582. const href = $element.attr('href');
  9583. $element.removeAttr('href')[0].click();
  9584. $element.attr('href', href);
  9585. }
  9586. }
  9587. if (socialIcon.hasClass('fa-twitter') || socialIcon.hasClass('fa-x-twitter')) {
  9588. const link = $task.find('a[href^="https://twitter.com/"],a[href^="https://x.com/"]').attr('href');
  9589. if (!link) {
  9590. continue;
  9591. }
  9592. if (/follow/gi.test(taskText)) {
  9593. if (action === 'undo') {
  9594. this.socialTasks.twitter.userLinks.push(link);
  9595. }
  9596. if (action === 'do') {
  9597. this.undoneTasks.twitter.userLinks.push(link);
  9598. }
  9599. } else if (/retweet/gim.test(taskText)) {
  9600. if (action === 'undo') {
  9601. this.socialTasks.twitter.retweetLinks.push(link);
  9602. }
  9603. if (action === 'do') {
  9604. this.undoneTasks.twitter.retweetLinks.push(link);
  9605. }
  9606. }
  9607. } else if (socialIcon.hasClass('fa-twitch')) {
  9608. if (/follow/gim.test(taskText)) {
  9609. const link = $task.find('a[href^="https://twitch.tv/"]').attr('href');
  9610. if (!link) {
  9611. continue;
  9612. }
  9613. if (action === 'undo') {
  9614. this.socialTasks.twitch.channelLinks.push(link);
  9615. }
  9616. if (action === 'do') {
  9617. this.undoneTasks.twitch.channelLinks.push(link);
  9618. }
  9619. }
  9620. } else if (socialIcon.hasClass('fa-discord')) {
  9621. if (/join/gim.test(taskText)) {
  9622. let link = $task.find('a[href^="https://discord.com/invite/"]').attr('href');
  9623. if (!link) {
  9624. const ggLink = $task.find('a[href^="https://discord.gg/"]').attr('href')?.match(/discord\.gg\/([^/]+)/)?.[1];
  9625. if (!ggLink) {
  9626. continue;
  9627. }
  9628. link = `https://discord.com/invite/${ggLink}`;
  9629. }
  9630. if (action === 'undo') {
  9631. this.socialTasks.discord.serverLinks.push(link);
  9632. }
  9633. if (action === 'do') {
  9634. this.undoneTasks.discord.serverLinks.push(link);
  9635. }
  9636. }
  9637. } else if (socialIcon.hasClass('fa-external-link-square-alt')) {
  9638. continue;
  9639. } else if (socialIcon.hasClass('fa-youtube')) {
  9640. if (/subscribe/gim.test(taskText)) {
  9641. const link = $task.find('a[href^="https://www.youtube.com/channel/"]').attr('href');
  9642. if (!link) {
  9643. continue;
  9644. }
  9645. if (action === 'undo') {
  9646. this.socialTasks.youtube.channelLinks.push(link);
  9647. }
  9648. if (action === 'do') {
  9649. this.undoneTasks.youtube.channelLinks.push(link);
  9650. }
  9651. }
  9652. } else if (socialIcon.attr('class')?.includes('steam')) {
  9653. if (/join.*group/gi.test(taskText)) {
  9654. const link = $task.find('a[href^="https://steamcommunity.com/groups/"]').attr('href');
  9655. if (!link) {
  9656. continue;
  9657. }
  9658. if (action === 'undo') {
  9659. this.socialTasks.steam.groupLinks.push(link);
  9660. }
  9661. if (action === 'do') {
  9662. this.undoneTasks.steam.groupLinks.push(link);
  9663. }
  9664. } else if (/follow.*curator/gi.test(taskText)) {
  9665. const link = $task.find('a[href^="https://store.steampowered.com/curator/"]').attr('href');
  9666. if (!link) {
  9667. continue;
  9668. }
  9669. if (action === 'undo') {
  9670. this.socialTasks.steam.curatorLinks.push(link);
  9671. }
  9672. if (action === 'do') {
  9673. this.undoneTasks.steam.curatorLinks.push(link);
  9674. }
  9675. }
  9676. } else if (socialIcon.hasClass('fa-bullhorn') && /Complete|Increase/gi.test(taskText)) {
  9677. if (action !== 'do') {
  9678. continue;
  9679. }
  9680. const gleamLink = await this.#getGleamLink(taskText);
  9681. if (!gleamLink) {
  9682. continue;
  9683. }
  9684. this.undoneTasks.extra.gleam.push(gleamLink);
  9685. } 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 {
  9686. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskText}`);
  9687. }
  9688. }
  9689. logStatus.success();
  9690. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9691. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9692. if (window.DEBUG) {
  9693. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9694. }
  9695. GM_setValue(`gleamTasks-${this.giveawayId}`, {
  9696. tasks: this.socialTasks,
  9697. time: new Date().getTime()
  9698. });
  9699. return true;
  9700. } catch (error) {
  9701. throwError(error, 'Gleam.classifyTask');
  9702. return false;
  9703. }
  9704. }
  9705. async extraDoTask({
  9706. gleam
  9707. }) {
  9708. try {
  9709. const pro = [];
  9710. for (const link of gleam) {
  9711. pro.push(this.#doGleamTask(link));
  9712. }
  9713. return Promise.all(pro).then(() => true);
  9714. } catch (error) {
  9715. throwError(error, 'Gleam.extraDoTask');
  9716. return false;
  9717. }
  9718. }
  9719. async verifyTask() {
  9720. try {
  9721. scripts_echoLog({
  9722. text: `${i18n('verifyingTask')}...`
  9723. });
  9724. const tasks = $('.entry-content .entry-method');
  9725. unsafeWindow._OxA = '_OxA';
  9726. for (const task of tasks) {
  9727. if ($('[campaign-key="campaign.key"]').length > 0) {
  9728. return scripts_echoLog({
  9729. text: i18n('campaign')
  9730. });
  9731. }
  9732. const $task = $(task);
  9733. if ($task.find('i.fa-question').length === 0) {
  9734. continue;
  9735. }
  9736. const taskInfo = $task.find('.user-links');
  9737. taskInfo[0].click();
  9738. const aElements = $task.find('.expandable').find('a.btn');
  9739. if (aElements.length > 0) {
  9740. for (const element of aElements) {
  9741. const $element = $(element);
  9742. const href = $element.attr('href');
  9743. $element.removeAttr('href')[0].click();
  9744. $element.attr('href', href);
  9745. }
  9746. }
  9747. unsafeWindow.$hookTimer?.setSpeed(1e3);
  9748. const visitBtn = $task.find('.expandable').find('span:contains(more seconds),button:contains(more seconds)').filter(':visible');
  9749. if (visitBtn.length > 0 && unsafeWindow.$hookTimer) {
  9750. const newTab = GM_openInTab('', {
  9751. active: true
  9752. });
  9753. await delay(1e3);
  9754. newTab?.close();
  9755. window.focus();
  9756. }
  9757. await delay(3e3);
  9758. unsafeWindow.$hookTimer?.setSpeed(1);
  9759. const expandInfo = $task.find('.expandable');
  9760. const [ input ] = expandInfo.find('input');
  9761. if (input) {
  9762. const evt = new Event('input', {
  9763. bubbles: true,
  9764. cancelable: true,
  9765. composed: true
  9766. });
  9767. const valuelimit = [ ...expandInfo.text().matchAll(/"(.+?)"/g) ].at(-1)?.[1];
  9768. input.value = valuelimit || 'vloot';
  9769. input.dispatchEvent(evt);
  9770. await delay(1e3);
  9771. }
  9772. await this.#checkSync();
  9773. const continueBtn = $task.find('.expandable').find('span:contains(Continue),button:contains(Continue)');
  9774. for (const button of continueBtn) {
  9775. button.click();
  9776. await delay(500);
  9777. await this.#checkSync();
  9778. }
  9779. }
  9780. scripts_echoLog({
  9781. text: i18n('verifiedGleamTasks')
  9782. });
  9783. } catch (error) {
  9784. throwError(error, 'Gleam.verifyTask');
  9785. return false;
  9786. }
  9787. }
  9788. async #checkSync() {
  9789. try {
  9790. return await new Promise(resolve => {
  9791. const checker = setInterval(() => {
  9792. if ($('.entry-content .entry-method i.fa-sync').length === 0) {
  9793. clearInterval(checker);
  9794. resolve(true);
  9795. }
  9796. }, 500);
  9797. });
  9798. } catch (error) {
  9799. throwError(error, 'Gleam.checkSync');
  9800. return false;
  9801. }
  9802. }
  9803. async #doGleamTask(link) {
  9804. try {
  9805. const logStatus = scripts_echoLog({
  9806. text: i18n('doingGleamTask')
  9807. });
  9808. return await new Promise(resolve => {
  9809. GM_openInTab(`${link}?8b07d23f4bfa65f9`, {
  9810. active: true,
  9811. insert: true,
  9812. setParent: true
  9813. }).onclose = () => {
  9814. logStatus.success();
  9815. resolve(true);
  9816. };
  9817. });
  9818. } catch (error) {
  9819. throwError(error, 'Gleam.doGleamTask');
  9820. return false;
  9821. }
  9822. }
  9823. #getGiveawayId() {
  9824. try {
  9825. const giveawayId = window.location.pathname;
  9826. if (giveawayId) {
  9827. this.giveawayId = giveawayId;
  9828. return true;
  9829. }
  9830. scripts_echoLog({
  9831. text: i18n('getFailed', 'GiveawayId')
  9832. });
  9833. return false;
  9834. } catch (error) {
  9835. throwError(error, 'Gleam.getGiveawayId');
  9836. return false;
  9837. }
  9838. }
  9839. async #getGleamLink(title) {
  9840. try {
  9841. const logStatus = scripts_echoLog({
  9842. text: i18n('gettingGleamLink')
  9843. });
  9844. const {
  9845. result,
  9846. statusText,
  9847. status,
  9848. data
  9849. } = await tools_httpRequest({
  9850. url: 'https://www.vloot.io/api/v1/giveaways',
  9851. method: 'GET',
  9852. responseType: 'json'
  9853. });
  9854. if (result === 'Success') {
  9855. if (data?.status === 200 && data?.response?.Success === true && data?.response?.Data) {
  9856. const {
  9857. link
  9858. } = data.response.Data.find(giveaway => title.replace(/[\s]/g, '').toLowerCase().includes(giveaway.title.replace(/[\s]/g, '').toLowerCase())) || {};
  9859. if (link) {
  9860. logStatus.success();
  9861. return link;
  9862. }
  9863. logStatus.error(`Error:${i18n('getLinkFailed')}`);
  9864. return false;
  9865. }
  9866. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9867. return false;
  9868. }
  9869. logStatus.error(`${result}:${statusText}(${status})`);
  9870. return false;
  9871. } catch (error) {
  9872. throwError(error, 'Gleam.getGleamLink');
  9873. return false;
  9874. }
  9875. }
  9876. async #checkLeftKey() {
  9877. try {
  9878. if (!globalOptions.other.checkLeftKey) {
  9879. return true;
  9880. }
  9881. const campaignString = $('div.popup-blocks-container').attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  9882. if (!campaignString) {
  9883. return false;
  9884. }
  9885. const {
  9886. campaign,
  9887. incentive
  9888. } = JSON.parse(campaignString);
  9889. const controllerString = $('div.campaign.reward').attr('ng-init')?.match(/initContestant\(([\w\W]+?)\);/)?.[1];
  9890. let ownedKey = false;
  9891. if (controllerString) {
  9892. if (JSON.parse(controllerString).contestant?.claims?.incentives?.[incentive.id]?.length) {
  9893. ownedKey = true;
  9894. }
  9895. }
  9896. if (campaign.banned || campaign.finished && !ownedKey || campaign.paused || new Date().getTime() < campaign.starts_at * 1e3) {
  9897. await external_Swal_default().fire({
  9898. icon: 'warning',
  9899. title: i18n('notice'),
  9900. text: i18n('giveawayNotWork'),
  9901. confirmButtonText: i18n('confirm'),
  9902. cancelButtonText: i18n('cancel'),
  9903. showCancelButton: true
  9904. }).then(({
  9905. value
  9906. }) => {
  9907. if (value) {
  9908. window.close();
  9909. }
  9910. });
  9911. }
  9912. return true;
  9913. } catch (error) {
  9914. throwError(error, 'Gleam.checkLeftKey');
  9915. return false;
  9916. }
  9917. }
  9918. }
  9919. const website_Gleam = Gleam;
  9920. const SweepWidget_defaultOptions = {
  9921. username: '',
  9922. email: ''
  9923. };
  9924. class SweepWidget extends website_Website {
  9925. name = 'SweepWidget';
  9926. options = {
  9927. ...SweepWidget_defaultOptions,
  9928. ...GM_getValue('SweepWidgetOptions')
  9929. };
  9930. buttons = [ 'doTask' ];
  9931. static test() {
  9932. return /^https?:\/\/sweepwidget\.com\/view\/[\d]+/.test(window.location.href);
  9933. }
  9934. async after() {
  9935. try {
  9936. if (!this.#checkLogin()) {
  9937. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9938. }
  9939. } catch (error) {
  9940. throwError(error, 'SweepWidget.after');
  9941. }
  9942. }
  9943. init() {
  9944. try {
  9945. const logStatus = scripts_echoLog({
  9946. text: i18n('initing')
  9947. });
  9948. if (!this.#checkLogin()) {
  9949. logStatus.warning(i18n('needLogin'));
  9950. return false;
  9951. }
  9952. if (!this.#getGiveawayId()) {
  9953. return false;
  9954. }
  9955. this.initialized = true;
  9956. logStatus.success();
  9957. return true;
  9958. } catch (error) {
  9959. throwError(error, 'SweepWidget.init');
  9960. return false;
  9961. }
  9962. }
  9963. classifyTask() {
  9964. return true;
  9965. }
  9966. async doTask() {
  9967. try {
  9968. if ($('#unlock_rewards_main_wrapper').length === 0) {
  9969. if ($('input[name="sw__login_name"]:visible').length > 0) {
  9970. $('input[name="sw__login_name"]').val(this.options.username);
  9971. }
  9972. if ($('input[name="sw__login_email"]:visible').length > 0) {
  9973. $('input[name="sw__login_email"]').val(this.options.email);
  9974. }
  9975. if ($('#sw_login_button:visible').length > 0) {
  9976. $('#sw_login_button')[0].click();
  9977. }
  9978. if (!await this.#checkEnter()) {
  9979. return false;
  9980. }
  9981. }
  9982. const logStatus = scripts_echoLog({
  9983. text: i18n('SweepWidgetNotice')
  9984. });
  9985. const tasks = $('#sw_inner_entry_methods_l2_wrapper>div.sw_entry');
  9986. for (const task of tasks) {
  9987. const $task = $(task);
  9988. if ($task.find('i.fa-check:visible').length > 0) {
  9989. continue;
  9990. }
  9991. const title = $task.find('.sw_text_inner');
  9992. title[0].click();
  9993. const aElement = $task.find('a.sw_link');
  9994. const link = aElement.attr('href');
  9995. aElement.attr('href', '#a').attr('target', '_self');
  9996. aElement[0]?.click();
  9997. await delay(300);
  9998. aElement.attr('href', link).attr('target', '_blank');
  9999. $task.find('input[type="text"]').val('test');
  10000. const verifyBtn = $task.find('input.sw_verify');
  10001. if (verifyBtn.prop('disabled') === true) {
  10002. title[0].click();
  10003. await delay(300);
  10004. title[0].click();
  10005. await delay(300);
  10006. }
  10007. $task.find('input.sw_verify').removeAttr('disabled')[0]?.click();
  10008. await this.#checkFinish($task);
  10009. await delay(parseInt(`${Math.random() * (3e3 - 1e3 + 1) + 1e3}`, 10));
  10010. }
  10011. logStatus.success();
  10012. return true;
  10013. } catch (error) {
  10014. throwError(error, 'SweepWidget.doTask');
  10015. return false;
  10016. }
  10017. }
  10018. #checkLogin() {
  10019. try {
  10020. if ($('#twitter_login_button').length > 0) {
  10021. $('#twitter_login_button')[0].click();
  10022. }
  10023. return true;
  10024. } catch (error) {
  10025. throwError(error, 'SweepWidget.checkLogin');
  10026. return false;
  10027. }
  10028. }
  10029. #getGiveawayId() {
  10030. try {
  10031. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  10032. if (giveawayId) {
  10033. this.giveawayId = giveawayId;
  10034. return true;
  10035. }
  10036. scripts_echoLog({
  10037. text: i18n('getFailed', 'GiveawayId')
  10038. });
  10039. return false;
  10040. } catch (error) {
  10041. throwError(error, 'SweepWidget.getGiveawayId');
  10042. return false;
  10043. }
  10044. }
  10045. async #checkEnter() {
  10046. try {
  10047. return new Promise(resolve => {
  10048. const checker = setInterval(() => {
  10049. if ($('#unlock_rewards_main_wrapper').length > 0) {
  10050. clearInterval(checker);
  10051. resolve(true);
  10052. }
  10053. }, 500);
  10054. });
  10055. } catch (error) {
  10056. throwError(error, 'SweepWidget.checkEnter');
  10057. return false;
  10058. }
  10059. }
  10060. async #checkFinish($task) {
  10061. try {
  10062. return new Promise(resolve => {
  10063. const checker = setInterval(() => {
  10064. if ($task.find('i.fa-check:visible').length > 0 || $task.find('.sw_entry_input:visible').length === 0) {
  10065. clearInterval(checker);
  10066. resolve(true);
  10067. }
  10068. }, 500);
  10069. });
  10070. } catch (error) {
  10071. throwError(error, 'SweepWidget.checkFinish');
  10072. return false;
  10073. }
  10074. }
  10075. }
  10076. const website_SweepWidget = SweepWidget;
  10077. const defaultWhiteList = {
  10078. discord: {
  10079. servers: []
  10080. },
  10081. instagram: {
  10082. users: []
  10083. },
  10084. twitch: {
  10085. channels: []
  10086. },
  10087. twitter: {
  10088. users: [],
  10089. retweets: [],
  10090. likes: []
  10091. },
  10092. vk: {
  10093. names: []
  10094. },
  10095. youtube: {
  10096. channels: [],
  10097. likes: []
  10098. },
  10099. reddit: {
  10100. reddits: []
  10101. },
  10102. steam: {
  10103. groups: [],
  10104. officialGroups: [],
  10105. wishlists: [],
  10106. follows: [],
  10107. forums: [],
  10108. workshops: [],
  10109. curators: [],
  10110. workshopVotes: [],
  10111. curatorLikes: [],
  10112. announcements: [],
  10113. licenses: [],
  10114. playtests: []
  10115. }
  10116. };
  10117. const link2id = async function(type) {
  10118. try {
  10119. const link = $('#socialLink').val();
  10120. let id = '';
  10121. switch (type) {
  10122. case 'discord.servers':
  10123. id = link.match(/invite\/(.+)/)?.[1] || '';
  10124. break;
  10125.  
  10126. case 'instagram.users':
  10127. id = link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1] || '';
  10128. break;
  10129.  
  10130. case 'twitch.channels':
  10131. id = link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2] || '';
  10132. break;
  10133.  
  10134. case 'twitter.users':
  10135. id = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || '';
  10136. break;
  10137.  
  10138. case 'twitter.retweets':
  10139. id = link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1] || '';
  10140. break;
  10141.  
  10142. case 'vk.names':
  10143. id = link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1] || '';
  10144. break;
  10145.  
  10146. case 'youtube.channels':
  10147. id = (await getInfo(link, 'channel'))?.params?.channelId || '';
  10148. break;
  10149.  
  10150. case 'youtube.likes':
  10151. id = (await getInfo(link, 'likeVideo'))?.params?.videoId || '';
  10152. break;
  10153.  
  10154. case 'reddit.reddits':
  10155. id = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1] || link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1] || '';
  10156. break;
  10157.  
  10158. case 'steam.groups':
  10159. id = link.match(/groups\/(.+)\/?/)?.[1] || '';
  10160. break;
  10161.  
  10162. case 'steam.wishlists':
  10163. case 'steam.follows':
  10164. case 'steam.forums':
  10165. id = link.match(/app\/([\d]+)/)?.[1] || '';
  10166. break;
  10167.  
  10168. case 'steam.workshops':
  10169. id = link.match(/\?id=([\d]+)/)?.[1] || '';
  10170. break;
  10171.  
  10172. case 'steam.curators':
  10173. {
  10174. if (link.includes('curator')) {
  10175. id = link.match(/curator\/([\d]+)/)?.[1] || '';
  10176. } else {
  10177. const param = link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3);
  10178. if (!param || param.length !== 2) {
  10179. break;
  10180. }
  10181. const steam = new social_Steam();
  10182. if (await steam.init()) {
  10183. id = await steam.getCuratorId(param[0], param[1]) || '';
  10184. }
  10185. }
  10186. }
  10187. break;
  10188. }
  10189. return id;
  10190. } catch (error) {
  10191. throwError(error, 'link2id');
  10192. return i18n('getFailed', 'id');
  10193. }
  10194. };
  10195. const disabledType = {
  10196. steam: [ 'workshopVotes', 'curatorLikes', 'announcements' ],
  10197. twitter: [ 'likes' ]
  10198. };
  10199. const assignWhiteList = whiteList => {
  10200. try {
  10201. const newWhiteList = {};
  10202. for (const [ key, value ] of Object.entries(defaultWhiteList)) {
  10203. newWhiteList[key] = {
  10204. ...value,
  10205. ...whiteList[key]
  10206. };
  10207. }
  10208. return newWhiteList;
  10209. } catch (error) {
  10210. throwError(error, 'assignWhiteList');
  10211. return defaultWhiteList;
  10212. }
  10213. };
  10214. const whiteListOptions = function(showType) {
  10215. try {
  10216. const whiteList = assignWhiteList(GM_getValue('whiteList') || {});
  10217. let whiteListOptionsForm = `<form id="whiteListForm" class="auto-task-form">
  10218. <table class="auto-task-table"><thead><tr><td>${i18n('website')}</td><td>${i18n('type')}</td><td>${i18n('edit')}</td></tr></thead><tbody>`;
  10219. for (const [ social, types ] of Object.entries(whiteList)) {
  10220. 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('');
  10221. }
  10222. whiteListOptionsForm += '</tbody></table></form>';
  10223. if (showType === 'swal') {
  10224. external_Swal_default().fire({
  10225. title: i18n('whiteListOptions'),
  10226. html: whiteListOptionsForm,
  10227. showConfirmButton: false,
  10228. showCloseButton: true
  10229. });
  10230. } else {
  10231. $('body').append(`<h2>${i18n('whiteList')}</h2>${whiteListOptionsForm}`);
  10232. }
  10233. $('.editWhiteList').on('click', function() {
  10234. const value = $(this).attr('data-value');
  10235. if (!value) {
  10236. return;
  10237. }
  10238. const [ social, type ] = value.split('.');
  10239. if (!whiteList?.[social]?.[type]) {
  10240. scripts_echoLog({}).warning(i18n('whiteListNotFound', value));
  10241. return;
  10242. }
  10243. external_Swal_default().fire({
  10244. title: i18n('changeWhiteListOption', value),
  10245. input: 'textarea',
  10246. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10247. <button id="link2id" data-type="${value}" class="swal2-confirm swal2-styled">获取id</button>
  10248. <p style="margin-bottom:0 !important;">在下方填写白名单,每行一个</p>`,
  10249. inputValue: whiteList[social][type].join('\n'),
  10250. showConfirmButton: true,
  10251. confirmButtonText: i18n('save'),
  10252. showCancelButton: true,
  10253. cancelButtonText: i18n('close'),
  10254. showDenyButton: true,
  10255. denyButtonText: i18n('return')
  10256. }).then(({
  10257. isDenied,
  10258. isConfirmed,
  10259. value
  10260. }) => {
  10261. if (isDenied) {
  10262. if (showType === 'swal') {
  10263. whiteListOptions(showType);
  10264. }
  10265. return;
  10266. } else if (isConfirmed) {
  10267. whiteList[social][type] = value.split('\n');
  10268. GM_setValue('whiteList', whiteList);
  10269. external_Swal_default().fire({
  10270. title: i18n('changeWhiteListSuccess'),
  10271. icon: 'success'
  10272. });
  10273. }
  10274. });
  10275. $('#link2id').on('click', async function() {
  10276. const type = $(this).attr('data-type');
  10277. $('#socialLink').val(await link2id(type));
  10278. });
  10279. });
  10280. } catch (error) {
  10281. throwError(error, 'whiteListOptions');
  10282. }
  10283. };
  10284. const whiteList = whiteListOptions;
  10285. const setGistData = async (token, gistId, fileName, content) => {
  10286. try {
  10287. const logStatus = scripts_echoLog({
  10288. text: i18n('settingData')
  10289. });
  10290. const contentData = JSON.stringify({
  10291. files: {
  10292. [fileName]: {
  10293. content: JSON.stringify(content)
  10294. }
  10295. }
  10296. });
  10297. const {
  10298. result,
  10299. statusText,
  10300. status,
  10301. data
  10302. } = await tools_httpRequest({
  10303. url: `https://api.github.com/gists/${gistId}`,
  10304. headers: {
  10305. Accept: 'application/vnd.github.v3+json',
  10306. Authorization: `token ${token}`
  10307. },
  10308. data: contentData,
  10309. responseType: 'json',
  10310. method: 'POST',
  10311. timeout: 3e4
  10312. });
  10313. if (result === 'Success') {
  10314. if (data?.status === 200 && data.response.files?.[fileName]?.content === JSON.stringify(content)) {
  10315. logStatus.success();
  10316. return true;
  10317. }
  10318. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10319. return false;
  10320. }
  10321. logStatus.error(`${result}:${statusText}(${status})`);
  10322. return false;
  10323. } catch (error) {
  10324. throwError(error, 'setGistData');
  10325. return false;
  10326. }
  10327. };
  10328. const getGistData = async (token, gistId, fileName, test = false) => {
  10329. try {
  10330. const logStatus = scripts_echoLog({
  10331. text: i18n('gettingData')
  10332. });
  10333. const {
  10334. result,
  10335. statusText,
  10336. status,
  10337. data
  10338. } = await tools_httpRequest({
  10339. url: `https://api.github.com/gists/${gistId}`,
  10340. headers: {
  10341. Accept: 'application/vnd.github.v3+json',
  10342. Authorization: `token ${token}`
  10343. },
  10344. responseType: 'json',
  10345. method: 'GET',
  10346. timeout: 3e4
  10347. });
  10348. if (result === 'Success') {
  10349. if (data?.status === 200) {
  10350. const content = data.response?.files?.[fileName]?.content;
  10351. let formatedContent;
  10352. if (!content) {
  10353. logStatus.error(`Error:${i18n('noRemoteData')}`);
  10354. return false;
  10355. }
  10356. if (test) {
  10357. logStatus.success();
  10358. return true;
  10359. }
  10360. try {
  10361. formatedContent = JSON.parse(content);
  10362. } catch (error) {
  10363. logStatus.error(`Error:${i18n('errorRemoteDataFormat')}`);
  10364. return false;
  10365. }
  10366. logStatus.success();
  10367. return formatedContent;
  10368. }
  10369. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10370. return false;
  10371. }
  10372. logStatus.error(`${result}:${statusText}(${status})`);
  10373. return false;
  10374. } catch (error) {
  10375. throwError(error, 'getGistData');
  10376. return false;
  10377. }
  10378. };
  10379. const syncOptions = () => {
  10380. try {
  10381. const {
  10382. TOKEN,
  10383. GIST_ID,
  10384. FILE_NAME,
  10385. SYNC_HISTORY
  10386. } = GM_getValue('gistOptions') || {
  10387. TOKEN: '',
  10388. GIST_ID: '',
  10389. FILE_NAME: '',
  10390. SYNC_HISTORY: true
  10391. };
  10392. external_Swal_default().fire({
  10393. title: i18n('gistOptions'),
  10394. 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;">
  10395. ${i18n('upload2gist')}</button>` + `<button id="download-data" type="button" class="swal2-confirm swal2-styled" style="display: inline-block;">
  10396. ${i18n('downloadFromGist')}</button></p>`,
  10397. focusConfirm: false,
  10398. showLoaderOnConfirm: true,
  10399. 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>`,
  10400. preConfirm: async () => {
  10401. const token = $('#github-token').val();
  10402. const gistId = $('#gist-id').val();
  10403. const fileName = $('#file-name').val();
  10404. const syncHistory = $('#sync-history').prop('checked');
  10405. GM_setValue('gistOptions', {
  10406. TOKEN: token,
  10407. GIST_ID: gistId,
  10408. FILE_NAME: fileName,
  10409. SYNC_HISTORY: syncHistory
  10410. });
  10411. return await getGistData(token, gistId, fileName, true);
  10412. },
  10413. allowOutsideClick: () => !external_Swal_default().isLoading(),
  10414. confirmButtonText: i18n('saveAndTest'),
  10415. showCancelButton: true,
  10416. cancelButtonText: i18n('close')
  10417. }).then(({
  10418. value
  10419. }) => {
  10420. if (value) {
  10421. external_Swal_default().fire({
  10422. icon: 'success',
  10423. title: i18n('testSuccess')
  10424. }).then(syncOptions);
  10425. } else if (value !== undefined) {
  10426. external_Swal_default().fire({
  10427. icon: 'error',
  10428. title: i18n('testFailed')
  10429. }).then(syncOptions);
  10430. }
  10431. });
  10432. $('#upload-data').on('click', async () => {
  10433. const {
  10434. TOKEN,
  10435. GIST_ID,
  10436. FILE_NAME
  10437. } = GM_getValue('gistOptions') || {};
  10438. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10439. return external_Swal_default().fire({
  10440. icon: 'error',
  10441. title: i18n('saveAndTestNotice')
  10442. }).then(syncOptions);
  10443. }
  10444. external_Swal_default().fire({
  10445. icon: 'info',
  10446. title: i18n('processingData')
  10447. });
  10448. const data = {};
  10449. const names = GM_listValues();
  10450. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10451. for (const name of names) {
  10452. if (name === 'gistOptions' || /^[\w]+?Auth$/.test(name)) {
  10453. continue;
  10454. }
  10455. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10456. continue;
  10457. }
  10458. data[name] = GM_getValue(name);
  10459. }
  10460. external_Swal_default().update({
  10461. icon: 'info',
  10462. title: i18n('updatingData')
  10463. });
  10464. if (await setGistData(TOKEN, GIST_ID, FILE_NAME, data)) {
  10465. external_Swal_default().fire({
  10466. icon: 'success',
  10467. title: i18n('syncDataSuccess')
  10468. });
  10469. } else {
  10470. external_Swal_default().fire({
  10471. icon: 'error',
  10472. title: i18n('syncDataFailed')
  10473. });
  10474. }
  10475. });
  10476. $('#download-data').on('click', async () => {
  10477. const {
  10478. TOKEN,
  10479. GIST_ID,
  10480. FILE_NAME
  10481. } = GM_getValue('gistOptions') || {};
  10482. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10483. return external_Swal_default().fire({
  10484. icon: 'error',
  10485. title: i18n('saveAndTestNotice')
  10486. }).then(syncOptions);
  10487. }
  10488. external_Swal_default().fire({
  10489. icon: 'info',
  10490. title: i18n('downloadingData')
  10491. });
  10492. const data = await getGistData(TOKEN, GIST_ID, FILE_NAME);
  10493. if (!data) {
  10494. return external_Swal_default().fire({
  10495. icon: 'error',
  10496. title: i18n('checkedNoData')
  10497. }).then(syncOptions);
  10498. }
  10499. external_Swal_default().update({
  10500. icon: 'info',
  10501. title: i18n('savingData')
  10502. });
  10503. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10504. for (const [ name, value ] of Object.entries(data)) {
  10505. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10506. continue;
  10507. }
  10508. GM_setValue(name, value);
  10509. }
  10510. external_Swal_default().fire({
  10511. icon: 'success',
  10512. title: i18n('syncDataSuccess')
  10513. });
  10514. });
  10515. } catch (error) {
  10516. throwError(error, 'syncOptions');
  10517. }
  10518. };
  10519. const dataSync = syncOptions;
  10520. class Setting {
  10521. name = 'Setting';
  10522. buttons = [ 'saveGlobalOptions', 'syncData', 'tasksHistory' ];
  10523. syncData = dataSync;
  10524. tasksHistory() {
  10525. GM_openInTab('https://auto-task-v4.hclonely.com/history.html', {
  10526. active: true
  10527. });
  10528. }
  10529. static test() {
  10530. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/setting.html';
  10531. }
  10532. before() {
  10533. try {
  10534. $('body').html('').addClass('auto-task-options');
  10535. } catch (error) {
  10536. throwError(error, 'Setting.before');
  10537. }
  10538. }
  10539. after() {
  10540. try {
  10541. this.#environment();
  10542. changeGlobalOptions('page');
  10543. whiteList('page');
  10544. $('input[name="other.twitterVerifyId"]').after(`<button id="getTwitterUserId" type="button">${i18n('getTwitterUserId')}</button>`);
  10545. $('#getTwitterUserId').on('click', () => {
  10546. this.#getId('twitterUser');
  10547. });
  10548. $('input[name="other.youtubeVerifyChannel"]').after(`<button id="getYoutubeChannelId" type="button">${i18n('getYoutubeChannelId')}</button>`);
  10549. $('#getYoutubeChannelId').on('click', () => {
  10550. this.#getId('youtubeChannel');
  10551. });
  10552. $('input[name^="position"]').on('input', function() {
  10553. const type = $(this).attr('name').replace('position.', '');
  10554. const xLabel = 'rightleft';
  10555. const yLabel = 'topbottpm';
  10556. switch (type) {
  10557. case 'buttonSideX':
  10558. case 'buttonSideY':
  10559. case 'buttonDistance':
  10560. {
  10561. const distance = $('input[name="position.buttonDistance"]').val();
  10562. const sideX = $('input[name="position.buttonSideX"]').val();
  10563. const sideY = $('input[name="position.buttonSideY"]').val();
  10564. if (![ 'right', 'left' ].includes(sideX)) {
  10565. break;
  10566. }
  10567. if (![ 'top', 'bottom' ].includes(sideY)) {
  10568. break;
  10569. }
  10570. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10571. break;
  10572. }
  10573. const distanceArr = distance.split(',');
  10574. $('#auto-task-buttons').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10575. break;
  10576. }
  10577.  
  10578. case 'showButtonSideX':
  10579. case 'showButtonSideY':
  10580. case 'showButtonDistance':
  10581. {
  10582. const distance = $('input[name="position.showButtonDistance"]').val();
  10583. const sideX = $('input[name="position.showButtonSideX"]').val();
  10584. const sideY = $('input[name="position.showButtonSideY"]').val();
  10585. if (![ 'right', 'left' ].includes(sideX)) {
  10586. break;
  10587. }
  10588. if (![ 'top', 'bottom' ].includes(sideY)) {
  10589. break;
  10590. }
  10591. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10592. break;
  10593. }
  10594. const distanceArr = distance.split(',');
  10595. $('div.show-button-div').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10596. break;
  10597. }
  10598.  
  10599. case 'logSideX':
  10600. case 'logSideY':
  10601. case 'logDistance':
  10602. {
  10603. const distance = $('input[name="position.logDistance"]').val();
  10604. const sideX = $('input[name="position.logSideX"]').val();
  10605. const sideY = $('input[name="position.logSideY"]').val();
  10606. if (![ 'right', 'left' ].includes(sideX)) {
  10607. break;
  10608. }
  10609. if (![ 'top', 'bottom' ].includes(sideY)) {
  10610. break;
  10611. }
  10612. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10613. break;
  10614. }
  10615. const distanceArr = distance.split(',');
  10616. $('#auto-task-info').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10617. break;
  10618. }
  10619.  
  10620. default:
  10621. break;
  10622. }
  10623. });
  10624. $('input[name^="hotKey"]').attr('readonly', 'readonly').off('keydown').on('keydown', function(event) {
  10625. let functionKey = '';
  10626. if (event.altKey) {
  10627. functionKey += 'alt + ';
  10628. } else if (event.ctrlKey) {
  10629. functionKey += 'ctrl + ';
  10630. } else if (event.shiftKey) {
  10631. functionKey += 'shift + ';
  10632. }
  10633. $(this).val(functionKey + (event.key.length === 1 ? event.key.toLowerCase() : ''));
  10634. });
  10635. } catch (error) {
  10636. throwError(error, 'Setting.after');
  10637. }
  10638. }
  10639. saveGlobalOptions() {
  10640. try {
  10641. saveData();
  10642. } catch (error) {
  10643. throwError(error, 'Setting.saveGlobalOptions');
  10644. }
  10645. }
  10646. #getId(social) {
  10647. try {
  10648. external_Swal_default().fire({
  10649. title: i18n('getId', i18n(social)),
  10650. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10651. <button id="link2id" data-type="${social}" class="swal2-confirm swal2-styled">获取id</button>`,
  10652. showCancelButton: true,
  10653. cancelButtonText: i18n('close'),
  10654. showConfirmButton: false
  10655. });
  10656. $('#link2id').on('click', async function() {
  10657. const link = $('#socialLink').val();
  10658. if (!link) {
  10659. return;
  10660. }
  10661. const type = $(this).attr('data-type');
  10662. if (type === 'twitterUser') {
  10663. const name = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || link;
  10664. $('#socialLink').val(await new social_Twitter().userName2id(name) || '');
  10665. } else if (type === 'youtubeChannel') {
  10666. const name = /^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www.youtube.com\/.*/.test(link) ? link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1] : link;
  10667. $('#socialLink').val((await getInfo(name, 'channel'))?.params?.channelId || '');
  10668. }
  10669. });
  10670. } catch (error) {
  10671. throwError(error, 'Setting.getId');
  10672. }
  10673. }
  10674. #environment() {
  10675. try {
  10676. const userAgent = (0, javascript_utils_umd_min.ua)();
  10677. const environmentForm = `<form id="environmentForm" class="auto-task-form">
  10678. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('name')}</td><td>${i18n('version')}</td></tr></thead><tbody>
  10679. <tr><td>${i18n('os')}</td><td>${userAgent.os}</td><td>${userAgent.osVersion}</td></tr>
  10680. <tr><td>${i18n('browser')}</td><td>${userAgent.browserZH}</td><td>${userAgent.browserVersion}</td></tr>
  10681. <tr><td>${i18n('scriptManager')}</td><td>${GM_info.scriptHandler}</td><td>${GM_info.version}</td></tr>
  10682. <tr><td>${i18n('script')}</td><td>${GM_info.script.name}</td><td>${GM_info.script.version}</td></tr>
  10683. </tbody></table></form>`;
  10684. $('body').append(`<h2>${i18n('environment')}</h2>${environmentForm}`);
  10685. } catch (error) {
  10686. throwError(error, 'Setting.environment');
  10687. }
  10688. }
  10689. }
  10690. const website_Setting = Setting;
  10691. class History extends website_Keylol {
  10692. name = 'History';
  10693. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect', 'clearHistory' ];
  10694. static test() {
  10695. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/history.html';
  10696. }
  10697. before() {
  10698. try {
  10699. $('body').html('<div class="container"></div>').addClass('auto-task-history');
  10700. const data = GM_listValues() || [];
  10701. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  10702. for (const item of tasksHistory) {
  10703. this.#addItem(item);
  10704. }
  10705. } catch (error) {
  10706. throwError(error, 'History.before');
  10707. }
  10708. }
  10709. clearHistory() {
  10710. try {
  10711. const data = GM_listValues() || [];
  10712. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  10713. for (const item of tasksHistory) {
  10714. GM_deleteValue(item);
  10715. }
  10716. external_Swal_default().fire({
  10717. title: i18n('clearHistoryFinished'),
  10718. icon: 'success'
  10719. });
  10720. } catch (error) {
  10721. throwError(error, 'History.clearHistory');
  10722. }
  10723. }
  10724. #addItem(item) {
  10725. try {
  10726. const tasksData = GM_getValue(item);
  10727. if (!tasksData?.tasks) {
  10728. return;
  10729. }
  10730. let html = '';
  10731. let title = '';
  10732. let link = '';
  10733. const [ website, id ] = item.split('-');
  10734. switch (website) {
  10735. case 'fawTasks':
  10736. title = `Freeanywhere[${id}]`;
  10737. link = `https://freeanywhere.net/#/giveaway/${id}`;
  10738. break;
  10739.  
  10740. case 'gasTasks':
  10741. title = `Giveawaysu[${id}]`;
  10742. link = `https://giveaway.su/giveaway/view/${id}`;
  10743. break;
  10744.  
  10745. case 'gcTasks':
  10746. title = `GiveeClub[${id}]`;
  10747. link = `https://givee.club/event/${id}`;
  10748. break;
  10749.  
  10750. case 'gkTasks':
  10751. title = `Givekey[${id}]`;
  10752. link = `https://givekey.ru/giveaway/${id}`;
  10753. break;
  10754.  
  10755. case 'gleamTasks':
  10756. title = `Gleam[${id}]`;
  10757. link = `https://gleam.io${id}`;
  10758. break;
  10759.  
  10760. case 'khTasks':
  10761. title = `keyhub[${id}]`;
  10762. link = `https://key-hub.eu/giveaway/${id}`;
  10763. break;
  10764.  
  10765. case 'prysTasks':
  10766. title = `Prys[${id}]`;
  10767. link = `https://prys.revadike.com/giveaway/?id=${id}`;
  10768. break;
  10769.  
  10770. default:
  10771. return;
  10772. }
  10773. for (const [ social, types ] of Object.entries(tasksData.tasks)) {
  10774. for (const [ type, tasks ] of Object.entries(types)) {
  10775. for (const task of tasks) {
  10776. 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>`;
  10777. }
  10778. }
  10779. }
  10780. $('.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>`);
  10781. $('span.delete-task').on('click', function() {
  10782. const itemName = $(this).attr('data-name');
  10783. if (itemName) {
  10784. GM_deleteValue(itemName);
  10785. $(`div.card[data-name="${itemName}"]`).remove();
  10786. external_Swal_default().fire({
  10787. title: i18n('clearTaskFinished'),
  10788. text: itemName,
  10789. icon: 'success'
  10790. });
  10791. } else {
  10792. external_Swal_default().fire({
  10793. title: i18n('clearTaskFailed'),
  10794. icon: 'error'
  10795. });
  10796. }
  10797. });
  10798. } catch (error) {
  10799. throwError(error, 'History.addItem');
  10800. }
  10801. }
  10802. }
  10803. const website_History = History;
  10804. const GiveawayHopper_defaultTasksTemplate = {
  10805. steam: {
  10806. groupLinks: [],
  10807. wishlistLinks: [],
  10808. followLinks: [],
  10809. curatorLinks: [],
  10810. curatorLikeLinks: []
  10811. },
  10812. twitter: {
  10813. userLinks: [],
  10814. retweetLinks: []
  10815. },
  10816. twitch: {
  10817. channelLinks: []
  10818. },
  10819. discord: {
  10820. serverLinks: []
  10821. },
  10822. youtube: {
  10823. channelLinks: []
  10824. },
  10825. extra: {
  10826. giveawayHopper: []
  10827. }
  10828. };
  10829. const GiveawayHopper_defaultTasks = JSON.stringify(GiveawayHopper_defaultTasksTemplate);
  10830. class GiveawayHopper extends website_Website {
  10831. name = 'GiveawayHopper';
  10832. undoneTasks = JSON.parse(GiveawayHopper_defaultTasks);
  10833. socialTasks = JSON.parse(GiveawayHopper_defaultTasks);
  10834. tasks = [];
  10835. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  10836. static test() {
  10837. return window.location.host === 'giveawayhopper.com';
  10838. }
  10839. async after() {
  10840. try {
  10841. if (!this.#checkLogin()) {
  10842. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  10843. }
  10844. this.#getGiveawayId();
  10845. } catch (error) {
  10846. throwError(error, 'GiveawayHopper.after');
  10847. }
  10848. }
  10849. async init() {
  10850. try {
  10851. const logStatus = scripts_echoLog({
  10852. text: i18n('initing')
  10853. });
  10854. if (!await this.#checkLeftKey()) {
  10855. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  10856. }
  10857. this.initialized = true;
  10858. logStatus.success();
  10859. return true;
  10860. } catch (error) {
  10861. throwError(error, 'GiveawayHopper.init');
  10862. return false;
  10863. }
  10864. }
  10865. async classifyTask(action) {
  10866. try {
  10867. if (!this.giveawayId) {
  10868. await this.#getGiveawayId();
  10869. }
  10870. const logStatus = scripts_echoLog({
  10871. text: i18n('getTasksInfo')
  10872. });
  10873. if (action === 'undo') {
  10874. this.socialTasks = GM_getValue(`giveawayHopperTasks-${this.giveawayId}`)?.tasks || JSON.parse(GiveawayHopper_defaultTasks);
  10875. }
  10876. const {
  10877. result,
  10878. statusText,
  10879. status,
  10880. data
  10881. } = await tools_httpRequest({
  10882. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/with-auth`,
  10883. method: 'GET',
  10884. responseType: 'json',
  10885. fetch: true,
  10886. headers: {
  10887. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10888. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10889. }
  10890. });
  10891. if (result === 'Success') {
  10892. if (data?.status === 200 && data?.response?.tasks) {
  10893. this.tasks = data.response.tasks;
  10894. for (const task of data.response.tasks) {
  10895. if (task.isDone) {
  10896. continue;
  10897. }
  10898. await tools_httpRequest({
  10899. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/visited`,
  10900. method: 'GET',
  10901. responseType: 'json',
  10902. fetch: true,
  10903. headers: {
  10904. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10905. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10906. }
  10907. });
  10908. if (task.category === 'Steam' && task.type === 'JoinGroup') {
  10909. const steamGroupLink = await getRedirectLink(`https://steamcommunity.com/gid/${task.group_id}`);
  10910. if (!steamGroupLink) {
  10911. continue;
  10912. }
  10913. if (action === 'undo') {
  10914. this.socialTasks.steam.groupLinks.push(steamGroupLink);
  10915. }
  10916. if (action === 'do') {
  10917. this.undoneTasks.steam.groupLinks.push(steamGroupLink);
  10918. }
  10919. continue;
  10920. }
  10921. if (task.category === 'Discord' && task.type === 'JoinServer') {
  10922. if (action === 'undo') {
  10923. this.socialTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  10924. }
  10925. if (action === 'do') {
  10926. this.undoneTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  10927. }
  10928. continue;
  10929. }
  10930. if ([ 'TikTok', 'YouTube', 'General' ].includes(task.category)) {
  10931. continue;
  10932. }
  10933. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${task.category}-${task.type}`);
  10934. }
  10935. logStatus.success();
  10936. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  10937. this.socialTasks = this.uniqueTasks(this.socialTasks);
  10938. if (window.DEBUG) {
  10939. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  10940. }
  10941. GM_setValue(`giveawayHopperTasks-${this.giveawayId}`, {
  10942. tasks: this.socialTasks,
  10943. time: new Date().getTime()
  10944. });
  10945. return true;
  10946. }
  10947. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10948. return false;
  10949. }
  10950. logStatus.error(`${result}:${statusText}(${status})`);
  10951. return false;
  10952. } catch (error) {
  10953. throwError(error, 'GiveawayHopper.classifyTask');
  10954. return false;
  10955. }
  10956. }
  10957. async verifyTask() {
  10958. try {
  10959. for (const task of this.tasks) {
  10960. if (task.isDone) {
  10961. continue;
  10962. }
  10963. const logStatus = scripts_echoLog({
  10964. text: `${i18n('verifyingTask')}[${task.displayName?.replace(':target', task.targetName) || task.name}]...`
  10965. });
  10966. if (!task.link) {
  10967. if (task.category === 'YouTube' && task.type === 'FollowAccount') {
  10968. task.link = `https://www.youtube.com/@${task.targetName}`;
  10969. } else if (task.category === 'TikTok' && task.type === 'FollowAccount') {
  10970. task.link = `https://www.tiktok.com/@${task.targetName}`;
  10971. } else if (task.category === 'Steam' && task.type === 'JoinGroup') {
  10972. task.link = '';
  10973. } else if (task.category === 'Discord' && task.type === 'JoinServer') {
  10974. task.link = '';
  10975. }
  10976. }
  10977. if (task.link) {
  10978. await tools_httpRequest({
  10979. 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}`,
  10980. method: 'GET',
  10981. fetch: true,
  10982. headers: {
  10983. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10984. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10985. }
  10986. });
  10987. }
  10988. await delay(1e3);
  10989. const postData = {
  10990. taskcategory: task.category,
  10991. taskname: task.type
  10992. };
  10993. if ([ 'YouTube', 'TikTok' ].includes(task.category)) {
  10994. postData.username = '1';
  10995. }
  10996. const {
  10997. result,
  10998. statusText,
  10999. status,
  11000. data
  11001. } = await tools_httpRequest({
  11002. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/complete`,
  11003. method: 'POST',
  11004. fetch: true,
  11005. headers: {
  11006. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  11007. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1]),
  11008. 'content-type': 'application/json'
  11009. },
  11010. dataType: 'json',
  11011. data: JSON.stringify(postData)
  11012. });
  11013. if (result === 'Success') {
  11014. if (data?.status === 200 && data?.response?.completed) {
  11015. logStatus.success();
  11016. continue;
  11017. }
  11018. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  11019. continue;
  11020. }
  11021. logStatus.error(`${result}:${statusText}(${status})`);
  11022. continue;
  11023. }
  11024. } catch (error) {
  11025. throwError(error, 'GiveawayHopper.verifyTask');
  11026. return false;
  11027. }
  11028. }
  11029. #getGiveawayId() {
  11030. try {
  11031. const giveawayId = window.location.pathname.split('/').at(-1);
  11032. if (giveawayId) {
  11033. this.giveawayId = giveawayId;
  11034. return true;
  11035. }
  11036. scripts_echoLog({
  11037. text: i18n('getFailed', 'GiveawayId')
  11038. });
  11039. return false;
  11040. } catch (error) {
  11041. throwError(error, 'GiveawayHopper.getGiveawayId');
  11042. return false;
  11043. }
  11044. }
  11045. #checkLogin() {
  11046. try {
  11047. if (!globalOptions.other.checkLogin) {
  11048. return true;
  11049. }
  11050. if ($('div.widget-connections-edit:contains("Log in")').length > 0) {
  11051. $('div.widget-connections-edit:contains("Log in") a')[0].click();
  11052. }
  11053. return true;
  11054. } catch (error) {
  11055. throwError(error, 'GiveawayHopper.checkLogin');
  11056. return false;
  11057. }
  11058. }
  11059. async #checkLeftKey() {
  11060. try {
  11061. if (!globalOptions.other.checkLeftKey) {
  11062. return true;
  11063. }
  11064. if ($('p.widget-single-prize span').length > 0 && parseInt($('p.widget-single-prize span').text()?.match(/\d+/)?.[0] || '0', 10) > 0) {
  11065. return true;
  11066. }
  11067. await external_Swal_default().fire({
  11068. icon: 'warning',
  11069. title: i18n('notice'),
  11070. text: i18n('noKeysLeft'),
  11071. confirmButtonText: i18n('confirm'),
  11072. cancelButtonText: i18n('cancel'),
  11073. showCancelButton: true
  11074. }).then(({
  11075. value
  11076. }) => {
  11077. if (value) {
  11078. window.close();
  11079. }
  11080. });
  11081. return true;
  11082. } catch (error) {
  11083. throwError(error, 'GiveawayHopper.checkLeftKey');
  11084. return false;
  11085. }
  11086. }
  11087. }
  11088. const website_GiveawayHopper = GiveawayHopper;
  11089. 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 ];
  11090. const websiteOptions = function(website, options) {
  11091. try {
  11092. let websiteOptionsForm = `<form id="websiteOptionsForm" class="auto-task-form">
  11093. <table class="auto-task-table"><thead><tr><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  11094. for (const [ option, value ] of Object.entries(options)) {
  11095. websiteOptionsForm += `<tr><td>${option}</td><td><input class="editOption" type="text" name="${option}" value="${value}"/></td></tr>`;
  11096. }
  11097. websiteOptionsForm += '</tbody></table></form>';
  11098. external_Swal_default().fire({
  11099. title: i18n('websiteOptions'),
  11100. html: websiteOptionsForm,
  11101. showConfirmButton: true,
  11102. confirmButtonText: i18n('save'),
  11103. showCancelButton: true,
  11104. cancelButtonText: i18n('close')
  11105. }).then(({
  11106. isConfirmed
  11107. }) => {
  11108. if (isConfirmed) {
  11109. $('#websiteOptionsForm').serializeArray().map(value => {
  11110. options[value.name] = value.value;
  11111. return value;
  11112. });
  11113. GM_setValue(`${website}Options`, options);
  11114. external_Swal_default().fire({
  11115. title: i18n('changeWebsiteOptionsSuccess'),
  11116. icon: 'success'
  11117. });
  11118. }
  11119. });
  11120. } catch (error) {
  11121. throwError(error, 'websiteOptions');
  11122. }
  11123. };
  11124. const options = websiteOptions;
  11125. const external_keyboardJS_namespaceObject = keyboardJS;
  11126. var external_keyboardJS_default = __webpack_require__.n(external_keyboardJS_namespaceObject);
  11127. const checkUpdate = async (updateLink, auto) => {
  11128. try {
  11129. const checkUrl = `${updateLink}package.json?time=${new Date().getTime()}`;
  11130. const {
  11131. result,
  11132. statusText,
  11133. status,
  11134. data
  11135. } = await tools_httpRequest({
  11136. url: checkUrl,
  11137. responseType: 'json',
  11138. method: 'GET',
  11139. timeout: 3e4
  11140. });
  11141. if (result === 'Success') {
  11142. if (data?.response?.version) {
  11143. return data.response;
  11144. }
  11145. if (!auto) {
  11146. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${data?.statusText}(${data?.status})]`);
  11147. }
  11148. return false;
  11149. }
  11150. if (!auto) {
  11151. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${result}:${statusText}(${status})]`);
  11152. }
  11153. return false;
  11154. } catch (error) {
  11155. throwError(error, 'checkUpdate');
  11156. return false;
  11157. }
  11158. };
  11159. const hasNewVersion = (currentVersion, remoteVersion) => {
  11160. try {
  11161. const [ currentRealVersion ] = currentVersion.split('-');
  11162. const [ remoteRealVersion, isPreview ] = remoteVersion.split('-');
  11163. if (isPreview && !globalOptions.other.receivePreview) {
  11164. return false;
  11165. }
  11166. const [ currentVersion1, currentVersion2, currentVersion3 ] = currentRealVersion.split('.').map(value => parseInt(value, 10));
  11167. const [ remoteVersion1, remoteVersion2, remoteVersion3 ] = remoteRealVersion.split('.').map(value => parseInt(value, 10));
  11168. if (remoteVersion1 > currentVersion1) {
  11169. return true;
  11170. }
  11171. if (remoteVersion1 < currentVersion1) {
  11172. return false;
  11173. }
  11174. if (remoteVersion2 > currentVersion2) {
  11175. return true;
  11176. }
  11177. if (remoteVersion2 < currentVersion2) {
  11178. return false;
  11179. }
  11180. if (remoteVersion3 > currentVersion3) {
  11181. return true;
  11182. }
  11183. return false;
  11184. } catch (error) {
  11185. throwError(error, 'compareVersion');
  11186. return false;
  11187. }
  11188. };
  11189. const updateChecker = async () => {
  11190. try {
  11191. const currentVersion = GM_info.script.version;
  11192. const updateSource = globalOptions.other.autoUpdateSource.toLowerCase();
  11193. const updateLinks = {
  11194. github: 'https://github.com/HCLonely/auto-task-new/raw/main/',
  11195. jsdelivr: 'https://cdn.jsdelivr.net/gh/HCLonely/auto-task-v4@main/',
  11196. standby: 'https://auto-task-v4.hclonely.com/'
  11197. };
  11198. let version;
  11199. let updateLink = '';
  11200. let packageData;
  11201. if ([ 'github', 'jsdelivr', 'standby' ].includes(updateSource)) {
  11202. updateLink = updateLinks[updateSource];
  11203. packageData = await checkUpdate(updateLink, false);
  11204. } else {
  11205. updateLink = updateLinks.github;
  11206. packageData = await checkUpdate(updateLink, true);
  11207. if (!packageData) {
  11208. updateLink = updateLinks.jsdelivr;
  11209. packageData = await checkUpdate(updateLink, true);
  11210. if (!packageData) {
  11211. updateLink = updateLinks.standby;
  11212. packageData = await checkUpdate(updateLink, true);
  11213. }
  11214. }
  11215. }
  11216. if (packageData) {
  11217. version = packageData.version || currentVersion;
  11218. } else {
  11219. version = currentVersion;
  11220. scripts_echoLog({}).error(i18n('checkUpdateFailed'));
  11221. }
  11222. if (packageData && hasNewVersion(currentVersion, version)) {
  11223. scripts_echoLog({
  11224. html: `<li><font>${i18n('newVersionNotice', version, `${updateLink}dist/${GM_info.script.name}.user.js`)}</font></li>`
  11225. });
  11226. scripts_echoLog({
  11227. html: `<li>${i18n('updateText', version)}</li><ol class="update-text">${packageData.change?.map(change => `<li>${change}</li>`).join('')}<li>${i18n('updateHistory')}</li></ol>`
  11228. });
  11229. }
  11230. } catch (error) {
  11231. throwError(error, 'updateChecker');
  11232. }
  11233. };
  11234. const scripts_updateChecker = updateChecker;
  11235. window.STYLE = GM_addStyle(auto_task.A + GM_getResourceText('style'));
  11236. window.DEBUG = !!globalOptions.other?.debug;
  11237. window.TRACE = !!globalOptions.other?.debug && typeof console.trace === 'function';
  11238. const loadScript = async () => {
  11239. if (window.name === 'ATv4_twitchAuth' && window.location.hostname === 'www.twitch.tv') {
  11240. const authToken = external_Cookies_default().get('auth-token');
  11241. const isLogin = !!external_Cookies_default().get('login');
  11242. if (isLogin) {
  11243. GM_setValue('twitchAuth', {
  11244. authToken: authToken,
  11245. clientVersion: __twilightBuildID,
  11246. clientId: commonOptions?.headers?.['Client-ID'],
  11247. deviceId: commonOptions?.headers?.['Device-ID'],
  11248. clientSessionId: window.localStorage.local_storage_app_session_id.replace(/"/g, '')
  11249. });
  11250. window.close();
  11251. external_Swal_default().fire('', i18n('closePageNotice'));
  11252. } else {
  11253. external_Swal_default().fire('', i18n('needLogin'));
  11254. }
  11255. return;
  11256. }
  11257. if (window.name === 'ATv4_redditAuth' && window.location.hostname === 'www.reddit.com') {
  11258. const betaButton = $('#redesign-beta-optin-btn');
  11259. if (betaButton.length > 0) {
  11260. return betaButton[0].click();
  11261. }
  11262. window.close();
  11263. external_Swal_default().fire('', i18n('closePageNotice'));
  11264. return;
  11265. }
  11266. let website;
  11267. for (const Website of Websites) {
  11268. if (Website.test()) {
  11269. website = new Website();
  11270. break;
  11271. }
  11272. }
  11273. if (!website) {
  11274. console.log('%c%s', 'color:#ff0000', 'Auto-Task[Warning]: 脚本停止加载,当前网站不支持!');
  11275. return;
  11276. }
  11277. if (website?.before) {
  11278. await website?.before();
  11279. }
  11280. $('body').append(`
  11281. <div id="auto-task-info"
  11282. style="display:${globalOptions.other.defaultShowLog ? 'block' : 'none'};
  11283. ${globalOptions.position.logSideX}:${globalOptions.position.logDistance.split(',')[0]}px;
  11284. ${globalOptions.position.logSideY}:${globalOptions.position.logDistance.split(',')[1]}px;">
  11285. </div>
  11286. <div id="auto-task-buttons"
  11287. style="display:${globalOptions.other.defaultShowButton ? 'block' : 'none'};
  11288. ${globalOptions.position.buttonSideX}:${globalOptions.position.buttonDistance.split(',')[0]}px;
  11289. ${globalOptions.position.buttonSideY}:${globalOptions.position.buttonDistance.split(',')[1]}px;">
  11290. </div>
  11291. <div class="show-button-div"
  11292. style="display:${globalOptions.other.defaultShowButton ? 'none' : 'block'};
  11293. ${globalOptions.position.showButtonSideX}:${globalOptions.position.showButtonDistance.split(',')[0]}px;
  11294. ${globalOptions.position.showButtonSideY}:${globalOptions.position.showButtonDistance.split(',')[1]}px;">
  11295. <a class="auto-task-website-btn"
  11296. href="javascript:void(0);"
  11297. target="_self"
  11298. title="${i18n('showButton')}"> </a>
  11299. </div>
  11300. `);
  11301. $('div.show-button-div').on('click', () => {
  11302. $('#auto-task-buttons').show();
  11303. $('div.show-button-div').hide();
  11304. });
  11305. const toggleLog = () => {
  11306. const $this = $('#toggle-log');
  11307. const status = $this.attr('data-status');
  11308. if (status === 'show') {
  11309. $('#auto-task-info').hide();
  11310. $this.attr('data-status', 'hide').text(i18n('showLog'));
  11311. } else {
  11312. $('#auto-task-info').show();
  11313. $this.attr('data-status', 'show').text(i18n('hideLog'));
  11314. }
  11315. };
  11316. external_keyboardJS_default().bind(globalOptions.hotKey.doTaskKey, () => {
  11317. if (website.doTask) {
  11318. website.doTask();
  11319. }
  11320. });
  11321. external_keyboardJS_default().bind(globalOptions.hotKey.undoTaskKey, () => {
  11322. if (website.undoTask) {
  11323. website.undoTask();
  11324. }
  11325. });
  11326. external_keyboardJS_default().bind(globalOptions.hotKey.toggleLogKey, toggleLog);
  11327. if (website?.after) {
  11328. await website?.after();
  11329. }
  11330. if (website?.buttons && $('#auto-task-buttons').children().length === 0) {
  11331. $('#auto-task-buttons').addClass(`${website.name}-buttons`);
  11332. for (const button of website.buttons) {
  11333. if (website[button]) {
  11334. const btnElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">${i18n(button)}</a></p>`);
  11335. btnElement.find('a.auto-task-website-btn').on('click', () => {
  11336. website[button]();
  11337. });
  11338. $('#auto-task-buttons').append(btnElement);
  11339. }
  11340. }
  11341. }
  11342. const hideButtonElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">
  11343. ${i18n('hideButton')}</a></p>`);
  11344. hideButtonElement.find('a.auto-task-website-btn').on('click', () => {
  11345. $('#auto-task-buttons').hide();
  11346. $('div.show-button-div').show();
  11347. });
  11348. 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'}">
  11349. ${globalOptions.other.defaultShowLog ? i18n('hideLog') : i18n('showLog')}</a></p>`);
  11350. toggleLogElement.find('a.auto-task-website-btn').on('click', toggleLog);
  11351. $('#auto-task-buttons').append(hideButtonElement).append(toggleLogElement);
  11352. if (website?.options) {
  11353. GM_registerMenuCommand(i18n('changeWebsiteOptions'), () => {
  11354. options(website.name, website.options);
  11355. });
  11356. }
  11357. if (website.name !== 'Setting') {
  11358. GM_registerMenuCommand(i18n('changeGlobalOptions'), () => {
  11359. changeGlobalOptions('swal');
  11360. });
  11361. GM_registerMenuCommand(i18n('settingPage'), () => {
  11362. GM_openInTab('https://auto-task-v4.hclonely.com/setting.html', {
  11363. active: true
  11364. });
  11365. });
  11366. }
  11367. console.log('%c%s', 'color:#1bbe1a', 'Auto-Task[Load]: 脚本加载完成');
  11368. const [ v1, v2 ] = GM_info.version.split('.');
  11369. if (!(parseInt(v1, 10) >= 5 && parseInt(v2, 10) >= 2)) {
  11370. scripts_echoLog({}).error(i18n('versionNotMatched'));
  11371. }
  11372. if (!GM_getValue('notice')) {
  11373. external_Swal_default().fire({
  11374. title: i18n('swalNotice'),
  11375. icon: 'warning'
  11376. }).then(() => {
  11377. GM_openInTab(i18n('noticeLink'), {
  11378. active: true
  11379. });
  11380. GM_setValue('notice', new Date().getTime());
  11381. });
  11382. scripts_echoLog({
  11383. html: `<li><font class="warning">${i18n('echoNotice', i18n('noticeLink'))}</font></li>`
  11384. }).font?.find('a').on('click', () => {
  11385. GM_setValue('notice', new Date().getTime());
  11386. });
  11387. }
  11388. scripts_updateChecker();
  11389. };
  11390. if (window.location.hostname === 'discord.com') {
  11391. const LocalStorage = window.localStorage;
  11392. if (window.name === 'ATv4_discordAuth') {
  11393. window.localStorage.removeItem = () => true;
  11394. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11395. if (discordAuth && discordAuth.length > 0) {
  11396. GM_setValue('discordAuth', {
  11397. auth: discordAuth
  11398. });
  11399. window.close();
  11400. external_Swal_default().fire('', i18n('closePageNotice'));
  11401. } else {
  11402. external_Swal_default().fire({
  11403. text: i18n('getDiscordAuthFailed'),
  11404. icon: 'error'
  11405. });
  11406. }
  11407. } else {
  11408. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11409. if (discordAuth && discordAuth.length > 0) {
  11410. GM_setValue('discordAuth', {
  11411. auth: discordAuth
  11412. });
  11413. }
  11414. }
  11415. } else if (window.location.hostname === 'opquests.com') {
  11416. loadScript();
  11417. } else if ((window.name === 'ATv4_updateStoreAuth' || GM_getValue('ATv4_updateStoreAuth')) && window.location.host === 'store.steampowered.com') {
  11418. $(() => {
  11419. if ($('[data-miniprofile]').length === 0) {
  11420. return;
  11421. }
  11422. const storeSessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11423. if (storeSessionID) {
  11424. GM_deleteValue('ATv4_updateStoreAuth');
  11425. GM_setValue('steamStoreAuth', {
  11426. storeSessionID: storeSessionID
  11427. });
  11428. window.close();
  11429. external_Swal_default().fire('', i18n('closePageNotice'));
  11430. } else {
  11431. external_Swal_default().fire({
  11432. title: 'Error: Get "sessionID" failed',
  11433. icon: 'error'
  11434. });
  11435. }
  11436. });
  11437. } else if ((window.name === 'ATv4_updateCommunityAuth' || GM_getValue('ATv4_updateCommunityAuth')) && window.location.host === 'steamcommunity.com') {
  11438. $(() => {
  11439. const steam64Id = document.body.innerHTML.match(/g_steamID = "(.+?)";/)?.[1];
  11440. const communitySessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11441. if (steam64Id && communitySessionID) {
  11442. GM_deleteValue('ATv4_updateCommunityAuth');
  11443. GM_setValue('steamCommunityAuth', {
  11444. steam64Id: steam64Id,
  11445. communitySessionID: communitySessionID
  11446. });
  11447. window.close();
  11448. external_Swal_default().fire('', i18n('closePageNotice'));
  11449. } else {
  11450. setTimeout(() => {
  11451. external_Swal_default().fire({
  11452. title: 'Error: Get "sessionID" failed',
  11453. icon: 'error'
  11454. });
  11455. }, 3e3);
  11456. }
  11457. });
  11458. } else {
  11459. if (window.location.hostname === 'key-hub.eu') {
  11460. unsafeWindow.keyhubtracker = 1;
  11461. unsafeWindow.gaData = {};
  11462. }
  11463. $(loadScript);
  11464. }
  11465. }();
  11466. })();