auto-task-v4

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

目前為 2025-03-19 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name auto-task-v4
  3. // @namespace auto-task-v4
  4. // @version 4.7.2
  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. tgTaskNotice: '检测到Telegram任务,需要手动完成',
  1476. confirmingTask: '正在跳过警告页面...'
  1477. };
  1478. const zh_CN = data;
  1479. const en_US_data = {
  1480. website: 'Website',
  1481. type: 'Type',
  1482. edit: 'Edit',
  1483. whiteList: 'Whitelist',
  1484. skipTask: 'Skip undo task',
  1485. whiteListOptions: 'Whitelist options',
  1486. changeWhiteListOption: 'Whitelist option(%0)',
  1487. whiteListNotFound: 'Cannot find this whitelist: %0',
  1488. changeWhiteListSuccess: 'The whitelist is successfully modified, and the page refresh will take effect!',
  1489. changeWebsiteOptions: 'Website options',
  1490. changeGlobalOptions: 'Global options',
  1491. ok: 'OK',
  1492. save: 'Save',
  1493. close: 'Close',
  1494. return: 'Return',
  1495. option: 'Option',
  1496. value: 'Value',
  1497. websiteOptions: 'Current website settings',
  1498. changeWebsiteOptionsSuccess: 'The current website setting is changed successfully, and the page refresh will take effect!',
  1499. changeGlobalOptionsSuccess: 'The global setting is changed successfully, and the refresh will take effect!',
  1500. needLogin: 'Please log in first!',
  1501. getTasksInfo: 'Obtaining and processing task information...',
  1502. gettingKey: 'Getting Key...',
  1503. verifyingTask: 'Verifying task',
  1504. notice: 'Automatic task script notice',
  1505. noKeysLeft: 'There are no more keys left on this page. Do you want to close it?',
  1506. giveawayEnded: 'This event has ended, do you want to close it?',
  1507. 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?',
  1508. confirm: 'Confirm',
  1509. cancel: 'Cancel',
  1510. unKnown: 'Unknown',
  1511. unKnownTaskType: 'Unrecognized task',
  1512. doing: 'Doing a task',
  1513. allTasksComplete: 'All tasks have been completed!',
  1514. getTaskIdFailed: 'Failed to obtain task Id!',
  1515. initSuccess: '%0 was initialized successfully!',
  1516. initFailed: '%0 initialization failed!',
  1517. errorLink: 'Link error: %0',
  1518. needInit: 'Please initialize first',
  1519. verifyingAuth: 'Verifying %0 token...',
  1520. updatingAuth: 'Update %0 token...',
  1521. refreshingToken: 'Refreshing %0 token...',
  1522. settingToken: 'Setting %0 token...',
  1523. steamStoreTab: 'Steam store (new tab)',
  1524. steamCommunityTab: 'Steam community(new tab)',
  1525. initing: 'Initializing...',
  1526. getFailed: 'Failed to get %0!',
  1527. checkLoginFailed: 'Failed to detect login status!',
  1528. checkLeftKeyFailed: 'Failed to detect the remaining keys!',
  1529. userId: 'User Id',
  1530. joiningGiveaway: 'Joining giveaway',
  1531. needJoinGiveaway: 'Need to join the giveaway first',
  1532. cannotUndo: 'This website does not support canceling tasks',
  1533. verifyAuth: 'Verifying %0 token...',
  1534. closePageNotice: 'f this page does not close automatically, please close this page yourself.',
  1535. errorReport: 'A script error is detected, do you want to report the BUG?',
  1536. visitingLink: 'Visiting link: ',
  1537. doTask: 'DoTask',
  1538. undoTask: 'UndoTask',
  1539. verifyTask: 'Verify',
  1540. getKey: 'GetKey',
  1541. selectAll: 'SelectAll',
  1542. selectNone: 'SelectNone',
  1543. invertSelect: 'InvertSelect',
  1544. doFreeTask: 'FreeTask',
  1545. doPointTask: 'PointTask',
  1546. skipTaskOption: 'Skip task has been configured in the settings',
  1547. other: 'Other',
  1548. globalOptions: 'Global Options',
  1549. checkLogin: 'Login detection</br>Need to log in to the website automatically log in, part of this website supports.',
  1550. checkLeftKey: 'Key remaining detection</br>The end of the giveaway event prompts whether to close or not, part of this website supports.',
  1551. 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.',
  1552. 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.',
  1553. 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.',
  1554. saveGlobalOptions: 'SaveSettings',
  1555. settingPage: 'Setting Page',
  1556. name: 'Name',
  1557. version: 'Version',
  1558. scriptManager: 'Script Manager',
  1559. script: 'Script',
  1560. environment: 'Environment',
  1561. os: 'OS',
  1562. browser: 'Browser',
  1563. getId: 'Get %0 id',
  1564. getTwitterUserId: 'Get Twitter user id (Get id function is only available on the settings page).',
  1565. getYoutubeChannelId: 'Get Youtube channel id (Get id function is only available on the settings page).',
  1566. showButton: 'ShowButton',
  1567. hideButton: 'HideButton',
  1568. showLog: 'ShowLog',
  1569. hideLog: 'HideLog',
  1570. defaultShowButton: 'Default display button',
  1571. defaultShowLog: 'Display log by default',
  1572. debug: 'Output debug log, do not enable this option!',
  1573. receivePreview: 'Receive preview updates',
  1574. position: 'Component position',
  1575. buttonSideX: 'Horizontal positioning of the button area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1576. 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',
  1577. 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',
  1578. showButtonSideX: 'ShowButton horizontal positioning (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1579. showButtonSideY: 'ShowButton vertical positioning (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  1580. 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',
  1581. logSideX: 'Horizontal positioning of the log area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1582. logSideY: 'Vertical positioning of the log area (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  1583. 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',
  1584. hotKey: 'Shortcut key',
  1585. doTaskKey: 'DoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  1586. undoTaskKey: 'UndoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  1587. toggleLogKey: 'ShowLog/HideLog shortcut keys</br> (real-time preview function is only available on the settings page).',
  1588. tasksHistory: 'TasksHistory',
  1589. clearHistory: 'Clear history',
  1590. clearHistoryFinished: 'The mission history has been cleared!',
  1591. deleteTask: 'Delete task',
  1592. lastChangeTime: 'Last Change Time',
  1593. clearTaskFinished: 'Delete the following tasks completed!',
  1594. clearTaskFailed: 'Failed to delete the task, the task name was not found!',
  1595. syncData: 'DataSync',
  1596. settingData: 'Uploading data...',
  1597. gettingData: 'Getting data...',
  1598. help: 'Help',
  1599. fileName: 'Filename',
  1600. upload2gist: 'Sync to Gist',
  1601. downloadFromGist: 'Sync from Gist',
  1602. saveAndTest: 'Save configuration and test',
  1603. testSuccess: 'Test success!',
  1604. testFailed: 'Test failed!',
  1605. saveAndTestNotice: 'Please save the configuration and test first!',
  1606. processingData: 'Processing data...',
  1607. updatingData: 'Uploading data...',
  1608. syncDataSuccess: 'Synchronized data successfully!',
  1609. syncDataFailed: 'Failed to synchronize data, please check the error message on the console!',
  1610. downloadingData: 'Downloading data...',
  1611. checkedNoData: 'No remote data is detected, please confirm whether the configuration is correct!',
  1612. savingData: 'Saving data...',
  1613. syncHistory: 'Synchronize tasks history',
  1614. checkUpdateFailed: 'Check update failed',
  1615. newVersionNotice: 'Checked a new version V%0, <a class="high-light" href="%1" target="_blank">click to update</a>',
  1616. language: 'Language</br> Currently only supports zh: Chinese, en: English',
  1617. gistOptions: 'Gist Settings',
  1618. 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!',
  1619. 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!',
  1620. noticeLink: 'https://auto-task-doc.js.org/en/guide/#read-me-first',
  1621. toGithub: 'Feedback(Github)',
  1622. toKeylol: 'Feedback(Keylol)',
  1623. copySuccess: 'The error message has been copied to the clipboard. Do you want to go to the Keylol forum to give feedback?',
  1624. copyFailed: 'Please copy the error information below and report back to the Keylol forum!',
  1625. updateText: 'Updates in version %0:',
  1626. Active: 'Active',
  1627. Ended: 'Ended',
  1628. Banned: 'Banned',
  1629. Paused: 'Paused',
  1630. notStart: 'notStart',
  1631. noRemoteData: 'No data remotely',
  1632. errorRemoteDataFormat: 'Remote data has wrong format',
  1633. updateHistory: '<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">Click here</a>' + ' to view the historical update record.',
  1634. AsfEnabled: 'Use ASF to do Steam related tasks (requires <a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a> plugin)',
  1635. AsfIpcUrl: 'ASF IPC URL',
  1636. AsfIpcPassword: 'ASF IPC Password',
  1637. groups: 'Group',
  1638. officialGroups: 'Official Group',
  1639. wishlists: 'Wishlist',
  1640. follows: 'Follow Game',
  1641. forums: 'Forum',
  1642. workshops: 'Favorite Workshop',
  1643. curators: 'Curator',
  1644. workshopVotes: 'Voteup Workshop',
  1645. announcements: 'Announcement',
  1646. steamCommunity: 'Steam Community',
  1647. steamStore: 'Steam Store',
  1648. licenses: 'Add License',
  1649. playtests: 'Playtest Access',
  1650. needLoginSteamStore: 'Please <a href="https://store.steampowered.com/login/" target="_blank">log in to the Steam Store</a>',
  1651. needLoginSteamCommunity: 'Please <a href="https://steamcommunity.com/login/home/" target="_blank">log in to the Steam Community</a>',
  1652. joiningSteamGroup: 'Joining Steam Group',
  1653. leavingSteamGroup: 'Leaving Steam Group',
  1654. gettingSteamGroupId: 'Getting Steam Group Id',
  1655. joiningSteamOfficialGroup: 'Joining Steam Official Group',
  1656. leavingSteamOfficialGroup: 'Leaving Steam Official Group',
  1657. gettingSteamOfficialGroupId: 'Getting Steam Official Group Id',
  1658. subscribingForum: 'Subscribing the Steam Forum',
  1659. unsubscribingForum: 'Unsubscribing the Steam Forum',
  1660. gettingForumId: 'Getting Steam Forum Id',
  1661. followingCurator: 'Following Steam Curator',
  1662. unfollowingCurator: 'Unfollowing Steam Curator',
  1663. gettingCuratorId: 'Getting Steam Curator Id',
  1664. addingToWishlist: 'Adding the game to the Steam wishlist',
  1665. removingFromWishlist: 'Removing the game from the Steam wishlist',
  1666. followingGame: 'Following Steam games',
  1667. unfollowingGame: 'Unfollowing Steam games',
  1668. favoritingWorkshop: 'Favouring Steam Workshop Items',
  1669. unfavoritingWorkshop: 'Unfavoriting Steam Workshop Items',
  1670. gettingWorkshopAppId: 'Getting Steam Workshop Item Id',
  1671. votingUpWorkshop: 'Liking Steam workshop items',
  1672. gettingAnnouncementParams: 'Getting Steam announcement information',
  1673. likingAnnouncement: 'Liking Steam announcement',
  1674. changingArea: 'Changing Steam area: %0...',
  1675. notNeededChangeArea: 'The current area does not need to be changed',
  1676. noAnotherArea: 'Please check whether the proxy is turned on correctly',
  1677. gettingAreaInfo: 'Getting Steam area information...',
  1678. changeAreaNotice: 'Suspected of a locked zone game, try to change the zone to execute',
  1679. steamFinishNotice: 'Steam task completed, try to change the shopping cart area back to ',
  1680. gettingSubid: 'Getting subid',
  1681. addingFreeLicense: 'Adding free license',
  1682. missParams: 'Missing parameters',
  1683. gettingLicenses: 'Getting licenses...',
  1684. requestingPlayTestAccess: 'Requesting play test access',
  1685. 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.',
  1686. versionNotMatched: 'The script manager version is too low, requiring TamperMonkey >= 5.2.0 or TamperMonkey Beta >= 5.2.6196',
  1687. gettingUserLink: 'Getting steam user community link...',
  1688. retry: 'Retry',
  1689. owned: 'Owned',
  1690. redirect: 'Redirect',
  1691. noSubid: 'skip due to unrecognized',
  1692. initingASF: 'Initing ASF...',
  1693. servers: 'Server',
  1694. joiningDiscordServer: 'Joining Discord Server',
  1695. leavingDiscordServer: 'Leaving Discord Server',
  1696. gettingDiscordGuild: 'Getting Discord server Id',
  1697. getDiscordAuthFailed: 'Failed to get Discord token, please check whether the Discord account is logged in',
  1698. discordImportantNotice: 'Important Reminder! ! !',
  1699. 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! ! !',
  1700. continue: 'Continue',
  1701. skipDiscordTask: 'Skip',
  1702. continueAndDontRemindAgain: 'Continue without Reminders',
  1703. users: 'User',
  1704. loginIns: 'Please <a href="https://www.instagram.com/accounts/login/" target="_blank">log in to Instagram</a>',
  1705. insBanned: 'Your Instagram account has been banned',
  1706. verifyingInsAuth: 'Verifying Instagram token...',
  1707. gettingInsUserId: 'Getting Instagram user Id',
  1708. followingIns: 'Following Instagram user',
  1709. unfollowingIns: 'Unfollowing Instagram user',
  1710. reddits: 'Reddit/User',
  1711. loginReddit: 'Please <a href="https://www.reddit.com/login/" target="_blank">log in to Reddit</a>',
  1712. changingRedditVersion: 'Switching Reddit to a new version page...',
  1713. joiningReddit: 'Joining the Reddit',
  1714. leavingReddit: 'Leaving the Reddit',
  1715. followingRedditUser: 'Following Reddit User',
  1716. unfollowingRedditUser: 'Unfollowing Reddit User',
  1717. channels: 'Channel',
  1718. followingTwitchChannel: 'Following Twitch Channel',
  1719. unfollowingTwitchChannel: 'Unfollowing Twitch Channel',
  1720. gettingTwitchChannelId: 'Getting Twitch Channel Id',
  1721. checkingTwitchIntegrity: 'Checking Twitch integrity...',
  1722. twitterUser: 'Twitter User',
  1723. retweets: 'Retweet',
  1724. gettingTwitterUserId: 'Getting Twitter User Id',
  1725. followingTwitterUser: 'Following Twitter User',
  1726. unfollowingTwitterUser: 'Unfollowing Twitter User',
  1727. retweetting: 'Retweetting',
  1728. unretweetting: 'Unretweetting',
  1729. names: 'Group/Public/Wall',
  1730. loginVk: 'Please <a href="https://vk.com/login/" target="_blank">log in to Vk</a>',
  1731. gettingVkId: 'Getting Vk task Id',
  1732. joiningVkGroup: 'Joining Vk Group',
  1733. leavingVkGroup: 'Leaving Vk Group',
  1734. joiningVkPublic: 'Joining Vk Public',
  1735. leavingVkPublic: 'Leaving Vk Public',
  1736. sendingVkWall: 'Sending Vk Wall',
  1737. deletingVkWall: 'Deleting Vk Wall',
  1738. youtubeChannel: 'YouTube Channel',
  1739. likes: 'Like',
  1740. loginYtb: 'Please <a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">log in to YouTube</a>',
  1741. tryUpdateYtbAuth: 'Please try to <a href="https://www.youtube.com/#auth" target="_blank">update YouTube token</a>',
  1742. gettingYtbToken: 'Getting YouTube Token...',
  1743. followingYtbChannel: 'Subscribing to YouTube channel',
  1744. unfollowingYtbChannel: 'Unsubscribing to YouTube channel',
  1745. likingYtbVideo: 'Liking YouTube video',
  1746. unlikingYtbVideo: 'Unliking YouTube video',
  1747. giveKeyNoticeBefore: 'Each verification interval is 15s',
  1748. giveKeyNoticeAfter: 'If there is no key, please check at <a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>',
  1749. noPoints: 'Not enough points, skip the lottery',
  1750. getNeedPointsFailed: 'ailed to obtain the required points, skip the lottery',
  1751. joiningLottery: 'Joining the lottery',
  1752. doingGleamTask: 'Doing Gleam Task...',
  1753. gettingGleamLink: 'Getting Gleam task link...',
  1754. gleamTaskNotice: 'If this page has not been closed for a long time, please close it yourself after completing any task!',
  1755. verifiedGleamTasks: 'Attempted to verify all tasks. If the verification fails, please try to verify manually or complete it!',
  1756. campaign: 'ReCAPTCHA detected, please complete it and re-verify the tasks!',
  1757. 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!',
  1758. giveeClubVerifyNotice: 'Verifying task...',
  1759. giveeClubVerifyFinished: 'Wait for the verification to complete and join it by yourself',
  1760. doingKeyhubTask: 'Doing Keyhub Task...',
  1761. 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...',
  1762. tasksNotCompleted: 'Tasks Not Completed',
  1763. notConnect: 'Social platform is not connectted, skip',
  1764. tgTaskNotice: 'The telegram task is checked, need to do it yourself!',
  1765. confirmingTask: 'Confirming task...'
  1766. };
  1767. const en_US = en_US_data;
  1768. const languages = {
  1769. zh: zh_CN,
  1770. en: en_US
  1771. };
  1772. const language = [ 'zh', 'en' ].includes(globalOptions.other.language) ? globalOptions.other.language : 'en';
  1773. const I18n = (key, ...argvs) => {
  1774. if (!languages[language]?.[key]) {
  1775. return key;
  1776. }
  1777. return languages[language][key].replace(/%([\d]+)/g, (match, index) => argvs[parseInt(index, 10)]);
  1778. };
  1779. const i18n = I18n;
  1780. function throwError(error, name) {
  1781. if (window.TRACE) {
  1782. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  1783. }
  1784. external_Swal_default().fire({
  1785. title: i18n('errorReport'),
  1786. icon: 'error',
  1787. showCancelButton: true,
  1788. confirmButtonText: i18n('toGithub'),
  1789. showDenyButton: true,
  1790. denyButtonText: i18n('toKeylol'),
  1791. cancelButtonText: i18n('close')
  1792. }).then(({
  1793. isDenied,
  1794. isConfirmed
  1795. }) => {
  1796. if (isConfirmed) {
  1797. 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,
  1798. 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'))}`, {
  1799. active: true
  1800. });
  1801. } else if (isDenied) {
  1802. const text = `错误链接: [url=${window.location.href}]${window.location.href}[/url]
  1803.  
  1804. 环境:
  1805.  
  1806. [code]${JSON.stringify((0, javascript_utils_umd_min.ua)(), null, 4)}[/code]
  1807.  
  1808. 脚本管理器: ${GM_info.scriptHandler} ${GM_info.version}
  1809. 脚本版本: ${GM_info.script.version}
  1810.  
  1811. 报错信息:
  1812. [code]${error.stack}[/code]
  1813.  
  1814. 执行日志:
  1815. [code]${$.makeArray($('#auto-task-info>li')).map(element => element.innerText).join('\n')}[/code]`;
  1816. GM_setClipboard(text);
  1817. external_Swal_default().fire({
  1818. title: i18n('copySuccess'),
  1819. icon: 'success',
  1820. confirmButtonText: i18n('ok')
  1821. }).then(() => {
  1822. GM_openInTab('https://keylol.com/forum.php?mod=post&action=reply&fid=319&tid=777450', {
  1823. active: true
  1824. });
  1825. });
  1826. }
  1827. });
  1828. console.log('%c%s', 'color:white;background:red', `Auto-Task[Error]: ${name}\n${error.stack}`);
  1829. }
  1830. class Social {
  1831. tasks;
  1832. getRealParams(name, links, doTask, link2param) {
  1833. try {
  1834. let realParams = [];
  1835. if (links.length > 0) {
  1836. realParams = [ ...realParams, ...links.map(link => link2param(link)).filter(link => link) ];
  1837. }
  1838. if (!doTask && this.tasks[name].length > 0) {
  1839. realParams = [ ...realParams, ...this.tasks[name] ];
  1840. }
  1841. return unique(realParams);
  1842. } catch (error) {
  1843. throwError(error, 'Social.getRealParams');
  1844. return [];
  1845. }
  1846. }
  1847. }
  1848. const social_Social = Social;
  1849. class Discord extends social_Social {
  1850. tasks;
  1851. whiteList;
  1852. #auth = GM_getValue('discordAuth') || {};
  1853. #cache = GM_getValue('discordCache') || {};
  1854. #initialized = false;
  1855. constructor() {
  1856. super();
  1857. const defaultTasksTemplate = {
  1858. servers: []
  1859. };
  1860. this.tasks = defaultTasksTemplate;
  1861. this.whiteList = {
  1862. ...defaultTasksTemplate,
  1863. ...GM_getValue('whiteList')?.discord || {}
  1864. };
  1865. }
  1866. async init(action) {
  1867. try {
  1868. if (!GM_getValue('dontRemindDiscordAgain')) {
  1869. const result = await external_Swal_default().fire({
  1870. title: i18n('discordImportantNotice'),
  1871. text: i18n('discordImportantNoticeText'),
  1872. showCancelButton: true,
  1873. showDenyButton: true,
  1874. confirmButtonText: i18n('continue'),
  1875. cancelButtonText: i18n('skipDiscordTask'),
  1876. denyButtonText: i18n('continueAndDontRemindAgain')
  1877. }).then(({
  1878. isConfirmed,
  1879. isDenied
  1880. }) => {
  1881. if (isConfirmed) {
  1882. return true;
  1883. }
  1884. if (isDenied) {
  1885. GM_setValue('dontRemindDiscordAgain', true);
  1886. return true;
  1887. }
  1888. return false;
  1889. });
  1890. if (!result) {
  1891. this.#initialized = false;
  1892. return 'skip';
  1893. }
  1894. }
  1895. if (GM_getValue('dontRemindDiscordAgain') || action === 'do' && !globalOptions.doTask.discord.servers || action === 'undo' && !globalOptions.undoTask.discord.servers) {
  1896. this.#initialized = false;
  1897. return 'skip';
  1898. }
  1899. if (this.#initialized) {
  1900. return true;
  1901. }
  1902. if (!this.#auth.auth) {
  1903. if (await this.#updateAuth()) {
  1904. this.#initialized = true;
  1905. return true;
  1906. }
  1907. return false;
  1908. }
  1909. const isVerified = await this.#verifyAuth();
  1910. if (isVerified) {
  1911. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  1912. this.#initialized = true;
  1913. return true;
  1914. }
  1915. GM_setValue('discordAuth', {
  1916. auth: null
  1917. });
  1918. if (await this.#updateAuth()) {
  1919. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  1920. this.#initialized = true;
  1921. return true;
  1922. }
  1923. scripts_echoLog({}).error(i18n('initFailed', 'Discord'));
  1924. return false;
  1925. } catch (error) {
  1926. throwError(error, 'Discord.init');
  1927. return false;
  1928. }
  1929. }
  1930. async #verifyAuth() {
  1931. try {
  1932. const logStatus = scripts_echoLog({
  1933. text: i18n('verifyingAuth', 'Discord')
  1934. });
  1935. const {
  1936. result,
  1937. statusText,
  1938. status,
  1939. data
  1940. } = await tools_httpRequest({
  1941. url: 'https://discord.com/api/v6/users/@me',
  1942. method: 'HEAD',
  1943. headers: {
  1944. authorization: this.#auth.auth
  1945. }
  1946. });
  1947. if (result === 'Success') {
  1948. if (data?.status === 200) {
  1949. logStatus.success();
  1950. return true;
  1951. }
  1952. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  1953. return false;
  1954. }
  1955. logStatus.error(`${result}:${statusText}(${status})`);
  1956. return false;
  1957. } catch (error) {
  1958. throwError(error, 'Discord.verifyAuth');
  1959. return false;
  1960. }
  1961. }
  1962. async #updateAuth() {
  1963. try {
  1964. const logStatus = scripts_echoLog({
  1965. text: i18n('updatingAuth', 'Discord')
  1966. });
  1967. return await new Promise(resolve => {
  1968. const newTab = GM_openInTab('https://discord.com/channels/@me', {
  1969. active: true,
  1970. insert: true,
  1971. setParent: true
  1972. });
  1973. newTab.name = 'ATv4_discordAuth';
  1974. newTab.onclose = async () => {
  1975. const auth = GM_getValue('discordAuth')?.auth;
  1976. if (auth) {
  1977. this.#auth = {
  1978. auth: auth
  1979. };
  1980. logStatus.success();
  1981. resolve(await this.#verifyAuth());
  1982. } else {
  1983. logStatus.error('Error: Update discord auth failed!');
  1984. resolve(false);
  1985. }
  1986. };
  1987. });
  1988. } catch (error) {
  1989. throwError(error, 'Discord.updateAuth');
  1990. return false;
  1991. }
  1992. }
  1993. async #joinServer(inviteId) {
  1994. try {
  1995. const logStatus = scripts_echoLog({
  1996. type: 'joiningDiscordServer',
  1997. text: inviteId
  1998. });
  1999. const {
  2000. result,
  2001. statusText,
  2002. status,
  2003. data
  2004. } = await tools_httpRequest({
  2005. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2006. method: 'POST',
  2007. dataType: 'json',
  2008. headers: {
  2009. authorization: this.#auth.auth,
  2010. origin: 'https://discord.com',
  2011. referer: `https://discord.com/invite/${inviteId}`
  2012. }
  2013. });
  2014. if (result === 'Success' && data?.status === 200) {
  2015. logStatus.success();
  2016. const guild = String(data.response?.guild?.id);
  2017. if (guild) {
  2018. this.#setCache(inviteId, guild);
  2019. this.tasks.servers = unique([ ...this.tasks.servers, inviteId ]);
  2020. }
  2021. return true;
  2022. }
  2023. logStatus.error(`${result}:${statusText}(${status})`);
  2024. return false;
  2025. } catch (error) {
  2026. throwError(error, 'Discord.joinServer');
  2027. return false;
  2028. }
  2029. }
  2030. async #leaveServer(inviteId) {
  2031. try {
  2032. if (this.whiteList.servers.includes(inviteId)) {
  2033. scripts_echoLog({
  2034. type: 'whiteList',
  2035. text: 'Discord.leaveServer',
  2036. id: inviteId
  2037. });
  2038. return true;
  2039. }
  2040. const guild = await this.#getGuild(inviteId);
  2041. if (!guild) {
  2042. return false;
  2043. }
  2044. const logStatus = scripts_echoLog({
  2045. type: 'leavingDiscordServer',
  2046. text: guild
  2047. });
  2048. const {
  2049. result,
  2050. statusText,
  2051. status,
  2052. data
  2053. } = await tools_httpRequest({
  2054. url: `https://discord.com/api/v9/users/@me/guilds/${guild}`,
  2055. method: 'DELETE',
  2056. headers: {
  2057. authorization: this.#auth.auth
  2058. }
  2059. });
  2060. if (result === 'Success' && data?.status === 204) {
  2061. logStatus.success();
  2062. return true;
  2063. }
  2064. logStatus.error(`${result}:${statusText}(${status})`);
  2065. return false;
  2066. } catch (error) {
  2067. throwError(error, 'Discord.leaveServer');
  2068. return false;
  2069. }
  2070. }
  2071. async #getGuild(inviteId) {
  2072. try {
  2073. const logStatus = scripts_echoLog({
  2074. type: 'gettingDiscordGuild',
  2075. text: inviteId
  2076. });
  2077. const guild = this.#cache[inviteId];
  2078. if (guild) {
  2079. logStatus.success();
  2080. return guild;
  2081. }
  2082. const {
  2083. result,
  2084. statusText,
  2085. status,
  2086. data
  2087. } = await tools_httpRequest({
  2088. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2089. responseType: 'json',
  2090. method: 'GET'
  2091. });
  2092. if (result === 'Success' && data?.status === 200) {
  2093. const guild = data.response?.guild?.id;
  2094. if (guild) {
  2095. logStatus.success();
  2096. this.#setCache(inviteId, guild);
  2097. return guild;
  2098. }
  2099. logStatus.error(`${result}:${statusText}(${status})`);
  2100. return false;
  2101. }
  2102. logStatus.error(`${result}:${statusText}(${status})`);
  2103. return false;
  2104. } catch (error) {
  2105. throwError(error, 'Discord.getGuild');
  2106. return false;
  2107. }
  2108. }
  2109. async toggle({
  2110. doTask = true,
  2111. serverLinks = []
  2112. }) {
  2113. try {
  2114. if (!this.#initialized) {
  2115. scripts_echoLog({
  2116. text: i18n('needInit')
  2117. });
  2118. return false;
  2119. }
  2120. const prom = [];
  2121. if (doTask && !globalOptions.doTask.discord.servers || !doTask && !globalOptions.undoTask.discord.servers) {
  2122. scripts_echoLog({
  2123. type: 'globalOptionsSkip',
  2124. text: 'discord.servers'
  2125. });
  2126. } else {
  2127. const realServers = this.getRealParams('servers', serverLinks, doTask, link => link.match(/invite\/(.+)/)?.[1]);
  2128. if (realServers.length > 0) {
  2129. for (const server of realServers) {
  2130. if (doTask) {
  2131. prom.push(this.#joinServer(server));
  2132. } else {
  2133. prom.push(this.#leaveServer(server));
  2134. }
  2135. await delay(1e3);
  2136. }
  2137. }
  2138. }
  2139. return await Promise.all(prom).then(() => true);
  2140. } catch (error) {
  2141. throwError(error, 'Discord.toggleServers');
  2142. return false;
  2143. }
  2144. }
  2145. #setCache(inviteId, guild) {
  2146. try {
  2147. this.#cache[inviteId] = guild;
  2148. GM_setValue('discordCache', this.#cache);
  2149. } catch (error) {
  2150. throwError(error, 'Discord.setCache');
  2151. }
  2152. }
  2153. }
  2154. const social_Discord = Discord;
  2155. class Instagram extends social_Social {
  2156. tasks;
  2157. whiteList;
  2158. #cache = GM_getValue('instagramCache') || {};
  2159. #auth = {};
  2160. #initialized = false;
  2161. constructor() {
  2162. super();
  2163. const defaultTasksTemplate = {
  2164. users: []
  2165. };
  2166. this.tasks = defaultTasksTemplate;
  2167. this.whiteList = {
  2168. ...defaultTasksTemplate,
  2169. ...GM_getValue('whiteList')?.instagram || {}
  2170. };
  2171. }
  2172. async init() {
  2173. try {
  2174. if (this.#initialized) {
  2175. return true;
  2176. }
  2177. const isVerified = await this.#getUserInfo();
  2178. if (isVerified) {
  2179. scripts_echoLog({}).success(i18n('initSuccess', 'Instagram'));
  2180. this.#initialized = true;
  2181. return true;
  2182. }
  2183. scripts_echoLog({}).error(i18n('initFailed', 'Instagram'));
  2184. return false;
  2185. } catch (error) {
  2186. throwError(error, 'Instagram.init');
  2187. return false;
  2188. }
  2189. }
  2190. async #getUserInfo(name = 'instagram') {
  2191. try {
  2192. const logStatus = scripts_echoLog({
  2193. type: name === 'instagram' ? 'verifyingInsAuth' : 'gettingInsUserId',
  2194. text: name
  2195. });
  2196. const userId = this.#cache[name];
  2197. if (userId && name !== 'instagram') {
  2198. logStatus.success();
  2199. return userId;
  2200. }
  2201. const {
  2202. result,
  2203. statusText,
  2204. status,
  2205. data
  2206. } = await tools_httpRequest({
  2207. url: `https://www.instagram.com/${name}/`,
  2208. method: 'GET'
  2209. });
  2210. if (result === 'Success') {
  2211. if (data?.finalUrl.includes('accounts/login')) {
  2212. logStatus.error(`Error:${i18n('loginIns')}`, true);
  2213. return false;
  2214. } else if (data?.finalUrl.includes('www.instagram.com/challenge')) {
  2215. logStatus.error(`Error:${i18n('insBanned')}`);
  2216. return false;
  2217. }
  2218. if (data?.status === 200) {
  2219. const csrftoken = data.responseText.match(/"csrf_token":"(.+?)"/)?.[1];
  2220. const hash = data.responseText.match(/"rollout_hash":"(.+?)"/)?.[1];
  2221. if (name === 'instagram') {
  2222. if (csrftoken && hash) {
  2223. this.#auth = {
  2224. csrftoken: csrftoken,
  2225. hash: hash
  2226. };
  2227. return true;
  2228. }
  2229. return false;
  2230. }
  2231. const id = data.responseText.match(/"profilePage_([\d]+?)"/)?.[1];
  2232. if (id) {
  2233. this.#setCache(name, id);
  2234. logStatus.success();
  2235. return id;
  2236. }
  2237. logStatus.error('Error: Get ins data error!');
  2238. return false;
  2239. }
  2240. logStatus.error(`${result}:${statusText}(${status})`);
  2241. return false;
  2242. }
  2243. return false;
  2244. } catch (error) {
  2245. throwError(error, 'Instagram.getUserInfo');
  2246. return false;
  2247. }
  2248. }
  2249. async #followUser(name) {
  2250. try {
  2251. const id = await this.#getUserInfo(name);
  2252. if (!id) {
  2253. return false;
  2254. }
  2255. const logStatus = scripts_echoLog({
  2256. type: 'followingIns',
  2257. text: name
  2258. });
  2259. const {
  2260. result,
  2261. statusText,
  2262. status,
  2263. data
  2264. } = await tools_httpRequest({
  2265. url: `https://www.instagram.com/web/friendships/${id}/follow/`,
  2266. method: 'POST',
  2267. dataType: 'json',
  2268. headers: {
  2269. 'x-csrftoken': this.#auth.csrftoken,
  2270. origin: 'https://www.instagram.com',
  2271. referer: `https://www.instagram.com/${name}/`,
  2272. 'content-type': 'application/x-www-form-urlencoded',
  2273. 'sec-fetch-site': 'same-origin',
  2274. 'x-instagram-ajax': this.#auth.hash
  2275. }
  2276. });
  2277. if (result === 'Success') {
  2278. if (data?.status === 200 && data.response?.result === 'following') {
  2279. logStatus.success();
  2280. this.tasks.users = unique([ ...this.tasks.users, name ]);
  2281. return true;
  2282. }
  2283. logStatus.error(`Error:${data?.response?.feedback_message || `${data?.statusText}(${data?.status})`}`);
  2284. return false;
  2285. }
  2286. logStatus.error(`${result}:${statusText}(${status})`);
  2287. return false;
  2288. } catch (error) {
  2289. throwError(error, 'Instagram.followUser');
  2290. return false;
  2291. }
  2292. }
  2293. async #unfollowUser(name) {
  2294. try {
  2295. if (this.whiteList.users.includes(name)) {
  2296. scripts_echoLog({
  2297. type: 'whiteList',
  2298. text: 'Instagram.unfollowUser',
  2299. id: name
  2300. });
  2301. return true;
  2302. }
  2303. const id = await this.#getUserInfo(name);
  2304. if (!id) {
  2305. return false;
  2306. }
  2307. const logStatus = scripts_echoLog({
  2308. type: 'unfollowingIns',
  2309. text: name
  2310. });
  2311. const {
  2312. result,
  2313. statusText,
  2314. status,
  2315. data
  2316. } = await tools_httpRequest({
  2317. url: `https://www.instagram.com/web/friendships/${id}/unfollow/`,
  2318. method: 'POST',
  2319. dataType: 'json',
  2320. headers: {
  2321. 'x-csrftoken': this.#auth.csrftoken,
  2322. origin: 'https://www.instagram.com',
  2323. referer: `https://www.instagram.com/${name}/`,
  2324. 'content-type': 'application/x-www-form-urlencoded',
  2325. 'sec-fetch-site': 'same-origin',
  2326. 'x-instagram-ajax': this.#auth.hash
  2327. }
  2328. });
  2329. if (result === 'Success') {
  2330. if (data?.status === 200 && data.response?.status === 'ok') {
  2331. logStatus.success();
  2332. return true;
  2333. }
  2334. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2335. return false;
  2336. }
  2337. logStatus.error(`${result}:${statusText}(${status})`);
  2338. return false;
  2339. } catch (error) {
  2340. throwError(error, 'Instagram.unfollowUser');
  2341. return false;
  2342. }
  2343. }
  2344. async toggle({
  2345. doTask = true,
  2346. userLinks = []
  2347. }) {
  2348. try {
  2349. if (!this.#initialized) {
  2350. scripts_echoLog({
  2351. text: i18n('needInit')
  2352. });
  2353. return false;
  2354. }
  2355. const prom = [];
  2356. if (doTask && !globalOptions.doTask.instagram.users || !doTask && !globalOptions.undoTask.instagram.users) {
  2357. scripts_echoLog({
  2358. type: 'globalOptionsSkip',
  2359. text: 'instagram.users'
  2360. });
  2361. } else {
  2362. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1]);
  2363. if (realUsers.length > 0) {
  2364. for (const username of realUsers) {
  2365. if (doTask) {
  2366. prom.push(this.#followUser(username));
  2367. } else {
  2368. prom.push(this.#unfollowUser(username));
  2369. }
  2370. await delay(1e3);
  2371. }
  2372. }
  2373. }
  2374. return await Promise.all(prom).then(() => true);
  2375. } catch (error) {
  2376. throwError(error, 'Instagram.toggleUsers');
  2377. return false;
  2378. }
  2379. }
  2380. #setCache(name, id) {
  2381. try {
  2382. this.#cache[name] = id;
  2383. GM_setValue('instagramCache', this.#cache);
  2384. } catch (error) {
  2385. throwError(error, 'Instagram.setCache');
  2386. }
  2387. }
  2388. }
  2389. const social_Instagram = Instagram;
  2390. class Reddit extends social_Social {
  2391. tasks;
  2392. whiteList;
  2393. #auth;
  2394. #initialized = false;
  2395. constructor() {
  2396. super();
  2397. const defaultTasksTemplate = {
  2398. reddits: []
  2399. };
  2400. this.tasks = defaultTasksTemplate;
  2401. this.whiteList = {
  2402. ...defaultTasksTemplate,
  2403. ...GM_getValue('whiteList')?.reddit || {}
  2404. };
  2405. }
  2406. async init() {
  2407. try {
  2408. if (this.#initialized) {
  2409. return true;
  2410. }
  2411. const isVerified = await this.#updateAuth();
  2412. if (isVerified) {
  2413. scripts_echoLog({}).success(i18n('initSuccess', 'Reddit'));
  2414. this.#initialized = true;
  2415. return true;
  2416. }
  2417. scripts_echoLog({}).error(i18n('initFailed', 'Reddit'));
  2418. return false;
  2419. } catch (error) {
  2420. throwError(error, 'Reddit.init');
  2421. return false;
  2422. }
  2423. }
  2424. async #useBeta() {
  2425. try {
  2426. const logStatus = scripts_echoLog({
  2427. text: i18n('changingRedditVersion')
  2428. });
  2429. return await new Promise(resolve => {
  2430. const newTab = GM_openInTab('https://www.reddit.com/', {
  2431. active: true,
  2432. insert: true,
  2433. setParent: true
  2434. });
  2435. newTab.name = 'ATv4_redditAuth';
  2436. newTab.onclose = async () => {
  2437. logStatus.success();
  2438. resolve(await this.#updateAuth(true));
  2439. };
  2440. });
  2441. } catch (error) {
  2442. throwError(error, 'Reddit.useBeta');
  2443. return false;
  2444. }
  2445. }
  2446. async #updateAuth(beta = false) {
  2447. try {
  2448. const logStatus = scripts_echoLog({
  2449. text: i18n('updatingAuth', 'Reddit')
  2450. });
  2451. const {
  2452. result,
  2453. statusText,
  2454. status,
  2455. data
  2456. } = await tools_httpRequest({
  2457. url: 'https://www.reddit.com/',
  2458. method: 'GET',
  2459. nochche: true,
  2460. headers: {
  2461. 'Cache-Control': 'no-cache'
  2462. }
  2463. });
  2464. if (result === 'Success') {
  2465. if (data?.responseText.includes('www.reddit.com/login/')) {
  2466. logStatus.error(`Error:${i18n('loginReddit')}`, true);
  2467. return false;
  2468. }
  2469. if (data?.status === 200) {
  2470. if (data.responseText.includes('redesign-beta-optin-btn') && !beta) {
  2471. return await this.#useBeta();
  2472. }
  2473. const accessToken = data.responseText.match(/"accessToken":"(.*?)","expires":"(.*?)"/)?.[1];
  2474. if (accessToken) {
  2475. this.#auth = {
  2476. token: accessToken
  2477. };
  2478. logStatus.success();
  2479. return true;
  2480. }
  2481. logStatus.error('Error: Parameter "accessToken" not found!');
  2482. return false;
  2483. }
  2484. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2485. return false;
  2486. }
  2487. logStatus.error(`${result}:${statusText}(${status})`);
  2488. return false;
  2489. } catch (error) {
  2490. throwError(error, 'Reddit.updateAuth');
  2491. return false;
  2492. }
  2493. }
  2494. async #toggleTask({
  2495. name,
  2496. doTask = true
  2497. }) {
  2498. try {
  2499. if (!doTask && this.whiteList.reddits.includes(name)) {
  2500. scripts_echoLog({
  2501. type: 'whiteList',
  2502. text: 'Reddit.undoTask',
  2503. id: name
  2504. });
  2505. return true;
  2506. }
  2507. let type = doTask ? 'joiningReddit' : 'leavingReddit';
  2508. if (/^u_/.test(name)) {
  2509. type = doTask ? 'followingRedditUser' : 'unfollowingRedditUser';
  2510. }
  2511. const logStatus = scripts_echoLog({
  2512. type: type,
  2513. text: name
  2514. });
  2515. const {
  2516. result,
  2517. statusText,
  2518. status,
  2519. data
  2520. } = await tools_httpRequest({
  2521. url: 'https://oauth.reddit.com/api/subscribe?redditWebClient=desktop2x&app=desktop2x-client-production&raw_json=1&gilding_detail=1',
  2522. method: 'POST',
  2523. headers: {
  2524. authorization: `Bearer ${this.#auth.token}`,
  2525. 'content-type': 'application/x-www-form-urlencoded'
  2526. },
  2527. data: $.param({
  2528. action: doTask ? 'sub' : 'unsub',
  2529. sr_name: name,
  2530. api_type: 'json'
  2531. })
  2532. });
  2533. if (result === 'Success') {
  2534. if (data?.status === 200) {
  2535. logStatus.success();
  2536. if (doTask) {
  2537. this.tasks.reddits = unique([ ...this.tasks.reddits, name ]);
  2538. }
  2539. return true;
  2540. }
  2541. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2542. return false;
  2543. }
  2544. logStatus.error(`${result}:${statusText}(${status})`);
  2545. return false;
  2546. } catch (error) {
  2547. throwError(error, 'Reddit.toggleTask');
  2548. return false;
  2549. }
  2550. }
  2551. async toggle({
  2552. doTask = true,
  2553. redditLinks = []
  2554. }) {
  2555. try {
  2556. if (!this.#initialized) {
  2557. scripts_echoLog({
  2558. text: i18n('needInit')
  2559. });
  2560. return false;
  2561. }
  2562. const prom = [];
  2563. if (doTask && !globalOptions.doTask.reddit.reddits || !doTask && !globalOptions.undoTask.reddit.reddits) {
  2564. scripts_echoLog({
  2565. type: 'globalOptionsSkip',
  2566. text: 'reddit.reddits'
  2567. });
  2568. } else {
  2569. const realReddits = this.getRealParams('reddits', redditLinks, doTask, link => {
  2570. const name = link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1];
  2571. const userName = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1];
  2572. if (userName) {
  2573. return name || userName;
  2574. }
  2575. return name;
  2576. });
  2577. if (realReddits.length > 0) {
  2578. for (const name of realReddits) {
  2579. prom.push(this.#toggleTask({
  2580. name: name,
  2581. doTask: doTask
  2582. }));
  2583. await delay(1e3);
  2584. }
  2585. }
  2586. }
  2587. return await Promise.all(prom).then(() => true);
  2588. } catch (error) {
  2589. throwError(error, 'Reddit.toggle');
  2590. return false;
  2591. }
  2592. }
  2593. }
  2594. const social_Reddit = Reddit;
  2595. class Twitch extends social_Social {
  2596. tasks;
  2597. whiteList;
  2598. #auth = GM_getValue('twitchAuth') || {};
  2599. #cache = GM_getValue('twitchCache') || {};
  2600. #initialized = false;
  2601. #integrityToken;
  2602. constructor() {
  2603. super();
  2604. const defaultTasksTemplate = {
  2605. channels: []
  2606. };
  2607. this.tasks = defaultTasksTemplate;
  2608. this.whiteList = {
  2609. ...defaultTasksTemplate,
  2610. ...GM_getValue('whiteList')?.twitch || {}
  2611. };
  2612. }
  2613. async init() {
  2614. try {
  2615. if (this.#initialized) {
  2616. return true;
  2617. }
  2618. if (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId) {
  2619. if (await this.#updateAuth()) {
  2620. this.#initialized = true;
  2621. return true;
  2622. }
  2623. return false;
  2624. }
  2625. const isVerified = await this.#verifyAuth(true);
  2626. if (isVerified) {
  2627. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  2628. this.#initialized = true;
  2629. return true;
  2630. }
  2631. GM_setValue('twitchAuth', null);
  2632. if (await this.#updateAuth()) {
  2633. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  2634. this.#initialized = true;
  2635. return true;
  2636. }
  2637. scripts_echoLog({}).error(i18n('initFailed', 'Twitch'));
  2638. return false;
  2639. } catch (error) {
  2640. throwError(error, 'Twitch.init');
  2641. return false;
  2642. }
  2643. }
  2644. async #verifyAuth(isFirst) {
  2645. try {
  2646. const logStatus = scripts_echoLog({
  2647. text: i18n('verifyingAuth', 'Twitch')
  2648. });
  2649. const {
  2650. result,
  2651. statusText,
  2652. status,
  2653. data
  2654. } = await tools_httpRequest({
  2655. url: 'https://gql.twitch.tv/gql',
  2656. method: 'POST',
  2657. dataType: 'json',
  2658. headers: {
  2659. Authorization: `OAuth ${this.#auth.authToken}`,
  2660. 'Client-Id': this.#auth.clientId
  2661. },
  2662. data: '[{"operationName":"FrontPageNew_User","variables":{"limit":1},"extensions":{"persistedQuery":{"version":1,' + '"sha256Hash":"64bd07a2cbaca80699d62636d966cf6395a5d14a1f0a14282067dcb28b13eb11"}}}]'
  2663. });
  2664. if (result === 'Success') {
  2665. if (data?.status === 200 && data.response?.[0]?.data?.currentUser) {
  2666. await this.#integrity(isFirst);
  2667. logStatus.success();
  2668. return true;
  2669. }
  2670. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2671. return false;
  2672. }
  2673. logStatus.error(`${result}:${statusText}(${status})`);
  2674. return false;
  2675. } catch (error) {
  2676. throwError(error, 'Twitch.verifyAuth');
  2677. return false;
  2678. }
  2679. }
  2680. async #integrity(isFirst = true, ct = '') {
  2681. try {
  2682. const logStatus = scripts_echoLog({
  2683. text: i18n('checkingTwitchIntegrity')
  2684. });
  2685. if (isFirst && (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId)) {
  2686. return await this.#updateAuth(false);
  2687. }
  2688. const {
  2689. result,
  2690. statusText,
  2691. status,
  2692. data
  2693. } = await tools_httpRequest({
  2694. url: 'https://gql.twitch.tv/integrity',
  2695. method: 'POST',
  2696. dataType: 'json',
  2697. anonymous: true,
  2698. headers: {
  2699. Origin: 'https://www.twitch.tv',
  2700. Referer: 'https://www.twitch.tv/',
  2701. Authorization: `OAuth ${this.#auth.authToken}`,
  2702. 'Client-Id': this.#auth.clientId,
  2703. 'Client-Version': this.#auth.clientVersion,
  2704. 'X-Device-Id': this.#auth.deviceId,
  2705. 'Client-Session-Id': this.#auth.clientSessionId,
  2706. 'x-kpsdk-ct': ct
  2707. }
  2708. });
  2709. if (result === 'Success') {
  2710. if (!ct && data?.responseHeaders?.['x-kpsdk-ct']) {
  2711. return await this.#integrity(isFirst, data.responseHeaders['x-kpsdk-ct']);
  2712. }
  2713. if (data?.status === 200 && data.response?.token) {
  2714. this.#integrityToken = data.response.token;
  2715. logStatus.success();
  2716. return true;
  2717. }
  2718. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2719. return false;
  2720. }
  2721. logStatus.error(`${result}:${statusText}(${status})`);
  2722. return false;
  2723. } catch (error) {
  2724. throwError(error, 'Twitch.integrity');
  2725. return false;
  2726. }
  2727. }
  2728. async #updateAuth(isFirst = true) {
  2729. try {
  2730. const logStatus = scripts_echoLog({
  2731. text: i18n('updatingAuth', 'Twitch')
  2732. });
  2733. return await new Promise(resolve => {
  2734. const newTab = GM_openInTab('https://www.twitch.tv/', {
  2735. active: true,
  2736. insert: true,
  2737. setParent: true
  2738. });
  2739. newTab.name = 'ATv4_twitchAuth';
  2740. newTab.onclose = async () => {
  2741. const auth = GM_getValue('twitchAuth');
  2742. if (auth) {
  2743. this.#auth = auth;
  2744. logStatus.success();
  2745. resolve(await this.#verifyAuth(isFirst));
  2746. } else {
  2747. logStatus.error('Error: Update twitch auth failed!');
  2748. resolve(false);
  2749. }
  2750. };
  2751. });
  2752. } catch (error) {
  2753. throwError(error, 'Twitch.updateAuth');
  2754. return false;
  2755. }
  2756. }
  2757. async #toggleChannel({
  2758. name,
  2759. doTask = true
  2760. }) {
  2761. try {
  2762. if (!doTask && this.whiteList.channels.includes(name)) {
  2763. scripts_echoLog({
  2764. type: 'whiteList',
  2765. text: 'Twitch.unfollowChannel',
  2766. id: name
  2767. });
  2768. return true;
  2769. }
  2770. const channelId = await this.#getChannelId(name);
  2771. if (!channelId) {
  2772. return false;
  2773. }
  2774. const logStatus = scripts_echoLog({
  2775. type: `${doTask ? '' : 'un'}followingTwitchChannel`,
  2776. text: name
  2777. });
  2778. const followData = `[{"operationName":"FollowButton_FollowUser","variables":{"input":{"disableNotifications":false,"targetID":"${channelId}` + '"}},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"800e7346bdf7e5278a3c1d3f21b2b56e2639928f86815677a7126b093b2fdd08"}}}]';
  2779. const unfollowData = `[{"operationName":"FollowButton_UnfollowUser","variables":{"input":{"targetID":"${channelId}"}},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"f7dae976ebf41c755ae2d758546bfd176b4eeb856656098bb40e0a672ca0d880"}}}]';
  2780. const {
  2781. result,
  2782. statusText,
  2783. status,
  2784. data
  2785. } = await tools_httpRequest({
  2786. url: 'https://gql.twitch.tv/gql',
  2787. method: 'POST',
  2788. dataType: 'json',
  2789. anonymous: true,
  2790. headers: {
  2791. Origin: 'https://www.twitch.tv',
  2792. Referer: 'https://www.twitch.tv/',
  2793. Authorization: `OAuth ${this.#auth.authToken}`,
  2794. 'Client-Id': this.#auth.clientId,
  2795. 'Client-Version': this.#auth.clientVersion,
  2796. 'X-Device-Id': this.#auth.deviceId,
  2797. 'Client-Session-Id': this.#auth.clientSessionId,
  2798. 'Client-Integrity': this.#integrityToken
  2799. },
  2800. data: doTask ? followData : unfollowData
  2801. });
  2802. if (result === 'Success') {
  2803. if (data?.status === 200 && data.response?.[0] && !data.response[0].errors) {
  2804. logStatus.success();
  2805. if (doTask) {
  2806. this.tasks.channels = unique([ ...this.tasks.channels, name ]);
  2807. }
  2808. return true;
  2809. }
  2810. logStatus.error(`Error:${data?.response?.[0].errors?.[0]?.message || `${data?.statusText}(${data?.status})`}`);
  2811. return false;
  2812. }
  2813. logStatus.error(`${result}:${statusText}(${status})`);
  2814. return false;
  2815. } catch (error) {
  2816. throwError(error, 'Twitch.toggleChannel');
  2817. return false;
  2818. }
  2819. }
  2820. async #getChannelId(name) {
  2821. try {
  2822. const logStatus = scripts_echoLog({
  2823. type: 'gettingTwitchChannelId',
  2824. text: name
  2825. });
  2826. const channelId = this.#cache[name];
  2827. if (channelId) {
  2828. logStatus.success();
  2829. return channelId;
  2830. }
  2831. const {
  2832. result,
  2833. statusText,
  2834. status,
  2835. data
  2836. } = await tools_httpRequest({
  2837. url: 'https://gql.twitch.tv/gql',
  2838. method: 'POST',
  2839. headers: {
  2840. Authorization: `OAuth ${this.#auth.authToken}`,
  2841. 'Client-Id': this.#auth.clientId
  2842. },
  2843. responseType: 'json',
  2844. data: `[{"operationName":"ActiveWatchParty","variables":{"channelLogin":"${name}"},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"4a8156c97b19e3a36e081cf6d6ddb5dbf9f9b02ae60e4d2ff26ed70aebc80a30"}}}]'
  2845. });
  2846. if (result === 'Success') {
  2847. if (data?.status === 200) {
  2848. const channelId = data.response?.[0]?.data?.user?.id;
  2849. if (channelId) {
  2850. this.#setCache(name, String(channelId));
  2851. logStatus.success();
  2852. return channelId;
  2853. }
  2854. logStatus.error(`Error:${data.statusText}(${data.status})`);
  2855. return false;
  2856. }
  2857. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2858. return false;
  2859. }
  2860. logStatus.error(`${result}:${statusText}(${status})`);
  2861. return false;
  2862. } catch (error) {
  2863. throwError(error, 'Twitch.getChannelId');
  2864. return false;
  2865. }
  2866. }
  2867. async toggle({
  2868. doTask = true,
  2869. channelLinks = []
  2870. }) {
  2871. try {
  2872. if (!this.#initialized) {
  2873. scripts_echoLog({
  2874. text: i18n('needInit')
  2875. });
  2876. return false;
  2877. }
  2878. const prom = [];
  2879. if (doTask && !globalOptions.doTask.twitch.channels || !doTask && !globalOptions.undoTask.twitch.channels) {
  2880. scripts_echoLog({
  2881. type: 'globalOptionsSkip',
  2882. text: 'twitch.channels'
  2883. });
  2884. } else {
  2885. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2]);
  2886. if (realChannels.length > 0) {
  2887. for (const channel of realChannels) {
  2888. prom.push(this.#toggleChannel({
  2889. name: channel,
  2890. doTask: doTask
  2891. }));
  2892. await delay(1e3);
  2893. }
  2894. }
  2895. }
  2896. return Promise.all(prom).then(() => true);
  2897. } catch (error) {
  2898. throwError(error, 'Twitch.toggle');
  2899. return false;
  2900. }
  2901. }
  2902. #setCache(name, id) {
  2903. try {
  2904. this.#cache[name] = id;
  2905. GM_setValue('twitchCache', this.#cache);
  2906. } catch (error) {
  2907. throwError(error, 'Twitch.setCache');
  2908. }
  2909. }
  2910. }
  2911. const social_Twitch = Twitch;
  2912. class Twitter extends social_Social {
  2913. tasks;
  2914. whiteList;
  2915. #verifyId = globalOptions.other.twitterVerifyId;
  2916. #auth = GM_getValue('twitterAuth') || {};
  2917. #cache = GM_getValue('twitterCache') || {};
  2918. #initialized = false;
  2919. constructor() {
  2920. super();
  2921. const defaultTasksTemplate = {
  2922. users: [],
  2923. retweets: [],
  2924. likes: []
  2925. };
  2926. this.tasks = defaultTasksTemplate;
  2927. this.whiteList = {
  2928. ...defaultTasksTemplate,
  2929. ...GM_getValue('whiteList')?.twitter || {}
  2930. };
  2931. }
  2932. async init() {
  2933. try {
  2934. if (this.#initialized) {
  2935. return true;
  2936. }
  2937. if (!this.#auth.ct0) {
  2938. if (await this.#updateAuth()) {
  2939. this.#initialized = true;
  2940. return true;
  2941. }
  2942. return false;
  2943. }
  2944. const isVerified = await this.#verifyAuth();
  2945. if (isVerified) {
  2946. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  2947. this.#initialized = true;
  2948. return true;
  2949. }
  2950. GM_setValue('twitterAuth', null);
  2951. if (await this.#updateAuth()) {
  2952. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  2953. this.#initialized = true;
  2954. return true;
  2955. }
  2956. scripts_echoLog({}).error(i18n('initFailed', 'Twitter'));
  2957. return false;
  2958. } catch (error) {
  2959. throwError(error, 'Twitter.init');
  2960. return false;
  2961. }
  2962. }
  2963. async #verifyAuth() {
  2964. try {
  2965. return await this.#toggleUser({
  2966. name: 'verify',
  2967. doTask: true,
  2968. verify: true
  2969. });
  2970. } catch (error) {
  2971. throwError(error, 'Twitter.verifyAuth');
  2972. return false;
  2973. }
  2974. }
  2975. async #updateAuth() {
  2976. try {
  2977. const logStatus = scripts_echoLog({
  2978. text: i18n('updatingAuth', 'Twitter')
  2979. });
  2980. return await new Promise(resolve => {
  2981. GM_cookie.list({
  2982. url: 'https://x.com/settings/account'
  2983. }, async (cookies, error) => {
  2984. if (!error) {
  2985. const [ ct0, isLogin ] = cookies.map(cookie => [ 'ct0', 'twid' ].includes(cookie.name) ? cookie.value : null).filter(cookie => cookie);
  2986. if (isLogin && ct0) {
  2987. GM_setValue('twitterAuth', {
  2988. ct0: ct0
  2989. });
  2990. this.#auth = {
  2991. ct0: ct0
  2992. };
  2993. logStatus.success();
  2994. resolve(await this.#verifyAuth());
  2995. } else {
  2996. logStatus.error(i18n('needLogin'));
  2997. resolve(false);
  2998. }
  2999. } else {
  3000. logStatus.error('Error: Update twitter auth failed!');
  3001. resolve(false);
  3002. }
  3003. });
  3004. });
  3005. } catch (error) {
  3006. throwError(error, 'Twitter.updateToken');
  3007. return false;
  3008. }
  3009. }
  3010. async #toggleUser({
  3011. name,
  3012. doTask = true,
  3013. verify = false,
  3014. retry = false
  3015. }) {
  3016. try {
  3017. if (!doTask && !verify && this.whiteList.users.includes(name)) {
  3018. scripts_echoLog({
  3019. type: 'whiteList',
  3020. text: 'Twitter.unfollowUser',
  3021. id: name
  3022. });
  3023. return true;
  3024. }
  3025. const userId = verify ? this.#verifyId : await this.userName2id(name);
  3026. if (!userId) {
  3027. return false;
  3028. }
  3029. const logStatus = verify ? scripts_echoLog({
  3030. text: i18n('verifyingAuth', 'Twitter')
  3031. }) : scripts_echoLog({
  3032. type: `${doTask ? '' : 'un'}followingTwitterUser`,
  3033. text: name
  3034. });
  3035. const {
  3036. result,
  3037. statusText,
  3038. status,
  3039. data
  3040. } = await tools_httpRequest({
  3041. url: `https://x.com/i/api/1.1/friendships/${doTask ? 'create' : 'destroy'}.json`,
  3042. method: 'POST',
  3043. headers: {
  3044. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3045. 'Content-Type': 'application/x-www-form-urlencoded',
  3046. 'x-csrf-token': this.#auth.ct0,
  3047. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3048. 'X-Twitter-Active-User': 'yes'
  3049. },
  3050. responseType: 'json',
  3051. data: $.param({
  3052. include_profile_interstitial_type: 1,
  3053. include_blocking: 1,
  3054. include_blocked_by: 1,
  3055. include_followed_by: 1,
  3056. include_want_retweets: 1,
  3057. include_mute_edge: 1,
  3058. include_can_dm: 1,
  3059. include_can_media_tag: 1,
  3060. skip_status: 1,
  3061. id: userId
  3062. })
  3063. });
  3064. if (result === 'Success') {
  3065. if (data?.status === 200) {
  3066. logStatus.success();
  3067. if (doTask && !verify) {
  3068. this.tasks.users = unique([ ...this.tasks.users, name ]);
  3069. }
  3070. return true;
  3071. }
  3072. if (verify && data?.status === 403) {
  3073. if (data.response?.errors?.[0]?.code === 158) {
  3074. logStatus.success();
  3075. return true;
  3076. }
  3077. if (data.response?.errors?.[0]?.code === 353 && !retry && data.responseHeaders?.['set-cookie']) {
  3078. this.#auth.ct0 = data.responseHeaders['set-cookie']?.find(cookie => cookie.includes('ct0='))?.split(';')?.at(0)?.split('=')?.at(-1) || this.#auth.ct0;
  3079. logStatus.warning(i18n('retry'));
  3080. return this.#toggleUser({
  3081. name: name,
  3082. doTask: doTask,
  3083. verify: verify,
  3084. retry: true
  3085. });
  3086. }
  3087. }
  3088. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3089. return false;
  3090. }
  3091. logStatus.error(`${result}:${statusText}(${status})`);
  3092. return false;
  3093. } catch (error) {
  3094. throwError(error, 'Twitter.toggleUser');
  3095. return false;
  3096. }
  3097. }
  3098. async userName2id(name) {
  3099. try {
  3100. const logStatus = scripts_echoLog({
  3101. type: 'gettingTwitterUserId',
  3102. text: name
  3103. });
  3104. const userId = this.#cache[name];
  3105. if (userId) {
  3106. logStatus.success();
  3107. return userId;
  3108. }
  3109. const {
  3110. result,
  3111. statusText,
  3112. status,
  3113. data
  3114. } = await tools_httpRequest({
  3115. 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`,
  3116. method: 'GET',
  3117. headers: {
  3118. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3119. 'content-type': 'application/json',
  3120. referer: `https://x.com/${name}`,
  3121. 'x-csrf-token': this.#auth.ct0,
  3122. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3123. 'X-Twitter-Active-User': 'yes'
  3124. },
  3125. responseType: 'json'
  3126. });
  3127. if (result === 'Success') {
  3128. if (data?.status === 200) {
  3129. let response = data.response || (typeof data.responseText === 'object' ? data.responseText : null);
  3130. if (!response) {
  3131. try {
  3132. response = JSON.parse(data.responseText);
  3133. } catch (error) {
  3134. response = null;
  3135. }
  3136. }
  3137. const userId = String(response?.data?.user?.result?.rest_id);
  3138. if (userId) {
  3139. this.#setCache(name, userId);
  3140. logStatus.success();
  3141. return userId;
  3142. }
  3143. logStatus.error(`Error:${data.statusText}(${data.status})`);
  3144. return false;
  3145. }
  3146. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3147. return false;
  3148. }
  3149. logStatus.error(`${result}:${statusText}(${status})`);
  3150. return false;
  3151. } catch (error) {
  3152. throwError(error, 'Twitter.getUserId');
  3153. return false;
  3154. }
  3155. }
  3156. async #toggleRetweet({
  3157. retweetId,
  3158. doTask = true
  3159. }) {
  3160. try {
  3161. if (!doTask && this.whiteList.retweets.includes(retweetId)) {
  3162. scripts_echoLog({
  3163. type: 'whiteList',
  3164. text: 'Twitter.unretweet',
  3165. id: retweetId
  3166. });
  3167. return true;
  3168. }
  3169. const logStatus = scripts_echoLog({
  3170. type: `${doTask ? '' : 'un'}retweetting`,
  3171. text: retweetId
  3172. });
  3173. const {
  3174. result,
  3175. statusText,
  3176. status,
  3177. data
  3178. } = await tools_httpRequest({
  3179. url: `https://x.com/i/api/graphql/${doTask ? 'ojPdsZsimiJrUGLR1sjUtA/CreateRetweet' : 'iQtK4dl5hBmXewYZuEOKVw/DeleteRetweet'}`,
  3180. method: 'POST',
  3181. headers: {
  3182. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3183. 'Content-Type': 'application/json',
  3184. 'x-csrf-token': this.#auth.ct0,
  3185. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3186. 'X-Twitter-Active-User': 'yes'
  3187. },
  3188. data: `{"variables":{"tweet_id":"${retweetId}","dark_request":false},"queryId":"${doTask ? 'ojPdsZsimiJrUGLR1sjUtA' : 'iQtK4dl5hBmXewYZuEOKVw'}"}`,
  3189. responseType: 'json'
  3190. });
  3191. if (result === 'Success') {
  3192. if (data?.status === 200 || data?.status === 403 && data.response?.errors?.[0]?.code === 327) {
  3193. logStatus.success();
  3194. if (doTask) {
  3195. this.tasks.retweets = unique([ ...this.tasks.retweets, retweetId ]);
  3196. }
  3197. return true;
  3198. }
  3199. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3200. return false;
  3201. }
  3202. logStatus.error(`${result}:${statusText}(${status})`);
  3203. return false;
  3204. } catch (error) {
  3205. throwError(error, 'Twitter.toggleRetweet');
  3206. return false;
  3207. }
  3208. }
  3209. async toggle({
  3210. doTask = true,
  3211. userLinks = [],
  3212. retweetLinks = []
  3213. }) {
  3214. try {
  3215. if (!this.#initialized) {
  3216. scripts_echoLog({
  3217. text: i18n('needInit')
  3218. });
  3219. return false;
  3220. }
  3221. const prom = [];
  3222. if (doTask && !globalOptions.doTask.twitter.users || !doTask && !globalOptions.undoTask.twitter.users) {
  3223. scripts_echoLog({
  3224. type: 'globalOptionsSkip',
  3225. text: 'twitter.users'
  3226. });
  3227. } else {
  3228. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/x\.com\/(.+)/)?.[1] || link.match(/https:\/\/twitter\.com\/(.+)/)?.[1]);
  3229. if (realUsers.length > 0) {
  3230. for (const user of realUsers) {
  3231. prom.push(this.#toggleUser({
  3232. name: user,
  3233. doTask: doTask
  3234. }));
  3235. await delay(1e3);
  3236. }
  3237. }
  3238. }
  3239. if (doTask && !globalOptions.doTask.twitter.retweets || !doTask && !globalOptions.undoTask.twitter.retweets) {
  3240. scripts_echoLog({
  3241. type: 'globalOptionsSkip',
  3242. text: 'twitter.retweets'
  3243. });
  3244. } else {
  3245. const realRetweets = this.getRealParams('retweets', retweetLinks, doTask, link => link.match(/https:\/\/x\.com\/.*?\/status\/([\d]+)/)?.[1] || link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1]);
  3246. if (realRetweets.length > 0) {
  3247. for (const retweet of realRetweets) {
  3248. prom.push(this.#toggleRetweet({
  3249. retweetId: retweet,
  3250. doTask: doTask
  3251. }));
  3252. await delay(1e3);
  3253. }
  3254. }
  3255. }
  3256. return Promise.all(prom).then(() => true);
  3257. } catch (error) {
  3258. throwError(error, 'Twitter.toggle');
  3259. return false;
  3260. }
  3261. }
  3262. #setCache(name, id) {
  3263. try {
  3264. this.#cache[name] = id;
  3265. GM_setValue('twitterCache', this.#cache);
  3266. } catch (error) {
  3267. throwError(error, 'Twitter.setCache');
  3268. }
  3269. }
  3270. }
  3271. const social_Twitter = Twitter;
  3272. class Vk extends social_Social {
  3273. tasks;
  3274. whiteList;
  3275. #username = '';
  3276. #cache = GM_getValue('vkCache') || {};
  3277. #initialized = false;
  3278. constructor() {
  3279. super();
  3280. const defaultTasksTemplate = {
  3281. names: []
  3282. };
  3283. this.tasks = defaultTasksTemplate;
  3284. this.whiteList = {
  3285. ...defaultTasksTemplate,
  3286. ...GM_getValue('whiteList')?.vk || {}
  3287. };
  3288. }
  3289. async init() {
  3290. try {
  3291. if (this.#initialized) {
  3292. return true;
  3293. }
  3294. const isVerified = await this.#verifyAuth();
  3295. if (isVerified) {
  3296. scripts_echoLog({}).success(i18n('initSuccess', 'Vk'));
  3297. this.#initialized = true;
  3298. return true;
  3299. }
  3300. scripts_echoLog({}).error(i18n('initFailed', 'Vk'));
  3301. return false;
  3302. } catch (error) {
  3303. throwError(error, 'Vk.init');
  3304. return false;
  3305. }
  3306. }
  3307. async #verifyAuth() {
  3308. try {
  3309. const logStatus = scripts_echoLog({
  3310. text: i18n('verifyAuth', 'Vk')
  3311. });
  3312. const {
  3313. result,
  3314. statusText,
  3315. status,
  3316. data
  3317. } = await tools_httpRequest({
  3318. url: 'https://vk.com/im',
  3319. method: 'GET'
  3320. });
  3321. if (result === 'Success') {
  3322. if (data?.finalUrl.includes('vk.com/login')) {
  3323. logStatus.error(`Error:${i18n('loginVk')}`, true);
  3324. return false;
  3325. }
  3326. if (data?.status === 200) {
  3327. this.#username = data.responseText.match(/TopNavBtn__profileLink" href="\/(.*?)"/)?.[1] || '';
  3328. logStatus.success();
  3329. return true;
  3330. }
  3331. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3332. return false;
  3333. }
  3334. logStatus.error(`${result}:${statusText}(${status})`);
  3335. return false;
  3336. } catch (error) {
  3337. throwError(error, 'Vk.verifyAuth');
  3338. return false;
  3339. }
  3340. }
  3341. async #toggleGroup(name, dataParam, doTask = true) {
  3342. try {
  3343. const logStatus = scripts_echoLog({
  3344. type: doTask ? 'joiningVkGroup' : 'leavingVkGroup',
  3345. text: name
  3346. });
  3347. if (dataParam.groupAct === 'enter' && !doTask || dataParam.groupAct === 'leave' && doTask) {
  3348. logStatus.success();
  3349. return true;
  3350. }
  3351. const reqData = {
  3352. act: doTask ? 'enter' : 'leave',
  3353. al: 1,
  3354. gid: dataParam.groupId,
  3355. hash: dataParam.groupHash
  3356. };
  3357. if (doTask) {
  3358. reqData.context = '_';
  3359. }
  3360. const {
  3361. result,
  3362. statusText,
  3363. status,
  3364. data
  3365. } = await tools_httpRequest({
  3366. url: 'https://vk.com/al_groups.php',
  3367. method: 'POST',
  3368. headers: {
  3369. origin: 'https://vk.com',
  3370. referer: `https://vk.com/${name}`,
  3371. 'content-type': 'application/x-www-form-urlencoded'
  3372. },
  3373. data: $.param(reqData)
  3374. });
  3375. if (result === 'Success') {
  3376. if (data?.status === 200) {
  3377. logStatus.success();
  3378. if (doTask) {
  3379. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3380. }
  3381. return true;
  3382. }
  3383. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3384. return false;
  3385. }
  3386. logStatus.error(`${result}:${statusText}(${status})`);
  3387. return false;
  3388. } catch (error) {
  3389. throwError(error, 'Vk.toggleGroup');
  3390. return false;
  3391. }
  3392. }
  3393. async #togglePublic(name, dataParam, doTask = true) {
  3394. try {
  3395. const logStatus = scripts_echoLog({
  3396. type: doTask ? 'joiningVkPublic' : 'leavingVkPublic',
  3397. text: name
  3398. });
  3399. if (dataParam.publicJoined && doTask || !dataParam.publicJoined && !doTask) {
  3400. logStatus.success();
  3401. return true;
  3402. }
  3403. const {
  3404. result,
  3405. statusText,
  3406. status,
  3407. data
  3408. } = await tools_httpRequest({
  3409. url: 'https://vk.com/al_public.php',
  3410. method: 'POST',
  3411. headers: {
  3412. origin: 'https://vk.com',
  3413. referer: `https://vk.com/${name}`,
  3414. 'content-type': 'application/x-www-form-urlencoded'
  3415. },
  3416. data: $.param({
  3417. act: doTask ? 'a_enter' : 'a_leave',
  3418. al: 1,
  3419. pid: dataParam.publicPid,
  3420. hash: dataParam.publicHash
  3421. })
  3422. });
  3423. if (result === 'Success') {
  3424. if (data?.status === 200) {
  3425. logStatus.success();
  3426. if (doTask) {
  3427. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3428. }
  3429. return true;
  3430. }
  3431. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3432. return false;
  3433. }
  3434. logStatus.error(`${result}:${statusText}(${status})`);
  3435. return false;
  3436. } catch (error) {
  3437. throwError(error, 'Vk.togglePublic');
  3438. return false;
  3439. }
  3440. }
  3441. async #toggleLikeWall(name, dataParam, doTask = true) {
  3442. try {
  3443. const logStatus = scripts_echoLog({
  3444. type: doTask ? 'likingVkPublic' : 'unlikingVkPublic',
  3445. text: name
  3446. });
  3447. const postData = {
  3448. act: 'a_set_reaction',
  3449. al: 1,
  3450. event_subtype: 'post_modal',
  3451. from: 'wall_page',
  3452. hash: dataParam.hash,
  3453. object: dataParam.object,
  3454. track_code: dataParam.trackCode,
  3455. wall: 2
  3456. };
  3457. if (doTask) {
  3458. postData.reaction_id = 0;
  3459. }
  3460. const {
  3461. result: resultR,
  3462. statusText: statusTextR,
  3463. status: statusR,
  3464. data: dataR
  3465. } = await tools_httpRequest({
  3466. url: 'https://vk.com/like.php?act=a_set_reaction',
  3467. method: 'POST',
  3468. headers: {
  3469. origin: 'https://vk.com',
  3470. referer: `https://vk.com/${name}`,
  3471. 'content-type': 'application/x-www-form-urlencoded'
  3472. },
  3473. data: $.param(postData)
  3474. });
  3475. if (resultR === 'Success') {
  3476. if (dataR?.status === 200) {
  3477. if (dataR.response?.payload?.[1]?.[1]?.like_my === true) {
  3478. logStatus.success();
  3479. return true;
  3480. }
  3481. }
  3482. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  3483. return false;
  3484. }
  3485. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  3486. return false;
  3487. } catch (error) {
  3488. throwError(error, 'Vk.sendWall');
  3489. return false;
  3490. }
  3491. }
  3492. async #sendWall(name) {
  3493. try {
  3494. const logStatus = scripts_echoLog({
  3495. type: 'sendingVkWall',
  3496. text: name
  3497. });
  3498. const {
  3499. result,
  3500. statusText,
  3501. status,
  3502. data
  3503. } = await tools_httpRequest({
  3504. url: 'https://vk.com/like.php',
  3505. method: 'POST',
  3506. headers: {
  3507. origin: 'https://vk.com',
  3508. referer: `https://vk.com/${name}`,
  3509. 'content-type': 'application/x-www-form-urlencoded'
  3510. },
  3511. data: $.param({
  3512. act: 'publish_box',
  3513. al: 1,
  3514. object: name
  3515. })
  3516. });
  3517. if (result === 'Success') {
  3518. if (data?.status === 200) {
  3519. const hash = data.responseText.match(/shHash:[\s]*'(.*?)'/)?.[1];
  3520. if (hash) {
  3521. const {
  3522. result: resultR,
  3523. statusText: statusTextR,
  3524. status: statusR,
  3525. data: dataR
  3526. } = await tools_httpRequest({
  3527. url: 'https://vk.com/like.php',
  3528. method: 'POST',
  3529. headers: {
  3530. origin: 'https://vk.com',
  3531. referer: `https://vk.com/${name}`,
  3532. 'content-type': 'application/x-www-form-urlencoded'
  3533. },
  3534. data: $.param({
  3535. Message: '',
  3536. act: 'a_do_publish',
  3537. al: 1,
  3538. close_comments: 0,
  3539. friends_only: 0,
  3540. from: 'box',
  3541. hash: hash,
  3542. list: '',
  3543. mark_as_ads: 0,
  3544. mute_notifications: 0,
  3545. object: name,
  3546. ret_data: 1,
  3547. to: 0
  3548. })
  3549. });
  3550. if (resultR === 'Success') {
  3551. if (dataR?.status === 200) {
  3552. const jsonData = JSON.parse(dataR.responseText?.replace('\x3c!--', '') || '{}');
  3553. if (jsonData?.payload?.[1]?.[1]?.share_my === true) {
  3554. logStatus.success();
  3555. const postId = String(jsonData?.payload?.[1]?.[1]?.post_id);
  3556. const ownerId = String(jsonData?.payload?.[1]?.[1]?.owner_id);
  3557. if (postId && ownerId) {
  3558. this.#setCache(name, `${ownerId}_${postId}`);
  3559. }
  3560. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3561. return true;
  3562. }
  3563. }
  3564. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  3565. return false;
  3566. }
  3567. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  3568. return false;
  3569. }
  3570. logStatus.error('Error: Get "hash" failed');
  3571. return false;
  3572. }
  3573. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3574. return false;
  3575. }
  3576. logStatus.error(`${result}:${statusText}(${status})`);
  3577. return false;
  3578. } catch (error) {
  3579. throwError(error, 'Vk.sendWall');
  3580. return false;
  3581. }
  3582. }
  3583. async #deleteWall(name, dataParams) {
  3584. try {
  3585. const logStatus = scripts_echoLog({
  3586. type: 'deletingVkWall',
  3587. text: name
  3588. });
  3589. const {
  3590. result,
  3591. statusText,
  3592. status,
  3593. data
  3594. } = await tools_httpRequest({
  3595. url: 'https://vk.com/al_wall.php?act=delete',
  3596. method: 'POST',
  3597. headers: {
  3598. origin: 'https://vk.com',
  3599. referer: `https://vk.com/${this.#username}?w=wall${this.#cache[name]}%2Fall`,
  3600. 'content-type': 'application/x-www-form-urlencoded'
  3601. },
  3602. data: $.param({
  3603. act: 'delete',
  3604. al: 1,
  3605. confirm: 0,
  3606. from: 'wkview',
  3607. hash: dataParams.wallHash,
  3608. post: this.#cache[name]
  3609. })
  3610. });
  3611. if (result === 'Success') {
  3612. if (data?.status === 200) {
  3613. const jsonData = JSON.parse(data.responseText?.replace('\x3c!--', '') || '{}');
  3614. if (jsonData?.payload?.[1]?.[1]) {
  3615. logStatus.success();
  3616. return true;
  3617. }
  3618. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3619. return false;
  3620. }
  3621. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3622. return false;
  3623. }
  3624. logStatus.error(`${result}:${statusText}(${status})`);
  3625. return false;
  3626. } catch (error) {
  3627. throwError(error, 'Vk.deleteWall');
  3628. return false;
  3629. }
  3630. }
  3631. async #getId(name, doTask) {
  3632. try {
  3633. let url = `https://vk.com/${name}`;
  3634. if (/^wall-/.test(name)) {
  3635. if (doTask) {
  3636. return {
  3637. type: 'sendWall'
  3638. };
  3639. }
  3640. if (!this.#cache[name]) {
  3641. return {
  3642. type: 'unSupport'
  3643. };
  3644. }
  3645. url = `https://vk.com/${this.#username}?w=wall${this.#cache[name]}`;
  3646. }
  3647. const logStatus = scripts_echoLog({
  3648. type: 'gettingVkId',
  3649. text: name
  3650. });
  3651. const {
  3652. result,
  3653. statusText,
  3654. status,
  3655. data
  3656. } = await tools_httpRequest({
  3657. url: url,
  3658. method: 'GET'
  3659. });
  3660. if (result === 'Success') {
  3661. if (data?.status === 200) {
  3662. const [ , groupAct, groupId, , groupHash ] = data.responseText.match(/Groups.(enter|leave)\(.*?,.*?([\d]+?), (&#39;|')(.*?)(&#39;|')/) || [];
  3663. const publicHash = data.responseText.match(/"enterHash":"(.*?)"/)?.[1];
  3664. const publicPid = data.responseText.match(/"public_id":([\d]+?),/)?.[1];
  3665. const publicJoined = !data.responseText.includes('Public.subscribe');
  3666. if (groupAct && groupId && groupHash) {
  3667. logStatus.success();
  3668. return {
  3669. groupAct: groupAct,
  3670. groupId: groupId,
  3671. groupHash: groupHash,
  3672. type: 'group'
  3673. };
  3674. } else if (publicHash && publicPid) {
  3675. logStatus.success();
  3676. return {
  3677. publicHash: publicHash,
  3678. publicPid: publicPid,
  3679. publicJoined: publicJoined,
  3680. type: 'public'
  3681. };
  3682. } else if (name.includes('action=like')) {
  3683. const hash = data.responseText.match(/data-reaction-hash="(.*?)"/)?.[1];
  3684. const trackCode = data.responseText.match(/data-post-track-code="(.*?)"/)?.[1];
  3685. const object = name.match(/wall-[\w_]+/)?.[0];
  3686. if (hash && trackCode && object) {
  3687. logStatus.success();
  3688. return {
  3689. type: 'likeWall',
  3690. hash: hash,
  3691. trackCode: trackCode,
  3692. object: object
  3693. };
  3694. }
  3695. } else if (data.responseText.includes('wall.deletePost') && !doTask) {
  3696. const wallHash = data.responseText.match(/wall\.deletePost\(this, '.*?', '(.*?)'\)/)?.[1];
  3697. if (wallHash) {
  3698. logStatus.success();
  3699. return {
  3700. type: 'deleteWall',
  3701. wallHash: wallHash
  3702. };
  3703. }
  3704. } else if (name.includes('wall') && doTask) {
  3705. logStatus.success();
  3706. return {
  3707. type: 'sendWall'
  3708. };
  3709. }
  3710. logStatus.error('Error: Parameters not found!');
  3711. return false;
  3712. }
  3713. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3714. return false;
  3715. }
  3716. logStatus.error(`${result}:${statusText}(${status})`);
  3717. return false;
  3718. } catch (error) {
  3719. throwError(error, 'Vk.getId');
  3720. return false;
  3721. }
  3722. }
  3723. async #toggleVk({
  3724. name,
  3725. doTask = true
  3726. }) {
  3727. try {
  3728. if (!doTask && this.whiteList.names.includes(name)) {
  3729. scripts_echoLog({
  3730. type: 'whiteList',
  3731. text: 'Vk.undoTask',
  3732. id: name
  3733. });
  3734. return true;
  3735. }
  3736. const formatName = name.replace(/\/$/, '');
  3737. const data = await this.#getId(formatName, doTask);
  3738. if (!data) {
  3739. return false;
  3740. }
  3741. switch (data.type) {
  3742. case 'group':
  3743. return await this.#toggleGroup(formatName, data, doTask);
  3744.  
  3745. case 'public':
  3746. return await this.#togglePublic(formatName, data, doTask);
  3747.  
  3748. case 'likeWall':
  3749. return await this.#toggleLikeWall(formatName, data, doTask);
  3750.  
  3751. case 'sendWall':
  3752. return doTask ? await this.#sendWall(formatName) : true;
  3753.  
  3754. case 'deleteWall':
  3755. return doTask ? true : await this.#deleteWall(formatName, data);
  3756.  
  3757. default:
  3758. return false;
  3759. }
  3760. } catch (error) {
  3761. throwError(error, 'Vk.toggleVk');
  3762. return false;
  3763. }
  3764. }
  3765. async toggle({
  3766. doTask = true,
  3767. nameLinks = []
  3768. }) {
  3769. try {
  3770. if (!this.#initialized) {
  3771. scripts_echoLog({
  3772. text: i18n('needInit')
  3773. });
  3774. return false;
  3775. }
  3776. const prom = [];
  3777. if (doTask && !globalOptions.doTask.vk.names || !doTask && !globalOptions.undoTask.vk.names) {
  3778. scripts_echoLog({
  3779. type: 'globalOptionsSkip',
  3780. text: 'vk.names'
  3781. });
  3782. } else {
  3783. const realNames = this.getRealParams('names', nameLinks, doTask, link => link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1]);
  3784. if (realNames.length > 0) {
  3785. for (const name of realNames) {
  3786. prom.push(this.#toggleVk({
  3787. name: name,
  3788. doTask: doTask
  3789. }));
  3790. await delay(1e3);
  3791. }
  3792. }
  3793. }
  3794. return Promise.all(prom).then(() => true);
  3795. } catch (error) {
  3796. throwError(error, 'Vk.toggle');
  3797. return false;
  3798. }
  3799. }
  3800. #setCache(name, postId) {
  3801. try {
  3802. this.#cache[name] = postId;
  3803. GM_setValue('vkCache', this.#cache);
  3804. } catch (error) {
  3805. throwError(error, 'Vk.setCache');
  3806. }
  3807. }
  3808. }
  3809. const social_Vk = Vk;
  3810. const getInfo = async function(link, type) {
  3811. try {
  3812. const logStatus = scripts_echoLog({
  3813. text: i18n('gettingYtbToken')
  3814. });
  3815. const {
  3816. result,
  3817. statusText,
  3818. status,
  3819. data
  3820. } = await tools_httpRequest({
  3821. url: link,
  3822. method: 'GET'
  3823. });
  3824. if (result === 'Success') {
  3825. if (data?.status === 200) {
  3826. if (data.responseText.includes('accounts.google.com/ServiceLogin?service=youtube')) {
  3827. logStatus.error(`Error:${i18n('loginYtb')}`, true);
  3828. return {
  3829. needLogin: true
  3830. };
  3831. }
  3832. const apiKey = data.responseText.match(/"INNERTUBE_API_KEY":"(.*?)"/)?.[1];
  3833. const context = (data.responseText.match(/\(\{"INNERTUBE_CONTEXT":([\w\W]*?)\}\)/) || data.responseText.match(/"INNERTUBE_CONTEXT":([\w\W]*?\}),"INNERTUBE/))?.[1] || '{}';
  3834. const {
  3835. client,
  3836. request
  3837. } = JSON.parse(context);
  3838. if (apiKey && client && request) {
  3839. client.hl = 'en';
  3840. if (type === 'channel') {
  3841. const channelId = data.responseText.match(/"channelId":"(.+?)"/)?.[1];
  3842. if (channelId) {
  3843. logStatus.success();
  3844. return {
  3845. params: {
  3846. apiKey: apiKey,
  3847. client: client,
  3848. request: request,
  3849. channelId: channelId
  3850. }
  3851. };
  3852. }
  3853. logStatus.error('Error: Get "channelId" failed!');
  3854. return {};
  3855. } else if (type === 'likeVideo') {
  3856. const videoId = data.responseText.match(/<link rel="shortlinkUrl" href="https:\/\/youtu\.be\/(.*?)">/)?.[1];
  3857. const likeParams = data.responseText.match(/"likeParams":"(.*?)"/)?.[1];
  3858. if (videoId) {
  3859. logStatus.success();
  3860. return {
  3861. params: {
  3862. apiKey: apiKey,
  3863. client: client,
  3864. request: request,
  3865. videoId: videoId,
  3866. likeParams: likeParams
  3867. }
  3868. };
  3869. }
  3870. logStatus.error('Error: Get "videoId" failed!');
  3871. return {};
  3872. }
  3873. logStatus.error('Error: Unknown type');
  3874. return {};
  3875. }
  3876. logStatus.error('Error: Parameter "apiKey" not found!');
  3877. return {};
  3878. }
  3879. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3880. return {};
  3881. }
  3882. logStatus.error(`${result}:${statusText}(${status})`);
  3883. return {};
  3884. } catch (error) {
  3885. throwError(error, 'Youtube.getInfo');
  3886. return {};
  3887. }
  3888. };
  3889. class Youtube extends social_Social {
  3890. tasks;
  3891. whiteList;
  3892. #auth = GM_getValue('youtubeAuth') || {};
  3893. #initialized = false;
  3894. #verifyChannel = `https://www.youtube.com/channel/${globalOptions.other.youtubeVerifyChannel}`;
  3895. constructor() {
  3896. super();
  3897. const defaultTasksTemplate = {
  3898. channels: [],
  3899. likes: []
  3900. };
  3901. this.tasks = defaultTasksTemplate;
  3902. this.whiteList = {
  3903. ...defaultTasksTemplate,
  3904. ...GM_getValue('whiteList')?.youtube || {}
  3905. };
  3906. }
  3907. async init() {
  3908. try {
  3909. if (this.#initialized) {
  3910. return true;
  3911. }
  3912. if (!this.#auth.PAPISID) {
  3913. if (await this.#updateAuth()) {
  3914. this.#initialized = true;
  3915. return true;
  3916. }
  3917. return false;
  3918. }
  3919. const isVerified = await this.#verifyAuth();
  3920. if (isVerified) {
  3921. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  3922. this.#initialized = true;
  3923. return true;
  3924. }
  3925. GM_setValue('youtubeAuth', null);
  3926. if (await this.#updateAuth()) {
  3927. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  3928. this.#initialized = true;
  3929. return true;
  3930. }
  3931. scripts_echoLog({}).error(i18n('initFailed', 'Youtube'));
  3932. return false;
  3933. } catch (error) {
  3934. throwError(error, 'Youtube.init');
  3935. return false;
  3936. }
  3937. }
  3938. async #verifyAuth() {
  3939. try {
  3940. return await this.#toggleChannel({
  3941. link: this.#verifyChannel,
  3942. doTask: true,
  3943. verify: true
  3944. });
  3945. } catch (error) {
  3946. throwError(error, 'Youtube.verifyAuth');
  3947. return false;
  3948. }
  3949. }
  3950. async #updateAuth() {
  3951. try {
  3952. const logStatus = scripts_echoLog({
  3953. text: i18n('updatingAuth', 'Youtube')
  3954. });
  3955. return await new Promise(resolve => {
  3956. GM_cookie.list({
  3957. url: 'https://www.youtube.com/@YouTube'
  3958. }, async (cookies, error) => {
  3959. if (!error) {
  3960. const PAPISID = cookies.find(cookie => cookie.name === '__Secure-3PAPISID')?.value;
  3961. if (PAPISID) {
  3962. GM_setValue('youtubeAuth', {
  3963. PAPISID: PAPISID
  3964. });
  3965. this.#auth = {
  3966. PAPISID: PAPISID
  3967. };
  3968. logStatus.success();
  3969. resolve(await this.#verifyAuth());
  3970. } else {
  3971. logStatus.error(i18n('needLogin'));
  3972. resolve(false);
  3973. }
  3974. } else {
  3975. logStatus.error('Error: Update youtube auth failed!');
  3976. resolve(false);
  3977. }
  3978. });
  3979. });
  3980. } catch (error) {
  3981. throwError(error, 'Youtube.updateAuth');
  3982. return false;
  3983. }
  3984. }
  3985. #getInfo(link, type) {
  3986. return getInfo(link, type);
  3987. }
  3988. async #toggleChannel({
  3989. link,
  3990. doTask = true,
  3991. verify = false
  3992. }) {
  3993. try {
  3994. const {
  3995. params,
  3996. needLogin
  3997. } = await this.#getInfo(link, 'channel');
  3998. const {
  3999. apiKey,
  4000. client,
  4001. request,
  4002. channelId
  4003. } = params || {};
  4004. if (needLogin) {
  4005. scripts_echoLog({
  4006. html: i18n('loginYtb')
  4007. });
  4008. return false;
  4009. }
  4010. if (!(apiKey && client && request && channelId)) {
  4011. scripts_echoLog({
  4012. text: '"getYtbToken" failed'
  4013. });
  4014. return false;
  4015. }
  4016. if (!doTask && !verify && this.whiteList.channels.includes(channelId)) {
  4017. scripts_echoLog({
  4018. type: 'whiteList',
  4019. text: 'Youtube.unfollowChannel',
  4020. id: channelId
  4021. });
  4022. return true;
  4023. }
  4024. const logStatus = verify ? scripts_echoLog({
  4025. text: i18n('verifyingAuth', 'Youtube')
  4026. }) : scripts_echoLog({
  4027. type: doTask ? 'followingYtbChannel' : 'unfollowingYtbChannel',
  4028. text: channelId
  4029. });
  4030. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  4031. const {
  4032. result,
  4033. statusText,
  4034. status,
  4035. data
  4036. } = await tools_httpRequest({
  4037. url: `https://www.youtube.com/youtubei/v1/subscription/${doTask ? '' : 'un'}subscribe?key=${apiKey}&prettyPrint=false`,
  4038. method: 'POST',
  4039. headers: {
  4040. origin: 'https://www.youtube.com',
  4041. referer: `https://www.youtube.com/channel/${channelId}`,
  4042. 'content-type': 'application/json',
  4043. 'x-goog-authuser': '0',
  4044. 'x-goog-visitor-id': client?.visitorData,
  4045. 'x-origin': 'https://www.youtube.com',
  4046. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  4047. },
  4048. data: JSON.stringify({
  4049. context: {
  4050. client: client,
  4051. request: {
  4052. sessionId: request?.sessionId,
  4053. internalExperimentFlags: [],
  4054. consistencyTokenJars: []
  4055. },
  4056. user: {}
  4057. },
  4058. channelIds: [ channelId ],
  4059. params: doTask ? 'EgIIAhgA' : 'CgIIAhgA'
  4060. })
  4061. });
  4062. if (result === 'Success') {
  4063. if (data?.status === 200) {
  4064. if (doTask && (/"subscribed":true/.test(data.responseText) || data.responseText.includes('The subscription already exists')) || !doTask && /"subscribed":false/.test(data.responseText)) {
  4065. logStatus.success();
  4066. if (doTask && !verify) {
  4067. this.tasks.channels = unique([ ...this.tasks.channels, link ]);
  4068. }
  4069. return true;
  4070. }
  4071. if (verify && data.responseText.includes('You may not subscribe to yourself')) {
  4072. logStatus.success();
  4073. return true;
  4074. }
  4075. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4076. return false;
  4077. }
  4078. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4079. return false;
  4080. }
  4081. logStatus.error(`${result}:${statusText}(${status})`);
  4082. return false;
  4083. } catch (error) {
  4084. throwError(error, 'Youtube.toggleChannel');
  4085. return false;
  4086. }
  4087. }
  4088. async #toggleLikeVideo({
  4089. link,
  4090. doTask = true
  4091. }) {
  4092. try {
  4093. const {
  4094. params,
  4095. needLogin
  4096. } = await this.#getInfo(link, 'likeVideo');
  4097. const {
  4098. apiKey,
  4099. client,
  4100. request,
  4101. videoId,
  4102. likeParams
  4103. } = params || {};
  4104. if (needLogin) {
  4105. scripts_echoLog({
  4106. html: `${i18n('loginYtb')}`
  4107. });
  4108. return false;
  4109. }
  4110. if (!(apiKey && client && request && videoId && likeParams)) {
  4111. scripts_echoLog({
  4112. text: '"getYtbToken" failed'
  4113. });
  4114. return false;
  4115. }
  4116. if (!doTask && this.whiteList.likes.includes(videoId)) {
  4117. scripts_echoLog({
  4118. type: 'whiteList',
  4119. text: 'Youtube.unlikeVideo',
  4120. id: videoId
  4121. });
  4122. return true;
  4123. }
  4124. const logStatus = scripts_echoLog({
  4125. type: doTask ? 'likingYtbVideo' : 'unlikingYtbVideo',
  4126. text: videoId
  4127. });
  4128. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  4129. const likeVideoData = {
  4130. context: {
  4131. client: client,
  4132. request: {
  4133. sessionId: request.sessionId,
  4134. internalExperimentFlags: [],
  4135. consistencyTokenJars: []
  4136. },
  4137. user: {}
  4138. },
  4139. target: {
  4140. videoId: videoId
  4141. }
  4142. };
  4143. if (doTask) {
  4144. if (likeParams) {
  4145. likeVideoData.params = likeParams;
  4146. } else {
  4147. logStatus.error('Empty likeParams');
  4148. return false;
  4149. }
  4150. }
  4151. const {
  4152. result,
  4153. statusText,
  4154. status,
  4155. data
  4156. } = await tools_httpRequest({
  4157. url: `https://www.youtube.com/youtubei/v1/like/${doTask ? '' : 'remove'}like?key=${apiKey}`,
  4158. method: 'POST',
  4159. headers: {
  4160. origin: 'https://www.youtube.com',
  4161. referer: `https://www.youtube.com/watch?v=${videoId}`,
  4162. 'content-type': 'application/json',
  4163. 'x-goog-authuser': '0',
  4164. 'x-goog-visitor-id': client.visitorData,
  4165. 'x-origin': 'https://www.youtube.com',
  4166. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  4167. },
  4168. data: JSON.stringify(likeVideoData)
  4169. });
  4170. if (result === 'Success') {
  4171. if (data?.status === 200) {
  4172. if (doTask && data.responseText.includes('Added to Liked videos') || !doTask && (data.responseText.includes('Removed from Liked videos') || data.responseText.includes('Dislike removed'))) {
  4173. logStatus.success();
  4174. if (doTask) {
  4175. this.tasks.likes = unique([ ...this.tasks.likes, link ]);
  4176. }
  4177. return true;
  4178. }
  4179. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4180. return false;
  4181. }
  4182. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4183. return false;
  4184. }
  4185. logStatus.error(`${result}:${statusText}(${status})`);
  4186. return false;
  4187. } catch (error) {
  4188. throwError(error, 'Youtube.toggleLikeVideo');
  4189. return false;
  4190. }
  4191. }
  4192. async toggle({
  4193. doTask = true,
  4194. channelLinks = [],
  4195. videoLinks = []
  4196. }) {
  4197. try {
  4198. if (!this.#initialized) {
  4199. scripts_echoLog({
  4200. text: i18n('needInit')
  4201. });
  4202. return false;
  4203. }
  4204. const prom = [];
  4205. if (doTask && !globalOptions.doTask.youtube.channels || !doTask && !globalOptions.undoTask.youtube.channels) {
  4206. scripts_echoLog({
  4207. type: 'globalOptionsSkip',
  4208. text: 'youtube.channels'
  4209. });
  4210. } else {
  4211. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => {
  4212. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4213. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4214. }
  4215. return link;
  4216. });
  4217. if (realChannels.length > 0) {
  4218. for (const channel of realChannels) {
  4219. prom.push(this.#toggleChannel({
  4220. link: channel,
  4221. doTask: doTask
  4222. }));
  4223. await delay(1e3);
  4224. }
  4225. }
  4226. }
  4227. if (doTask && !globalOptions.doTask.youtube.likes || !doTask && !globalOptions.undoTask.youtube.likes) {
  4228. scripts_echoLog({
  4229. type: 'globalOptionsSkip',
  4230. text: 'youtube.likes'
  4231. });
  4232. } else {
  4233. const realLikes = this.getRealParams('likes', videoLinks, doTask, link => {
  4234. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4235. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4236. }
  4237. return link;
  4238. });
  4239. if (realLikes.length > 0) {
  4240. for (const video of realLikes) {
  4241. prom.push(this.#toggleLikeVideo({
  4242. link: video,
  4243. doTask: doTask
  4244. }));
  4245. await delay(1e3);
  4246. }
  4247. }
  4248. }
  4249. return Promise.all(prom).then(() => true);
  4250. } catch (error) {
  4251. throwError(error, 'Youtube.toggle');
  4252. return false;
  4253. }
  4254. }
  4255. }
  4256. class SteamASF {
  4257. #asfOptions;
  4258. #botName = 'asf';
  4259. #groupInfo;
  4260. async init() {
  4261. try {
  4262. const asfCommandsUrl = new URL('/Api/Command/', globalOptions.ASF.AsfIpcUrl);
  4263. this.#asfOptions = {
  4264. url: asfCommandsUrl.href,
  4265. method: 'POST',
  4266. responseType: 'json',
  4267. headers: {
  4268. accept: 'application/json',
  4269. 'Content-Type': 'application/json',
  4270. Host: asfCommandsUrl.host,
  4271. Origin: asfCommandsUrl.origin,
  4272. Referer: asfCommandsUrl.href,
  4273. Authentication: globalOptions.ASF.AsfIpcPassword
  4274. }
  4275. };
  4276. if (globalOptions.ASF.AsfBotname) {
  4277. this.#botName = globalOptions.ASF.AsfBotname;
  4278. }
  4279. const logStatus = scripts_echoLog({
  4280. text: i18n('initingASF')
  4281. });
  4282. const {
  4283. result,
  4284. statusText,
  4285. status,
  4286. data
  4287. } = await tools_httpRequest({
  4288. ...this.#asfOptions,
  4289. data: '{"Command":"!stats"}'
  4290. });
  4291. if (result === 'Success') {
  4292. if (data?.response?.Success === true && data.response.Message === 'OK' && data.response.Result) {
  4293. logStatus.success();
  4294. return true;
  4295. }
  4296. if (data?.response?.Result || data?.response?.Message) {
  4297. logStatus.error(data?.response?.Result || data.response.Message);
  4298. return false;
  4299. }
  4300. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4301. return false;
  4302. }
  4303. logStatus.error(`${result}:${statusText}(${status})`);
  4304. return false;
  4305. } catch (error) {
  4306. throwError(error, 'SteamASF.init');
  4307. return false;
  4308. }
  4309. }
  4310. async joinGroup(groupName) {
  4311. try {
  4312. const logStatus = scripts_echoLog({
  4313. type: 'joiningSteamGroup',
  4314. text: groupName
  4315. });
  4316. const {
  4317. result,
  4318. statusText,
  4319. status,
  4320. data
  4321. } = await tools_httpRequest({
  4322. ...this.#asfOptions,
  4323. data: JSON.stringify({
  4324. Command: `!JOINGROUP ${this.#botName} ${groupName}`
  4325. })
  4326. });
  4327. if (result === 'Success') {
  4328. if (data?.status === 200 && [ '已加入', '已申请', 'Joined', 'Applied', 'Присоединился', 'costs' ].find(text => data.response?.Result?.includes(text))) {
  4329. logStatus.success();
  4330. return true;
  4331. }
  4332. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4333. return false;
  4334. }
  4335. logStatus.error(`${result}:${statusText}(${status})`);
  4336. return false;
  4337. } catch (error) {
  4338. throwError(error, 'SteamASF.joinGroup');
  4339. return false;
  4340. }
  4341. }
  4342. async leaveGroup(groupName) {
  4343. try {
  4344. if (!this.#groupInfo) {
  4345. if (!await this.#getGroupId()) {
  4346. return false;
  4347. }
  4348. }
  4349. const groupId = await this.#groupInfo[groupName];
  4350. if (!groupId) {
  4351. return false;
  4352. }
  4353. const logStatus = scripts_echoLog({
  4354. type: 'leavingSteamGroup',
  4355. text: groupName
  4356. });
  4357. const {
  4358. result,
  4359. statusText,
  4360. status,
  4361. data
  4362. } = await tools_httpRequest({
  4363. ...this.#asfOptions,
  4364. data: JSON.stringify({
  4365. Command: `!LEAVEGROUP ${this.#botName} ${groupId}`
  4366. })
  4367. });
  4368. if (result === 'Success') {
  4369. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4370. logStatus.success();
  4371. return true;
  4372. }
  4373. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4374. return false;
  4375. }
  4376. logStatus.error(`${result}:${statusText}(${status})`);
  4377. return false;
  4378. } catch (error) {
  4379. throwError(error, 'SteamASF.leaveGroup');
  4380. return false;
  4381. }
  4382. }
  4383. async #getGroupId() {
  4384. try {
  4385. const logStatus = scripts_echoLog({
  4386. type: 'gettingSteamGroupId',
  4387. text: 'All'
  4388. });
  4389. const {
  4390. result,
  4391. statusText,
  4392. status,
  4393. data
  4394. } = await tools_httpRequest({
  4395. ...this.#asfOptions,
  4396. data: JSON.stringify({
  4397. Command: `!GROUPLIST ${this.#botName}`
  4398. })
  4399. });
  4400. if (result === 'Success') {
  4401. if (data?.status === 200 && data.response?.Result?.includes('|')) {
  4402. this.#groupInfo = Object.fromEntries(data.response.Result.split('\n').map(line => {
  4403. const [ , name, id ] = line.trim().split('|');
  4404. if (name && id) {
  4405. return [ name, id ];
  4406. }
  4407. return null;
  4408. }).filter(ele => ele));
  4409. logStatus.success();
  4410. return true;
  4411. }
  4412. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4413. return false;
  4414. }
  4415. logStatus.error(`${result}:${statusText}(${status})`);
  4416. return false;
  4417. } catch (error) {
  4418. throwError(error, 'SteamASF.getGroupID');
  4419. return false;
  4420. }
  4421. }
  4422. async addToWishlist(gameId) {
  4423. try {
  4424. const logStatus = scripts_echoLog({
  4425. type: 'addingToWishlist',
  4426. text: gameId
  4427. });
  4428. if ((await this.#checkGame(gameId)).wishlist === true) {
  4429. logStatus.success();
  4430. return true;
  4431. }
  4432. const {
  4433. result,
  4434. statusText,
  4435. status,
  4436. data
  4437. } = await tools_httpRequest({
  4438. ...this.#asfOptions,
  4439. data: JSON.stringify({
  4440. Command: `!ADDWISHLIST ${this.#botName} ${gameId}`
  4441. })
  4442. });
  4443. if (result === 'Success') {
  4444. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4445. logStatus.success();
  4446. return true;
  4447. }
  4448. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4449. return false;
  4450. }
  4451. logStatus.error(`${result}:${statusText}(${status})`);
  4452. return false;
  4453. } catch (error) {
  4454. throwError(error, 'SteamASF.addToWishlist');
  4455. return false;
  4456. }
  4457. }
  4458. async removeFromWishlist(gameId) {
  4459. try {
  4460. const logStatus = scripts_echoLog({
  4461. type: 'removingFromWishlist',
  4462. text: gameId
  4463. });
  4464. if ((await this.#checkGame(gameId)).wishlist === false) {
  4465. logStatus.success();
  4466. return true;
  4467. }
  4468. const {
  4469. result,
  4470. statusText,
  4471. status,
  4472. data
  4473. } = await tools_httpRequest({
  4474. ...this.#asfOptions,
  4475. data: JSON.stringify({
  4476. Command: `!REMOVEWISHLIST ${this.#botName} ${gameId}`
  4477. })
  4478. });
  4479. if (result === 'Success') {
  4480. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4481. logStatus.success();
  4482. return true;
  4483. }
  4484. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4485. return false;
  4486. }
  4487. logStatus.error(`${result}:${statusText}(${status})`);
  4488. return false;
  4489. } catch (error) {
  4490. throwError(error, 'SteamASF.removeFromWishlist');
  4491. return false;
  4492. }
  4493. }
  4494. async toggleFollowGame(gameId, doTask) {
  4495. try {
  4496. const logStatus = scripts_echoLog({
  4497. type: `${doTask ? '' : 'un'}followingGame`,
  4498. text: gameId
  4499. });
  4500. if (doTask && (await this.#checkGame(gameId)).followed === true || !doTask && (await this.#checkGame(gameId)).followed === false) {
  4501. logStatus.success();
  4502. return true;
  4503. }
  4504. const {
  4505. result,
  4506. statusText,
  4507. status,
  4508. data
  4509. } = await tools_httpRequest({
  4510. ...this.#asfOptions,
  4511. data: JSON.stringify({
  4512. Command: `!${doTask ? '' : 'UN'}FOLLOWGAME ${this.#botName} ${gameId}`
  4513. })
  4514. });
  4515. if (result === 'Success') {
  4516. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4517. logStatus.success();
  4518. return true;
  4519. }
  4520. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4521. return false;
  4522. }
  4523. logStatus.error(`${result}:${statusText}(${status})`);
  4524. return false;
  4525. } catch (error) {
  4526. throwError(error, 'SteamASF.toggleFollowGame');
  4527. return false;
  4528. }
  4529. }
  4530. async #checkGame(gameId) {
  4531. try {
  4532. const {
  4533. result,
  4534. data
  4535. } = await tools_httpRequest({
  4536. ...this.#asfOptions,
  4537. data: JSON.stringify({
  4538. Command: `!CHECK ${this.#botName} ${gameId}`
  4539. })
  4540. });
  4541. if (result === 'Success') {
  4542. if (data?.status === 200 && data.response?.Result?.includes(gameId)) {
  4543. const matchedResult = data.response.Result.split('\n').find(result => result.includes(gameId))?.split('|');
  4544. if (matchedResult?.length > 3) {
  4545. return {
  4546. wishlist: matchedResult.at(-3).trim() === '√' || matchedResult.at(-2).trim() === '√',
  4547. followed: matchedResult.at(-1).trim() === '√'
  4548. };
  4549. }
  4550. return {};
  4551. }
  4552. return {};
  4553. }
  4554. return {};
  4555. } catch (error) {
  4556. throwError(error, 'SteamASF.checkGame');
  4557. return {};
  4558. }
  4559. }
  4560. async toggleCurator(curatorId, doTask = true) {
  4561. try {
  4562. const logStatus = scripts_echoLog({
  4563. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  4564. text: curatorId
  4565. });
  4566. const {
  4567. result,
  4568. statusText,
  4569. status,
  4570. data
  4571. } = await tools_httpRequest({
  4572. ...this.#asfOptions,
  4573. data: JSON.stringify({
  4574. Command: `!${doTask ? '' : 'UN'}FOLLOWCURATOR ${this.#botName} ${curatorId}`
  4575. })
  4576. });
  4577. if (result === 'Success') {
  4578. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4579. logStatus.success();
  4580. return true;
  4581. }
  4582. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4583. return false;
  4584. }
  4585. logStatus.error(`${result}:${statusText}(${status})`);
  4586. return false;
  4587. } catch (error) {
  4588. throwError(error, 'Steam.toggleCurator');
  4589. return false;
  4590. }
  4591. }
  4592. async addLicense(id) {
  4593. try {
  4594. const [ type, ids ] = id.split('-');
  4595. if (type === 'appid') {
  4596. const logStatus = scripts_echoLog({
  4597. type: 'addingFreeLicense',
  4598. text: ids
  4599. });
  4600. const {
  4601. result,
  4602. statusText,
  4603. status,
  4604. data
  4605. } = await tools_httpRequest({
  4606. ...this.#asfOptions,
  4607. data: JSON.stringify({
  4608. Command: `!addlicense ${this.#botName} app/${ids}`
  4609. })
  4610. });
  4611. if (result === 'Success') {
  4612. if (data?.status === 200 && [ 'AlreadyPurchased', 'OK' ].find(text => data.response?.Result?.includes(text))) {
  4613. logStatus.success();
  4614. return true;
  4615. }
  4616. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4617. return false;
  4618. }
  4619. logStatus.error(`${result}:${statusText}(${status})`);
  4620. return false;
  4621. } else if (type === 'subid') {
  4622. const idsArr = ids.split(',');
  4623. const logStatus = scripts_echoLog({
  4624. type: 'addingFreeLicenseSubid',
  4625. text: ids
  4626. });
  4627. const {
  4628. result,
  4629. statusText,
  4630. status,
  4631. data
  4632. } = await tools_httpRequest({
  4633. ...this.#asfOptions,
  4634. data: JSON.stringify({
  4635. Command: `!addlicense ${this.#botName} ${idsArr.map(id => `sub/${id}`).join(',')}`
  4636. })
  4637. });
  4638. if (result === 'Success') {
  4639. if (data?.status === 200 && data.response?.Result) {
  4640. const resultLines = data.response.Result.split('\n');
  4641. idsArr.forEach(subid => {
  4642. const targetLine = resultLines.find(text => text.includes(subid));
  4643. if (targetLine && [ '成功', 'Success', 'Успех' ].find(text => targetLine.includes(text))) {
  4644. scripts_echoLog({}).success(targetLine);
  4645. } else {
  4646. scripts_echoLog({}).error(targetLine);
  4647. }
  4648. });
  4649. return true;
  4650. }
  4651. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4652. return false;
  4653. }
  4654. logStatus.error(`${result}:${statusText}(${status})`);
  4655. return false;
  4656. }
  4657. return false;
  4658. } catch (error) {
  4659. throwError(error, 'SteamASF.addLicense');
  4660. return false;
  4661. }
  4662. }
  4663. async requestPlayTestAccess(id) {
  4664. try {
  4665. const logStatus = scripts_echoLog({
  4666. type: 'requestingPlayTestAccess',
  4667. text: id
  4668. });
  4669. const {
  4670. result,
  4671. statusText,
  4672. status,
  4673. data
  4674. } = await tools_httpRequest({
  4675. ...this.#asfOptions,
  4676. data: JSON.stringify({
  4677. Command: `!REQUESTACCESS ${this.#botName} ${id}`
  4678. })
  4679. });
  4680. if (result === 'Success') {
  4681. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4682. logStatus.success();
  4683. return true;
  4684. }
  4685. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4686. return false;
  4687. }
  4688. logStatus.error(`${result}:${statusText}(${status})`);
  4689. return false;
  4690. } catch (error) {
  4691. throwError(error, 'Steam.requestPlayTestAccess');
  4692. return false;
  4693. }
  4694. }
  4695. }
  4696. const social_SteamASF = SteamASF;
  4697. class Steam extends social_Social {
  4698. tasks;
  4699. whiteList;
  4700. #cache = {
  4701. ...{
  4702. group: {},
  4703. officialGroup: {},
  4704. forum: {},
  4705. workshop: {},
  4706. curator: {}
  4707. },
  4708. ...GM_getValue('steamCache')
  4709. };
  4710. #auth = {};
  4711. #storeInitialized = false;
  4712. #communityInitialized = false;
  4713. #area = 'CN';
  4714. #oldArea;
  4715. #areaStatus = 'end';
  4716. #ASF;
  4717. constructor() {
  4718. super();
  4719. const defaultTasksTemplate = {
  4720. groups: [],
  4721. officialGroups: [],
  4722. wishlists: [],
  4723. follows: [],
  4724. forums: [],
  4725. workshops: [],
  4726. workshopVotes: [],
  4727. curators: [],
  4728. curatorLikes: [],
  4729. announcements: [],
  4730. licenses: [],
  4731. playtests: []
  4732. };
  4733. this.tasks = defaultTasksTemplate;
  4734. this.whiteList = {
  4735. ...defaultTasksTemplate,
  4736. ...GM_getValue('whiteList')?.steam || {}
  4737. };
  4738. }
  4739. async init(type = 'all') {
  4740. try {
  4741. if (globalOptions.ASF.AsfEnabled && globalOptions.ASF.AsfIpcUrl && globalOptions.ASF.AsfIpcPassword) {
  4742. this.#ASF = new social_SteamASF();
  4743. if (await this.#ASF.init()) {
  4744. this.#storeInitialized = true;
  4745. this.#communityInitialized = true;
  4746. return true;
  4747. }
  4748. return false;
  4749. }
  4750. if (type === 'store') {
  4751. if (this.#storeInitialized) {
  4752. return true;
  4753. }
  4754. let storeInitialized = await this.#updateStoreAuth();
  4755. if (!storeInitialized) {
  4756. storeInitialized = await this.#updateStoreAuthTab();
  4757. }
  4758. this.#storeInitialized = storeInitialized;
  4759. if (!this.#storeInitialized) {
  4760. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4761. return false;
  4762. }
  4763. scripts_echoLog({}).success(i18n('initSuccess', 'SteamStore'));
  4764. return true;
  4765. }
  4766. if (type === 'community') {
  4767. if (this.#communityInitialized) {
  4768. return true;
  4769. }
  4770. let communityInitialized = await this.#updateCommunityAuth();
  4771. if (!communityInitialized) {
  4772. communityInitialized = await this.#updateCommunityAuthTab();
  4773. GM_setValue('steamCommunityAuth', null);
  4774. }
  4775. this.#communityInitialized = communityInitialized;
  4776. if (!this.#communityInitialized) {
  4777. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4778. return false;
  4779. }
  4780. scripts_echoLog({}).success(i18n('initSuccess', 'SteamCommunity'));
  4781. return true;
  4782. }
  4783. if (this.#storeInitialized && this.#communityInitialized) {
  4784. scripts_echoLog({}).success(i18n('initSuccess', 'Steam'));
  4785. return true;
  4786. }
  4787. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4788. return false;
  4789. } catch (error) {
  4790. throwError(error, 'Steam.init');
  4791. return false;
  4792. }
  4793. }
  4794. async #refreshToken(type = 'steamStore') {
  4795. try {
  4796. const host = {
  4797. steamStore: 'store.steampowered.com',
  4798. steamCommunity: 'steamcommunity.com'
  4799. };
  4800. const logStatus = scripts_echoLog({
  4801. text: i18n('refreshingToken', i18n(type))
  4802. });
  4803. const formData = new FormData();
  4804. formData.append('redir', `https://${host[type]}/`);
  4805. const {
  4806. result,
  4807. statusText,
  4808. status,
  4809. data
  4810. } = await tools_httpRequest({
  4811. url: 'https://login.steampowered.com/jwt/ajaxrefresh',
  4812. method: 'POST',
  4813. responseType: 'json',
  4814. headers: {
  4815. Host: 'login.steampowered.com',
  4816. Origin: `https://${host[type]}`,
  4817. Referer: `https://${host[type]}/`
  4818. },
  4819. data: formData
  4820. });
  4821. if (result === 'Success') {
  4822. if (data?.response?.success) {
  4823. if (await this.#setStoreToken(data.response, type)) {
  4824. logStatus.success();
  4825. return true;
  4826. }
  4827. logStatus.error('Error');
  4828. return false;
  4829. }
  4830. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4831. return false;
  4832. }
  4833. logStatus.error(`${result}:${statusText}(${status})`);
  4834. return false;
  4835. } catch (error) {
  4836. throwError(error, 'Steam.refreshToken');
  4837. return false;
  4838. }
  4839. }
  4840. async #setStoreToken(param, type) {
  4841. try {
  4842. const host = {
  4843. steamStore: 'store.steampowered.com',
  4844. steamCommunity: 'steamcommunity.com'
  4845. };
  4846. const logStatus = scripts_echoLog({
  4847. text: i18n('settingToken', i18n(type))
  4848. });
  4849. const formData = new FormData();
  4850. formData.append('steamID', param.steamID);
  4851. formData.append('nonce', param.nonce);
  4852. formData.append('redir', param.redir);
  4853. formData.append('auth', param.auth);
  4854. const {
  4855. result,
  4856. statusText,
  4857. status,
  4858. data
  4859. } = await tools_httpRequest({
  4860. url: `https://${host[type]}/login/settoken`,
  4861. method: 'POST',
  4862. headers: {
  4863. Accept: 'application/json, text/plain, */*',
  4864. Host: host[type],
  4865. Origin: `https://${host[type]}`
  4866. },
  4867. data: formData
  4868. });
  4869. if (result === 'Success') {
  4870. if (data?.status === 200) {
  4871. logStatus.success();
  4872. return true;
  4873. }
  4874. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4875. return false;
  4876. }
  4877. logStatus.error(`${result}:${statusText}(${status})`);
  4878. return false;
  4879. } catch (error) {
  4880. throwError(error, 'Steam.setStoreToken');
  4881. return false;
  4882. }
  4883. }
  4884. async #updateStoreAuth(retry = false) {
  4885. try {
  4886. const logStatus = scripts_echoLog({
  4887. text: i18n('updatingAuth', i18n('steamStore'))
  4888. });
  4889. const {
  4890. result,
  4891. statusText,
  4892. status,
  4893. data
  4894. } = await tools_httpRequest({
  4895. url: 'https://store.steampowered.com/',
  4896. method: 'GET',
  4897. headers: {
  4898. 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',
  4899. 'Sec-Fetch-Dest': 'document',
  4900. 'Sec-Fetch-Mode': 'navigate',
  4901. 'Upgrade-Insecure-Requests': '1'
  4902. },
  4903. fetch: false,
  4904. redirect: 'manual'
  4905. });
  4906. if (data?.status === 200) {
  4907. if (!data.responseText.includes('data-miniprofile=')) {
  4908. if (await this.#refreshToken('steamStore')) {
  4909. logStatus.warning(i18n('retry'));
  4910. if (retry) {
  4911. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4912. return false;
  4913. }
  4914. return this.#updateStoreAuth(true);
  4915. }
  4916. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4917. return false;
  4918. }
  4919. const storeSessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  4920. if (storeSessionID) {
  4921. this.#auth.storeSessionID = storeSessionID;
  4922. logStatus.success();
  4923. return true;
  4924. }
  4925. logStatus.error('Error: Get "sessionID" failed');
  4926. return false;
  4927. }
  4928. if ([ 301, 302 ].includes(data?.status)) {
  4929. if (await this.#refreshToken('steamStore')) {
  4930. logStatus.warning(i18n('retry'));
  4931. if (retry) {
  4932. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4933. return false;
  4934. }
  4935. return this.#updateStoreAuth(true);
  4936. }
  4937. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4938. return false;
  4939. }
  4940. logStatus.error(`${result}:${statusText}(${status})`);
  4941. return false;
  4942. } catch (error) {
  4943. throwError(error, 'Steam.updateStoreAuth');
  4944. return false;
  4945. }
  4946. }
  4947. async #updateStoreAuthTab() {
  4948. try {
  4949. const logStatus = scripts_echoLog({
  4950. text: i18n('updatingAuth', i18n('steamStoreTab'))
  4951. });
  4952. return await new Promise(resolve => {
  4953. GM_deleteValue('steamStoreAuth');
  4954. GM_setValue('ATv4_updateStoreAuth', true);
  4955. const newTab = GM_openInTab('https://store.steampowered.com/', {
  4956. active: true,
  4957. setParent: true
  4958. });
  4959. newTab.name = 'ATv4_updateStoreAuth';
  4960. const listenerId = GM_addValueChangeListener('steamStoreAuth', (key, oldValue, newValue) => {
  4961. GM_removeValueChangeListener(listenerId);
  4962. GM_deleteValue('ATv4_updateStoreAuth');
  4963. newTab?.close();
  4964. window.focus();
  4965. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  4966. this.#auth.storeSessionID = newValue.storeSessionID;
  4967. logStatus.success();
  4968. resolve(true);
  4969. return;
  4970. }
  4971. logStatus.error('Failed');
  4972. resolve(false);
  4973. });
  4974. newTab.onclose = () => {
  4975. GM_deleteValue('ATv4_updateStoreAuth');
  4976. };
  4977. });
  4978. } catch (error) {
  4979. throwError(error, 'Steam.updateStoreAuthTab');
  4980. return false;
  4981. }
  4982. }
  4983. async #updateCommunityAuthTab() {
  4984. try {
  4985. const logStatus = scripts_echoLog({
  4986. text: i18n('updatingAuth', i18n('steamCommunityTab'))
  4987. });
  4988. return await new Promise(resolve => {
  4989. GM_deleteValue('steamCommunityAuth');
  4990. GM_setValue('ATv4_updateCommunityAuth', true);
  4991. const newTab = GM_openInTab('https://steamcommunity.com/my', {
  4992. active: true,
  4993. setParent: true
  4994. });
  4995. newTab.name = 'ATv4_updateCommunityAuth';
  4996. const listenerId = GM_addValueChangeListener('steamCommunityAuth', (key, oldValue, newValue) => {
  4997. GM_removeValueChangeListener(listenerId);
  4998. GM_deleteValue('ATv4_updateCommunityAuth');
  4999. newTab?.close();
  5000. window.focus();
  5001. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  5002. this.#auth.steam64Id = newValue.steam64Id;
  5003. this.#auth.communitySessionID = newValue.communitySessionID;
  5004. logStatus.success();
  5005. resolve(true);
  5006. return;
  5007. }
  5008. logStatus.error('Failed');
  5009. resolve(false);
  5010. });
  5011. newTab.onclose = () => {
  5012. GM_deleteValue('ATv4_updateCommunityAuth');
  5013. };
  5014. });
  5015. } catch (error) {
  5016. throwError(error, 'Steam.updateCommunityAuthTab');
  5017. return false;
  5018. }
  5019. }
  5020. async #updateCommunityAuth() {
  5021. try {
  5022. const logStatus = scripts_echoLog({
  5023. text: i18n('gettingUserLink')
  5024. });
  5025. const {
  5026. result,
  5027. statusText,
  5028. status,
  5029. data
  5030. } = await tools_httpRequest({
  5031. url: 'https://steamcommunity.com/my',
  5032. method: 'GET',
  5033. headers: {
  5034. 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',
  5035. Host: 'steamcommunity.com',
  5036. 'Sec-Fetch-Dest': 'document',
  5037. 'Sec-Fetch-Mode': 'navigate'
  5038. },
  5039. fetch: false
  5040. });
  5041. if (data?.status === 200) {
  5042. if (data.finalUrl.includes('https://steamcommunity.com/login/home')) {
  5043. logStatus.error(`Error:${i18n('needLoginSteamCommunity')}`, true);
  5044. return false;
  5045. }
  5046. const steam64Id = data.responseText.match(/g_steamID = "(.+?)";/)?.[1];
  5047. const communitySessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  5048. if (steam64Id && communitySessionID) {
  5049. this.#auth.steam64Id = steam64Id;
  5050. this.#auth.communitySessionID = communitySessionID;
  5051. logStatus.success();
  5052. return true;
  5053. }
  5054. logStatus.error('Error: Get "sessionID" failed');
  5055. return false;
  5056. }
  5057. logStatus.error(`${result}:${statusText}(${status})`);
  5058. return false;
  5059. } catch (error) {
  5060. throwError(error, 'Steam.updateCommunityAuth');
  5061. return false;
  5062. }
  5063. }
  5064. async #getAreaInfo() {
  5065. try {
  5066. const logStatus = scripts_echoLog({
  5067. text: i18n('gettingAreaInfo')
  5068. });
  5069. const {
  5070. result,
  5071. statusText,
  5072. status,
  5073. data
  5074. } = await tools_httpRequest({
  5075. url: 'https://store.steampowered.com/cart/',
  5076. method: 'GET'
  5077. });
  5078. if (result === 'Success') {
  5079. if (data?.status === 200) {
  5080. const cartConfigRaw = data.responseText.match(/data-cart_config="(.*?)"/)?.[1];
  5081. const temp = document.createElement('div');
  5082. temp.innerHTML = cartConfigRaw || '{}';
  5083. const cartConfigStr = temp.textContent || temp.innerText;
  5084. let cartConfig;
  5085. try {
  5086. cartConfig = JSON.parse(cartConfigStr);
  5087. } catch (error) {
  5088. logStatus.error('Error: get country info filed');
  5089. console.error(error);
  5090. return {};
  5091. }
  5092. if (!cartConfig.rgUserCountryOptions) {
  5093. logStatus.warning('Warning: Area cannot be changed');
  5094. return {};
  5095. }
  5096. const userInfoRaw = data.responseText.match(/data-userinfo="(.*?)"/)?.[1];
  5097. const temp1 = document.createElement('div');
  5098. temp1.innerHTML = userInfoRaw || '{}';
  5099. const userInfoStr = temp1.textContent || temp1.innerText;
  5100. let userInfo;
  5101. try {
  5102. userInfo = JSON.parse(userInfoStr);
  5103. } catch (error) {
  5104. logStatus.error('Error: get country info filed');
  5105. console.error(error);
  5106. return {};
  5107. }
  5108. const currentArea = userInfo.country_code;
  5109. const areas = Object.keys(cartConfig.rgUserCountryOptions).filter(area => area !== 'help');
  5110. if (currentArea && areas.length > 0) {
  5111. this.#area = currentArea;
  5112. logStatus.success();
  5113. return {
  5114. currentArea: currentArea,
  5115. areas: areas
  5116. };
  5117. }
  5118. logStatus.error('Error: get country info filed');
  5119. return {};
  5120. }
  5121. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5122. return {};
  5123. }
  5124. logStatus.error(`${result}:${statusText}(${status})`);
  5125. return {};
  5126. } catch (error) {
  5127. throwError(error, 'Steam.getAreaInfo');
  5128. return {};
  5129. }
  5130. }
  5131. async #changeArea(area) {
  5132. try {
  5133. if (this.#areaStatus === 'waiting') {
  5134. await new Promise(resolve => {
  5135. const checker = setInterval(() => {
  5136. if (this.#areaStatus !== 'waiting') {
  5137. clearInterval(checker);
  5138. resolve(true);
  5139. }
  5140. });
  5141. });
  5142. }
  5143. if (this.#area === area || !area && this.#area !== 'CN') {
  5144. return true;
  5145. }
  5146. this.#areaStatus = 'waiting';
  5147. let aimedArea = area;
  5148. if (!aimedArea) {
  5149. const {
  5150. currentArea,
  5151. areas
  5152. } = await this.#getAreaInfo();
  5153. if (!currentArea || !areas) {
  5154. this.#areaStatus = 'error';
  5155. return false;
  5156. }
  5157. if (currentArea !== 'CN') {
  5158. this.#areaStatus = 'skip';
  5159. scripts_echoLog({
  5160. text: 'notNeededChangeArea'
  5161. });
  5162. return 'skip';
  5163. }
  5164. const anotherArea = areas.filter(area => area && area !== 'CN');
  5165. if (!anotherArea || anotherArea.length === 0) {
  5166. this.#areaStatus = 'noAnotherArea';
  5167. scripts_echoLog({
  5168. text: 'noAnotherArea'
  5169. });
  5170. return false;
  5171. }
  5172. [ aimedArea ] = anotherArea;
  5173. }
  5174. const logStatus = scripts_echoLog({
  5175. text: i18n('changingArea', aimedArea)
  5176. });
  5177. const {
  5178. result,
  5179. statusText,
  5180. status,
  5181. data
  5182. } = await tools_httpRequest({
  5183. url: 'https://store.steampowered.com/country/setcountry',
  5184. method: 'POST',
  5185. headers: {
  5186. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5187. },
  5188. data: $.param({
  5189. cc: aimedArea,
  5190. sessionid: this.#auth.storeSessionID
  5191. })
  5192. });
  5193. if (result === 'Success') {
  5194. if (data?.status === 200 && data.responseText === 'true') {
  5195. const {
  5196. currentArea
  5197. } = await this.#getAreaInfo();
  5198. if (currentArea) {
  5199. this.#area = currentArea;
  5200. if (!this.#oldArea) {
  5201. this.#oldArea = currentArea;
  5202. }
  5203. }
  5204. if (currentArea === aimedArea) {
  5205. this.#areaStatus = 'success';
  5206. logStatus.success();
  5207. return currentArea;
  5208. }
  5209. this.#areaStatus = 'error';
  5210. logStatus.error('Error: change country filed');
  5211. return 'CN';
  5212. }
  5213. this.#areaStatus = 'error';
  5214. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5215. return 'CN';
  5216. }
  5217. this.#areaStatus = 'error';
  5218. logStatus.error(`${result}:${statusText}(${status})`);
  5219. return 'CN';
  5220. } catch (error) {
  5221. this.#areaStatus = 'error';
  5222. throwError(error, 'Steam.changeArea');
  5223. return false;
  5224. }
  5225. }
  5226. async #joinGroup(groupName) {
  5227. try {
  5228. if (this.#ASF) {
  5229. if (await this.#ASF.joinGroup(groupName)) {
  5230. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5231. return true;
  5232. }
  5233. return false;
  5234. }
  5235. const logStatus = scripts_echoLog({
  5236. type: 'joiningSteamGroup',
  5237. text: groupName
  5238. });
  5239. const {
  5240. result,
  5241. statusText,
  5242. status,
  5243. data
  5244. } = await tools_httpRequest({
  5245. url: `https://steamcommunity.com/groups/${groupName}`,
  5246. method: 'POST',
  5247. headers: {
  5248. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5249. },
  5250. data: $.param({
  5251. action: 'join',
  5252. sessionID: this.#auth.communitySessionID
  5253. })
  5254. });
  5255. if (result === 'Success') {
  5256. if (data?.status === 200 && !data.responseText.includes('grouppage_join_area')) {
  5257. logStatus.success();
  5258. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5259. return true;
  5260. }
  5261. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5262. return false;
  5263. }
  5264. logStatus.error(`${result}:${statusText}(${status})`);
  5265. return false;
  5266. } catch (error) {
  5267. throwError(error, 'Steam.joinGroup');
  5268. return false;
  5269. }
  5270. }
  5271. async #leaveGroup(groupName) {
  5272. try {
  5273. if (this.whiteList.groups.includes(groupName)) {
  5274. scripts_echoLog({
  5275. type: 'whiteList',
  5276. text: 'Steam.leaveGroup',
  5277. id: groupName
  5278. });
  5279. return true;
  5280. }
  5281. if (this.#ASF) {
  5282. return await this.#ASF.leaveGroup(groupName);
  5283. }
  5284. const groupId = await this.#getGroupId(groupName);
  5285. if (!groupId) {
  5286. return false;
  5287. }
  5288. const logStatus = scripts_echoLog({
  5289. type: 'leavingSteamGroup',
  5290. text: groupName
  5291. });
  5292. const {
  5293. result,
  5294. statusText,
  5295. status,
  5296. data
  5297. } = await tools_httpRequest({
  5298. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5299. method: 'POST',
  5300. headers: {
  5301. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5302. },
  5303. data: $.param({
  5304. sessionID: this.#auth.communitySessionID,
  5305. action: 'leaveGroup',
  5306. groupId: groupId
  5307. })
  5308. });
  5309. if (result === 'Success') {
  5310. 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) {
  5311. logStatus.success();
  5312. return true;
  5313. }
  5314. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5315. return false;
  5316. }
  5317. logStatus.error(`${result}:${statusText}(${status})`);
  5318. return false;
  5319. } catch (error) {
  5320. throwError(error, 'Steam.leaveGroup');
  5321. return false;
  5322. }
  5323. }
  5324. async #getGroupId(groupName) {
  5325. try {
  5326. const logStatus = scripts_echoLog({
  5327. type: 'gettingSteamGroupId',
  5328. text: groupName
  5329. });
  5330. const groupId = this.#cache.group[groupName];
  5331. if (groupId) {
  5332. logStatus.success();
  5333. return groupId;
  5334. }
  5335. const {
  5336. result,
  5337. statusText,
  5338. status,
  5339. data
  5340. } = await tools_httpRequest({
  5341. url: `https://steamcommunity.com/groups/${groupName}`,
  5342. method: 'GET',
  5343. headers: {
  5344. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5345. }
  5346. });
  5347. if (result === 'Success') {
  5348. if (data?.status === 200) {
  5349. const groupId = data.responseText.match(/OpenGroupChat\( '([0-9]+)'/)?.[1];
  5350. if (groupId) {
  5351. this.#setCache('group', groupName, groupId);
  5352. logStatus.success();
  5353. return groupId;
  5354. }
  5355. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5356. return false;
  5357. }
  5358. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5359. return false;
  5360. }
  5361. logStatus.error(`${result}:${statusText}(${status})`);
  5362. return false;
  5363. } catch (error) {
  5364. throwError(error, 'Steam.getGroupID');
  5365. return false;
  5366. }
  5367. }
  5368. async #joinOfficialGroup(gameId) {
  5369. try {
  5370. if (this.#ASF) {
  5371. if (await this.#ASF.joinGroup(gameId)) {
  5372. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5373. return true;
  5374. }
  5375. return false;
  5376. }
  5377. const logStatus = scripts_echoLog({
  5378. type: 'joiningSteamOfficialGroup',
  5379. text: gameId
  5380. });
  5381. const {
  5382. result,
  5383. statusText,
  5384. status,
  5385. data
  5386. } = await tools_httpRequest({
  5387. url: `https://steamcommunity.com/games/${gameId}?action=join&sessionID=${this.#auth.communitySessionID}`,
  5388. method: 'GET',
  5389. headers: {
  5390. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5391. }
  5392. });
  5393. if (result === 'Success') {
  5394. if (data?.status === 200 && !data.responseText.includes('id="publicGroupJoin"')) {
  5395. logStatus.success();
  5396. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5397. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5398. if (groupId) {
  5399. this.#setCache('officialGroup', gameId, groupId);
  5400. }
  5401. return true;
  5402. }
  5403. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5404. return false;
  5405. }
  5406. logStatus.error(`${result}:${statusText}(${status})`);
  5407. return false;
  5408. } catch (error) {
  5409. throwError(error, 'Steam.joinOfficialGroup');
  5410. return false;
  5411. }
  5412. }
  5413. async #leaveOfficialGroup(gameId) {
  5414. try {
  5415. if (this.whiteList.officialGroups.includes(gameId)) {
  5416. scripts_echoLog({
  5417. type: 'whiteList',
  5418. text: 'Steam.leaveOfficialGroup',
  5419. id: gameId
  5420. });
  5421. return true;
  5422. }
  5423. if (this.#ASF) {
  5424. return await this.#ASF.leaveGroup(gameId);
  5425. }
  5426. const groupId = await this.#getOfficialGroupId(gameId);
  5427. if (!groupId) {
  5428. return false;
  5429. }
  5430. const logStatus = scripts_echoLog({
  5431. type: 'leavingSteamOfficialGroup',
  5432. text: gameId
  5433. });
  5434. const {
  5435. result,
  5436. statusText,
  5437. status,
  5438. data
  5439. } = await tools_httpRequest({
  5440. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5441. method: 'POST',
  5442. headers: {
  5443. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5444. },
  5445. data: $.param({
  5446. sessionID: this.#auth.communitySessionID,
  5447. action: 'leaveGroup',
  5448. groupId: groupId
  5449. })
  5450. });
  5451. if (result === 'Success') {
  5452. if (data?.status === 200) {
  5453. const {
  5454. result: resultR,
  5455. statusText: statusTextR,
  5456. status: statusR,
  5457. data: dataR
  5458. } = await tools_httpRequest({
  5459. url: `https://steamcommunity.com/games/${gameId}`,
  5460. method: 'GET',
  5461. headers: {
  5462. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5463. }
  5464. });
  5465. if (resultR === 'Success') {
  5466. if (dataR?.status === 200 && dataR.responseText.includes('id="publicGroupJoin"')) {
  5467. logStatus.success();
  5468. return true;
  5469. }
  5470. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5471. return false;
  5472. }
  5473. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5474. return false;
  5475. }
  5476. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5477. return false;
  5478. }
  5479. logStatus.error(`${result}:${statusText}(${status})`);
  5480. return false;
  5481. } catch (error) {
  5482. throwError(error, 'Steam.leaveOfficialGroup');
  5483. return false;
  5484. }
  5485. }
  5486. async #getOfficialGroupId(gameId) {
  5487. try {
  5488. const logStatus = scripts_echoLog({
  5489. type: 'gettingSteamOfficialGroupId',
  5490. text: gameId
  5491. });
  5492. const groupId = this.#cache.officialGroup[gameId];
  5493. if (groupId) {
  5494. logStatus.success();
  5495. return groupId;
  5496. }
  5497. const {
  5498. result,
  5499. statusText,
  5500. status,
  5501. data
  5502. } = await tools_httpRequest({
  5503. url: `https://steamcommunity.com/games/${gameId}`,
  5504. method: 'GET',
  5505. headers: {
  5506. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5507. }
  5508. });
  5509. if (result === 'Success') {
  5510. if (data?.status === 200) {
  5511. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5512. if (groupId) {
  5513. this.#setCache('officialGroup', gameId, groupId);
  5514. logStatus.success();
  5515. return groupId;
  5516. }
  5517. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5518. return false;
  5519. }
  5520. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5521. return false;
  5522. }
  5523. logStatus.error(`${result}:${statusText}(${status})`);
  5524. return false;
  5525. } catch (error) {
  5526. throwError(error, 'Steam.getGroupID');
  5527. return false;
  5528. }
  5529. }
  5530. async #addToWishlist(gameId) {
  5531. try {
  5532. if (this.#ASF) {
  5533. if (await this.#ASF.addToWishlist(gameId)) {
  5534. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5535. return true;
  5536. }
  5537. return false;
  5538. }
  5539. const logStatus = scripts_echoLog({
  5540. type: 'addingToWishlist',
  5541. text: gameId
  5542. });
  5543. const {
  5544. result,
  5545. data
  5546. } = await tools_httpRequest({
  5547. url: 'https://store.steampowered.com/api/addtowishlist',
  5548. method: 'POST',
  5549. headers: {
  5550. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5551. },
  5552. data: $.param({
  5553. sessionid: this.#auth.storeSessionID,
  5554. appid: gameId
  5555. }),
  5556. dataType: 'json'
  5557. });
  5558. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  5559. logStatus.success();
  5560. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5561. return true;
  5562. }
  5563. const {
  5564. result: resultR,
  5565. statusText: statusTextR,
  5566. status: statusR,
  5567. data: dataR
  5568. } = await tools_httpRequest({
  5569. url: `https://store.steampowered.com/app/${gameId}`,
  5570. method: 'GET'
  5571. });
  5572. if (resultR === 'Success') {
  5573. if (dataR?.status === 200) {
  5574. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  5575. logStatus.warning(i18n('changeAreaNotice'));
  5576. if (!await this.#changeArea()) {
  5577. return false;
  5578. }
  5579. return await this.#addToWishlist(gameId);
  5580. }
  5581. if (dataR.responseText.includes('class="queue_actions_ctn"') && dataR.responseText.includes('class="already_in_library"')) {
  5582. logStatus.success();
  5583. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5584. return true;
  5585. } 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"')) {
  5586. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  5587. return false;
  5588. }
  5589. logStatus.success();
  5590. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5591. return true;
  5592. }
  5593. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5594. return false;
  5595. }
  5596. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5597. return false;
  5598. } catch (error) {
  5599. throwError(error, 'Steam.addToWishlist');
  5600. return false;
  5601. }
  5602. }
  5603. async #removeFromWishlist(gameId) {
  5604. try {
  5605. if (this.whiteList.wishlists.includes(gameId)) {
  5606. scripts_echoLog({
  5607. type: 'whiteList',
  5608. text: 'Steam.removeFromWishlist',
  5609. id: gameId
  5610. });
  5611. return true;
  5612. }
  5613. if (this.#ASF) {
  5614. return await this.#ASF.removeFromWishlist(gameId);
  5615. }
  5616. const logStatus = scripts_echoLog({
  5617. type: 'removingFromWishlist',
  5618. text: gameId
  5619. });
  5620. const {
  5621. result,
  5622. data
  5623. } = await tools_httpRequest({
  5624. url: 'https://store.steampowered.com/api/removefromwishlist',
  5625. method: 'POST',
  5626. headers: {
  5627. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5628. },
  5629. data: $.param({
  5630. sessionid: this.#auth.storeSessionID,
  5631. appid: gameId
  5632. }),
  5633. dataType: 'json'
  5634. });
  5635. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  5636. logStatus.success();
  5637. return true;
  5638. }
  5639. const {
  5640. result: resultR,
  5641. statusText: statusTextR,
  5642. status: statusR,
  5643. data: dataR
  5644. } = await tools_httpRequest({
  5645. url: `https://store.steampowered.com/app/${gameId}`,
  5646. method: 'GET'
  5647. });
  5648. if (resultR === 'Success') {
  5649. if (dataR?.status === 200) {
  5650. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  5651. logStatus.warning(i18n('changeAreaNotice'));
  5652. const result = await this.#changeArea();
  5653. if (!result || result === 'CN' || result === 'skip') {
  5654. return false;
  5655. }
  5656. return await this.#removeFromWishlist(gameId);
  5657. }
  5658. if (dataR.responseText.includes('class="queue_actions_ctn"') && (dataR.responseText.includes('ds_owned_flag ds_flag') || dataR.responseText.includes('add_to_wishlist_area'))) {
  5659. logStatus.success();
  5660. return true;
  5661. }
  5662. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  5663. return false;
  5664. }
  5665. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5666. return false;
  5667. }
  5668. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5669. return false;
  5670. } catch (error) {
  5671. throwError(error, 'Steam.removeFromWishlist');
  5672. return false;
  5673. }
  5674. }
  5675. async #toggleFollowGame(gameId, doTask) {
  5676. try {
  5677. if (!doTask && this.whiteList.follows.includes(gameId)) {
  5678. scripts_echoLog({
  5679. type: 'whiteList',
  5680. text: 'Steam.unfollowGame',
  5681. id: gameId
  5682. });
  5683. return true;
  5684. }
  5685. if (this.#ASF) {
  5686. if (await this.#ASF.toggleFollowGame(gameId, doTask)) {
  5687. if (doTask) {
  5688. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  5689. }
  5690. return true;
  5691. }
  5692. return false;
  5693. }
  5694. const logStatus = scripts_echoLog({
  5695. type: `${doTask ? '' : 'un'}followingGame`,
  5696. text: gameId
  5697. });
  5698. const requestData = {
  5699. sessionid: this.#auth.storeSessionID,
  5700. appid: gameId
  5701. };
  5702. if (!doTask) {
  5703. requestData.unfollow = '1';
  5704. }
  5705. const {
  5706. result,
  5707. data
  5708. } = await tools_httpRequest({
  5709. url: 'https://store.steampowered.com/explore/followgame/',
  5710. method: 'POST',
  5711. headers: {
  5712. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5713. },
  5714. data: $.param(requestData)
  5715. });
  5716. if (result === 'Success' && data?.status === 200 && data.responseText === 'true') {
  5717. logStatus.success();
  5718. return true;
  5719. }
  5720. const followed = await this.#isFollowedGame(gameId);
  5721. if (this.#area === 'CN' && followed === 'areaLocked') {
  5722. logStatus.warning(i18n('changeAreaNotice'));
  5723. if (!await this.#changeArea()) {
  5724. return false;
  5725. }
  5726. return await this.#toggleFollowGame(gameId, doTask);
  5727. }
  5728. if (doTask === followed) {
  5729. logStatus.success();
  5730. if (doTask) {
  5731. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  5732. }
  5733. return true;
  5734. }
  5735. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5736. return false;
  5737. } catch (error) {
  5738. throwError(error, 'Steam.toggleFollowGame');
  5739. return false;
  5740. }
  5741. }
  5742. async #isFollowedGame(gameId) {
  5743. try {
  5744. const {
  5745. result,
  5746. data
  5747. } = await tools_httpRequest({
  5748. url: `https://store.steampowered.com/app/${gameId}`,
  5749. method: 'GET'
  5750. });
  5751. if (result === 'Success') {
  5752. if (data?.status === 200) {
  5753. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  5754. return 'areaLocked';
  5755. }
  5756. if ($(data.responseText.replace(/<img.*?>/g, '')).find('.queue_control_button.queue_btn_follow>.btnv6_blue_hoverfade.btn_medium.queue_btn_active').css('display') !== 'none') {
  5757. return true;
  5758. }
  5759. return false;
  5760. }
  5761. return false;
  5762. }
  5763. return false;
  5764. } catch (error) {
  5765. throwError(error, 'Steam.isFollowedGame');
  5766. return false;
  5767. }
  5768. }
  5769. async #toggleForum(gameId, doTask = true) {
  5770. try {
  5771. if (!doTask && this.whiteList.forums.includes(gameId)) {
  5772. scripts_echoLog({
  5773. type: 'whiteList',
  5774. text: 'Steam.unsubscribeForum',
  5775. id: gameId
  5776. });
  5777. return true;
  5778. }
  5779. const forumId = await this.#getForumId(gameId);
  5780. if (!forumId) {
  5781. return false;
  5782. }
  5783. const logStatus = scripts_echoLog({
  5784. type: `${doTask ? '' : 'un'}subscribingForum`,
  5785. text: gameId
  5786. });
  5787. const [ id, feature ] = forumId.split('_');
  5788. const {
  5789. result,
  5790. statusText,
  5791. status,
  5792. data
  5793. } = await tools_httpRequest({
  5794. url: `https://steamcommunity.com/forum/${id}/General/${doTask ? '' : 'un'}subscribe/${feature || '0'}/`,
  5795. method: 'POST',
  5796. responseType: 'json',
  5797. headers: {
  5798. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5799. },
  5800. data: $.param({
  5801. sessionid: this.#auth.communitySessionID
  5802. })
  5803. });
  5804. if (result === 'Success') {
  5805. if (data?.status === 200 && (data.response?.success === 1 || data.response?.success === 29)) {
  5806. if (doTask) {
  5807. this.tasks.forums = unique([ ...this.tasks.forums, gameId ]);
  5808. }
  5809. logStatus.success();
  5810. return true;
  5811. }
  5812. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5813. return true;
  5814. }
  5815. logStatus.error(`${result}:${statusText}(${status})`);
  5816. return true;
  5817. } catch (error) {
  5818. throwError(error, 'Steam.toggleForum');
  5819. return true;
  5820. }
  5821. }
  5822. async #getForumId(gameId) {
  5823. try {
  5824. const logStatus = scripts_echoLog({
  5825. type: 'gettingForumId',
  5826. text: gameId
  5827. });
  5828. const forumId = this.#cache.forum[gameId];
  5829. if (forumId) {
  5830. logStatus.success();
  5831. return forumId;
  5832. }
  5833. const {
  5834. result,
  5835. statusText,
  5836. status,
  5837. data
  5838. } = await tools_httpRequest({
  5839. url: `https://steamcommunity.com/app/${gameId}/discussions/`,
  5840. method: 'GET'
  5841. });
  5842. if (result === 'Success') {
  5843. if (data?.status === 200) {
  5844. const forumId = data.responseText?.match(/General_([\d]+(_[\d]+)?)/)?.[1];
  5845. if (forumId) {
  5846. this.#setCache('forum', gameId, forumId);
  5847. logStatus.success();
  5848. return forumId;
  5849. }
  5850. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5851. return false;
  5852. }
  5853. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5854. return false;
  5855. }
  5856. logStatus.error(`${result}:${statusText}(${status})`);
  5857. return false;
  5858. } catch (error) {
  5859. throwError(error, 'Steam.getForumId');
  5860. return false;
  5861. }
  5862. }
  5863. async #toggleFavoriteWorkshop(id, doTask = true) {
  5864. try {
  5865. if (!doTask && this.whiteList.workshops.includes(id)) {
  5866. scripts_echoLog({
  5867. type: 'whiteList',
  5868. text: 'Steam.unfavoriteWorkshop',
  5869. id: id
  5870. });
  5871. return true;
  5872. }
  5873. const appid = await this.#getWorkshopAppId(id);
  5874. if (!appid) {
  5875. return false;
  5876. }
  5877. const logStatus = scripts_echoLog({
  5878. type: doTask ? 'favoritingWorkshop' : 'unfavoritingWorkshop',
  5879. text: id
  5880. });
  5881. const {
  5882. result,
  5883. statusText,
  5884. status,
  5885. data
  5886. } = await tools_httpRequest({
  5887. url: `https://steamcommunity.com/sharedfiles/${doTask ? '' : 'un'}favorite`,
  5888. method: 'POST',
  5889. headers: {
  5890. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5891. },
  5892. data: $.param({
  5893. id: id,
  5894. appid: appid,
  5895. sessionid: this.#auth.communitySessionID
  5896. })
  5897. });
  5898. if (result === 'Success') {
  5899. if (data?.status === 200 && !data.responseText) {
  5900. if (doTask) {
  5901. this.tasks.workshops = unique([ ...this.tasks.workshops, id ]);
  5902. }
  5903. logStatus.success();
  5904. return true;
  5905. }
  5906. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5907. return false;
  5908. }
  5909. logStatus.error(`${result}:${statusText}(${status})`);
  5910. return false;
  5911. } catch (error) {
  5912. throwError(error, 'Steam.toggleFavoriteWorkshop');
  5913. return false;
  5914. }
  5915. }
  5916. async #getWorkshopAppId(id) {
  5917. try {
  5918. const logStatus = scripts_echoLog({
  5919. type: 'gettingWorkshopAppId',
  5920. text: id
  5921. });
  5922. const appId = this.#cache.workshop[id];
  5923. if (appId) {
  5924. logStatus.success();
  5925. return appId;
  5926. }
  5927. const {
  5928. result,
  5929. statusText,
  5930. status,
  5931. data
  5932. } = await tools_httpRequest({
  5933. url: `https://steamcommunity.com/sharedfiles/filedetails/?id=${id}`,
  5934. method: 'GET'
  5935. });
  5936. if (result === 'Success') {
  5937. if (data?.status === 200) {
  5938. const appId = data.responseText.match(/<input type="hidden" name="appid" value="([\d]+?)" \/>/)?.[1];
  5939. if (appId) {
  5940. this.#setCache('workshop', id, appId);
  5941. logStatus.success();
  5942. return appId;
  5943. }
  5944. logStatus.error('Error: getWorkshopAppId failed');
  5945. return false;
  5946. }
  5947. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5948. return false;
  5949. }
  5950. logStatus.error(`${result}:${statusText}(${status})`);
  5951. return false;
  5952. } catch (error) {
  5953. throwError(error, 'Steam.getWorkshopAppId');
  5954. return false;
  5955. }
  5956. }
  5957. async #voteUpWorkshop(id) {
  5958. try {
  5959. const logStatus = scripts_echoLog({
  5960. type: 'votingUpWorkshop',
  5961. text: id
  5962. });
  5963. const {
  5964. result,
  5965. statusText,
  5966. status,
  5967. data
  5968. } = await tools_httpRequest({
  5969. url: 'https://steamcommunity.com/sharedfiles/voteup',
  5970. method: 'POST',
  5971. responseType: 'json',
  5972. headers: {
  5973. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5974. },
  5975. data: $.param({
  5976. id: id,
  5977. sessionid: this.#auth.communitySessionID
  5978. })
  5979. });
  5980. if (result === 'Success') {
  5981. if (data?.status === 200 && data.response?.success === 1) {
  5982. logStatus.success();
  5983. return true;
  5984. }
  5985. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5986. return true;
  5987. }
  5988. logStatus.error(`${result}:${statusText}(${status})`);
  5989. return true;
  5990. } catch (error) {
  5991. throwError(error, 'Steam.voteupWorkshop');
  5992. return true;
  5993. }
  5994. }
  5995. async #toggleCurator(curatorId, doTask = true) {
  5996. try {
  5997. if (!doTask && this.whiteList.curators.includes(curatorId)) {
  5998. scripts_echoLog({
  5999. type: 'whiteList',
  6000. text: 'Steam.unfollowCurator',
  6001. id: curatorId
  6002. });
  6003. return true;
  6004. }
  6005. if (this.#ASF) {
  6006. return await this.#ASF.toggleCurator(curatorId, doTask);
  6007. }
  6008. const logStatus = scripts_echoLog({
  6009. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  6010. text: curatorId
  6011. });
  6012. const {
  6013. result,
  6014. statusText,
  6015. status,
  6016. data
  6017. } = await tools_httpRequest({
  6018. url: 'https://store.steampowered.com/curators/ajaxfollow',
  6019. method: 'POST',
  6020. headers: {
  6021. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6022. },
  6023. data: $.param({
  6024. clanid: curatorId,
  6025. sessionid: this.#auth.storeSessionID,
  6026. follow: doTask
  6027. }),
  6028. dataType: 'json'
  6029. });
  6030. if (result === 'Success') {
  6031. if (data?.status === 200 && data.response?.success?.success === 1) {
  6032. logStatus.success();
  6033. return true;
  6034. }
  6035. logStatus.error(`Error:${data?.statusText}(${data?.response?.success}` || `${data?.status})`);
  6036. return false;
  6037. }
  6038. logStatus.error(`${result}:${statusText}(${status})`);
  6039. return false;
  6040. } catch (error) {
  6041. throwError(error, 'Steam.toggleCurator');
  6042. return false;
  6043. }
  6044. }
  6045. async getCuratorId(path, name) {
  6046. try {
  6047. const logStatus = scripts_echoLog({
  6048. type: 'gettingCuratorId',
  6049. text: `${path}/${name}`
  6050. });
  6051. const curatorId = this.#cache.curator[`${path}/${name}`];
  6052. if (curatorId) {
  6053. logStatus.success();
  6054. return curatorId;
  6055. }
  6056. const {
  6057. result,
  6058. statusText,
  6059. status,
  6060. data
  6061. } = await tools_httpRequest({
  6062. url: `https://store.steampowered.com/${path}/${name}`,
  6063. method: 'GET',
  6064. headers: {
  6065. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6066. }
  6067. });
  6068. if (result === 'Success') {
  6069. if (data?.status === 200) {
  6070. const curatorId = data.responseText.match(/g_pagingData.*?"clanid":([\d]+)/)?.[1];
  6071. if (curatorId) {
  6072. this.#setCache('curator', `${path}/${name}`, curatorId);
  6073. logStatus.success();
  6074. return curatorId;
  6075. }
  6076. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6077. return false;
  6078. }
  6079. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6080. return false;
  6081. }
  6082. logStatus.error(`${result}:${statusText}(${status})`);
  6083. return false;
  6084. } catch (error) {
  6085. throwError(error, 'Steam.getCuratorID');
  6086. return false;
  6087. }
  6088. }
  6089. async #toggleCuratorLike(link, doTask = true) {
  6090. try {
  6091. const [ path, name ] = link.split('/');
  6092. if (!(path && name)) {
  6093. scripts_echoLog({
  6094. text: i18n('errorLink', link)
  6095. });
  6096. return false;
  6097. }
  6098. const curatorId = await this.getCuratorId(path, name);
  6099. if (curatorId) {
  6100. return await this.#toggleCurator(curatorId, doTask);
  6101. }
  6102. return false;
  6103. } catch (error) {
  6104. throwError(error, 'Steam.toggleCuratorLike');
  6105. return false;
  6106. }
  6107. }
  6108. async #getAnnouncementParams(appId, viewId) {
  6109. try {
  6110. const logStatus = scripts_echoLog({
  6111. type: 'gettingAnnouncementParams',
  6112. text: appId,
  6113. id: viewId
  6114. });
  6115. const {
  6116. result,
  6117. statusText,
  6118. status,
  6119. data
  6120. } = await tools_httpRequest({
  6121. 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`,
  6122. method: 'GET',
  6123. responseType: 'json',
  6124. headers: {
  6125. Host: 'store.steampowered.com',
  6126. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6127. }
  6128. });
  6129. if (result === 'Success') {
  6130. if (data?.status === 200 && data?.response?.success === 1) {
  6131. const {
  6132. clanid,
  6133. gid
  6134. } = data.response.event?.announcement_body || {};
  6135. if (clanid) {
  6136. logStatus.success();
  6137. return {
  6138. clanId: clanid,
  6139. gid: gid
  6140. };
  6141. }
  6142. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6143. return {};
  6144. }
  6145. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6146. return {};
  6147. }
  6148. logStatus.error(`${result}:${statusText}(${status})`);
  6149. return {};
  6150. } catch (error) {
  6151. throwError(error, 'Steam.likeAnnouncement');
  6152. return {};
  6153. }
  6154. }
  6155. async #likeAnnouncement(id) {
  6156. try {
  6157. const [ appId, viewId ] = id.split('/');
  6158. if (!(appId && viewId)) {
  6159. scripts_echoLog({}).error(`${i18n('missParams')}(id)`);
  6160. return false;
  6161. }
  6162. const {
  6163. clanId,
  6164. gid
  6165. } = await this.#getAnnouncementParams(appId, viewId);
  6166. if (!clanId) {
  6167. return false;
  6168. }
  6169. const logStatus = scripts_echoLog({
  6170. type: 'likingAnnouncement',
  6171. text: appId,
  6172. id: viewId
  6173. });
  6174. const {
  6175. result,
  6176. statusText,
  6177. status,
  6178. data
  6179. } = await tools_httpRequest({
  6180. url: `https://store.steampowered.com/updated/ajaxrateupdate/${gid || viewId}`,
  6181. method: 'POST',
  6182. headers: {
  6183. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6184. Host: 'store.steampowered.com',
  6185. Origin: 'https://store.steampowered.com',
  6186. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6187. },
  6188. data: $.param({
  6189. sessionid: this.#auth.storeSessionID,
  6190. voteup: 1,
  6191. clanid: clanId,
  6192. ajax: 1
  6193. }),
  6194. dataType: 'json'
  6195. });
  6196. if (result === 'Success') {
  6197. if (data?.status === 200 && data.response.success === 1) {
  6198. logStatus.success();
  6199. return true;
  6200. }
  6201. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6202. return false;
  6203. }
  6204. logStatus.error(`${result}:${statusText}(${status})`);
  6205. return false;
  6206. } catch (error) {
  6207. throwError(error, 'Steam.likeAnnouncement');
  6208. return false;
  6209. }
  6210. }
  6211. async #appid2subid(id) {
  6212. try {
  6213. const logStatus = scripts_echoLog({
  6214. type: 'gettingSubid',
  6215. text: id
  6216. });
  6217. const {
  6218. result,
  6219. statusText,
  6220. status,
  6221. data
  6222. } = await tools_httpRequest({
  6223. url: `https://store.steampowered.com/app/${id}`,
  6224. method: 'GET',
  6225. headers: {
  6226. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6227. }
  6228. });
  6229. if (result === 'Success') {
  6230. if (data?.status === 200) {
  6231. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6232. logStatus.success(i18n('owned'));
  6233. return false;
  6234. }
  6235. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6236. logStatus.warning(i18n('changeAreaNotice'));
  6237. const result = await this.#changeArea();
  6238. if (!result || result === 'CN' || result === 'skip') {
  6239. return false;
  6240. }
  6241. return await this.#appid2subid(id);
  6242. }
  6243. let subid = data.responseText.match(/name="subid" value="([\d]+?)"/)?.[1];
  6244. if (subid) {
  6245. logStatus.success();
  6246. return subid;
  6247. }
  6248. subid = data.responseText.match(/AddFreeLicense\(\s*(\d+)/)?.[1];
  6249. if (subid) {
  6250. logStatus.success();
  6251. return subid;
  6252. }
  6253. logStatus.error(`Error:${i18n('noSubid')}`);
  6254. return false;
  6255. }
  6256. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6257. return false;
  6258. }
  6259. logStatus.error(`${result}:${statusText}(${status})`);
  6260. return false;
  6261. } catch (error) {
  6262. throwError(error, 'Steam.appid2subid');
  6263. return false;
  6264. }
  6265. }
  6266. async #getLicenses() {
  6267. try {
  6268. const logStatus = scripts_echoLog({
  6269. text: i18n('gettingLicenses')
  6270. });
  6271. const {
  6272. result,
  6273. statusText,
  6274. status,
  6275. data
  6276. } = await tools_httpRequest({
  6277. url: `https://store.steampowered.com/dynamicstore/userdata/?t=${new Date().getTime()}`,
  6278. method: 'GET',
  6279. responseType: 'json'
  6280. });
  6281. if (result === 'Success') {
  6282. if (data?.status === 200) {
  6283. logStatus.success();
  6284. return data.response?.rgOwnedPackages;
  6285. }
  6286. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6287. return false;
  6288. }
  6289. logStatus.error(`${result}:${statusText}(${status})`);
  6290. return false;
  6291. } catch (error) {
  6292. throwError(error, 'Steam.getLicenses');
  6293. return false;
  6294. }
  6295. }
  6296. async #addLicense(id) {
  6297. try {
  6298. if (this.#ASF) {
  6299. return await this.#ASF.addLicense(id);
  6300. }
  6301. const [ type, ids ] = id.split('-');
  6302. if (type === 'appid') {
  6303. const subid = await this.#appid2subid(ids);
  6304. if (!subid) {
  6305. return false;
  6306. }
  6307. const logStatus = scripts_echoLog({
  6308. type: 'addingFreeLicense',
  6309. text: ids
  6310. });
  6311. if (!await this.#addFreeLicense(subid, logStatus)) {
  6312. return false;
  6313. }
  6314. const {
  6315. result,
  6316. statusText,
  6317. status,
  6318. data
  6319. } = await tools_httpRequest({
  6320. url: `https://store.steampowered.com/app/${ids}`,
  6321. method: 'GET'
  6322. });
  6323. if (result === 'Success') {
  6324. if (data?.status === 200) {
  6325. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6326. logStatus.success();
  6327. return true;
  6328. }
  6329. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6330. return false;
  6331. }
  6332. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6333. return false;
  6334. }
  6335. logStatus.error(`${result}:${statusText}(${status})`);
  6336. return false;
  6337. } else if (type === 'subid') {
  6338. if (this.#area === 'CN') {
  6339. scripts_echoLog({}).success(i18n('tryChangeAreaNotice'));
  6340. await this.#changeArea();
  6341. }
  6342. const logStatusArr = {};
  6343. const idsArr = ids.split(',');
  6344. for (const subid of idsArr) {
  6345. const logStatus = scripts_echoLog({
  6346. type: 'addingFreeLicenseSubid',
  6347. text: subid
  6348. });
  6349. if (!await this.#addFreeLicense(subid, logStatus)) {
  6350. return false;
  6351. }
  6352. logStatusArr[subid] = logStatus;
  6353. }
  6354. const licenses = await this.#getLicenses();
  6355. if (!licenses) {
  6356. return false;
  6357. }
  6358. for (const subid of idsArr) {
  6359. if (licenses.includes(parseInt(subid, 10))) {
  6360. logStatusArr[subid].success();
  6361. } else {
  6362. logStatusArr[subid].error();
  6363. }
  6364. }
  6365. return true;
  6366. }
  6367. return false;
  6368. } catch (error) {
  6369. throwError(error, 'Steam.addLicense');
  6370. return false;
  6371. }
  6372. }
  6373. async #addFreeLicense(id, logStatusPre) {
  6374. try {
  6375. const logStatus = logStatusPre || scripts_echoLog({
  6376. type: 'addingFreeLicenseSubid',
  6377. text: id
  6378. });
  6379. const {
  6380. result,
  6381. statusText,
  6382. status,
  6383. data
  6384. } = await tools_httpRequest({
  6385. url: `https://store.steampowered.com/freelicense/addfreelicense/${id}`,
  6386. method: 'POST',
  6387. headers: {
  6388. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6389. Host: 'store.steampowered.com',
  6390. Origin: 'https://store.steampowered.com',
  6391. Referer: 'https://store.steampowered.com/account/licenses/'
  6392. },
  6393. data: $.param({
  6394. ajax: true,
  6395. sessionid: this.#auth.storeSessionID
  6396. }),
  6397. dataType: 'json'
  6398. });
  6399. if (result === 'Success') {
  6400. if (data?.status === 200) {
  6401. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6402. logStatus.warning(i18n('changeAreaNotice'));
  6403. const result = await this.#changeArea();
  6404. if (!result || [ 'CN', 'skip' ].includes(result)) {
  6405. return false;
  6406. }
  6407. return await this.#addFreeLicense(id);
  6408. }
  6409. logStatus.success();
  6410. return true;
  6411. }
  6412. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6413. return false;
  6414. }
  6415. logStatus.error(`${result}:${statusText}(${status})`);
  6416. return false;
  6417. } catch (error) {
  6418. throwError(error, 'Steam.addFreeLicense');
  6419. return false;
  6420. }
  6421. }
  6422. async #requestPlayTestAccess(id) {
  6423. try {
  6424. if (this.#ASF) {
  6425. return await this.#ASF.requestPlayTestAccess(id);
  6426. }
  6427. const logStatus = scripts_echoLog({
  6428. type: 'requestingPlayTestAccess',
  6429. text: id
  6430. });
  6431. const {
  6432. result,
  6433. statusText,
  6434. status,
  6435. data
  6436. } = await tools_httpRequest({
  6437. url: `https://store.steampowered.com/ajaxrequestplaytestaccess/${id}`,
  6438. method: 'POST',
  6439. headers: {
  6440. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6441. Host: 'store.steampowered.com',
  6442. Origin: 'https://store.steampowered.com',
  6443. Referer: `https://store.steampowered.com/app/${id}`
  6444. },
  6445. data: $.param({
  6446. sessionid: this.#auth.storeSessionID
  6447. }),
  6448. dataType: 'json'
  6449. });
  6450. if (result === 'Success') {
  6451. if (data?.status === 200 && data?.response?.success === 1) {
  6452. logStatus.success();
  6453. return true;
  6454. }
  6455. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6456. return false;
  6457. }
  6458. logStatus.error(`${result}:${statusText}(${status})`);
  6459. return false;
  6460. } catch (error) {
  6461. throwError(error, 'Steam.requestPlayTestAccess');
  6462. return false;
  6463. }
  6464. }
  6465. async toggle({
  6466. doTask = true,
  6467. groupLinks = [],
  6468. officialGroupLinks = [],
  6469. wishlistLinks = [],
  6470. followLinks = [],
  6471. forumLinks = [],
  6472. workshopLinks = [],
  6473. workshopVoteLinks = [],
  6474. curatorLinks = [],
  6475. curatorLikeLinks = [],
  6476. announcementLinks = [],
  6477. licenseLinks = [],
  6478. playtestLinks = []
  6479. }) {
  6480. try {
  6481. if ([ ...groupLinks, ...officialGroupLinks, ...forumLinks, ...workshopLinks, ...workshopVoteLinks ].length > 0 && !this.#communityInitialized) {
  6482. scripts_echoLog({
  6483. text: i18n('needInit')
  6484. });
  6485. return false;
  6486. }
  6487. if ([ ...wishlistLinks, ...followLinks, ...curatorLinks, ...curatorLikeLinks, ...announcementLinks, ...licenseLinks, ...playtestLinks ].length > 0 && !this.#storeInitialized) {
  6488. scripts_echoLog({
  6489. text: i18n('needInit')
  6490. });
  6491. return false;
  6492. }
  6493. const prom = [];
  6494. if (doTask && !globalOptions.doTask.steam.groups || !doTask && !globalOptions.undoTask.steam.groups) {
  6495. scripts_echoLog({
  6496. type: 'globalOptionsSkip',
  6497. text: 'steam.groups'
  6498. });
  6499. } else {
  6500. const realGroups = this.getRealParams('groups', groupLinks, doTask, link => link.match(/groups\/(.+)\/?/)?.[1]);
  6501. if (realGroups.length > 0) {
  6502. for (const group of realGroups) {
  6503. if (doTask) {
  6504. prom.push(this.#joinGroup(group));
  6505. } else {
  6506. prom.push(this.#leaveGroup(group));
  6507. }
  6508. await delay(1e3);
  6509. }
  6510. }
  6511. }
  6512. if (doTask && !globalOptions.doTask.steam.officialGroups || !doTask && !globalOptions.undoTask.steam.officialGroups) {
  6513. scripts_echoLog({
  6514. type: 'globalOptionsSkip',
  6515. text: 'steam.officialGroups'
  6516. });
  6517. } else {
  6518. const realOfficialGroups = this.getRealParams('officialGroups', officialGroupLinks, doTask, link => link.match(/games\/(.+)\/?/)?.[1]);
  6519. if (realOfficialGroups.length > 0) {
  6520. for (const officialGroup of realOfficialGroups) {
  6521. if (doTask) {
  6522. prom.push(this.#joinOfficialGroup(officialGroup));
  6523. } else {
  6524. prom.push(this.#leaveOfficialGroup(officialGroup));
  6525. }
  6526. await delay(1e3);
  6527. }
  6528. }
  6529. }
  6530. if (doTask && !globalOptions.doTask.steam.wishlists || !doTask && !globalOptions.undoTask.steam.wishlists) {
  6531. scripts_echoLog({
  6532. type: 'globalOptionsSkip',
  6533. text: 'steam.wishlists'
  6534. });
  6535. } else {
  6536. const realWishlists = this.getRealParams('wishlists', wishlistLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6537. if (realWishlists.length > 0) {
  6538. for (const game of realWishlists) {
  6539. if (doTask) {
  6540. prom.push(this.#addToWishlist(game));
  6541. } else {
  6542. prom.push(this.#removeFromWishlist(game));
  6543. }
  6544. await delay(1e3);
  6545. }
  6546. }
  6547. }
  6548. if (doTask && !globalOptions.doTask.steam.follows || !doTask && !globalOptions.undoTask.steam.follows) {
  6549. scripts_echoLog({
  6550. type: 'globalOptionsSkip',
  6551. text: 'steam.follows'
  6552. });
  6553. } else {
  6554. const realFollows = this.getRealParams('follows', followLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6555. if (realFollows.length > 0) {
  6556. for (const game of realFollows) {
  6557. prom.push(this.#toggleFollowGame(game, doTask));
  6558. await delay(1e3);
  6559. }
  6560. }
  6561. }
  6562. if (doTask && !globalOptions.doTask.steam.forums || !doTask && !globalOptions.undoTask.steam.forums) {
  6563. scripts_echoLog({
  6564. type: 'globalOptionsSkip',
  6565. text: 'steam.forums'
  6566. });
  6567. } else {
  6568. const realForums = this.getRealParams('forums', forumLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6569. if (realForums.length > 0) {
  6570. for (const forum of realForums) {
  6571. prom.push(this.#toggleForum(forum, doTask));
  6572. await delay(1e3);
  6573. }
  6574. }
  6575. }
  6576. if (doTask && !globalOptions.doTask.steam.workshops || !doTask && !globalOptions.undoTask.steam.workshops) {
  6577. scripts_echoLog({
  6578. type: 'globalOptionsSkip',
  6579. text: 'steam.workshops'
  6580. });
  6581. } else {
  6582. const realWorkshops = this.getRealParams('workshops', workshopLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  6583. if (realWorkshops.length > 0) {
  6584. for (const workshop of realWorkshops) {
  6585. prom.push(this.#toggleFavoriteWorkshop(workshop, doTask));
  6586. await delay(1e3);
  6587. }
  6588. }
  6589. }
  6590. if (doTask && !globalOptions.doTask.steam.workshopVotes) {
  6591. scripts_echoLog({
  6592. type: 'globalOptionsSkip',
  6593. text: 'steam.workshopVotes'
  6594. });
  6595. } else {
  6596. const realworkshopVotes = this.getRealParams('workshopVotes', workshopVoteLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  6597. if (doTask && realworkshopVotes.length > 0) {
  6598. for (const workshop of realworkshopVotes) {
  6599. prom.push(this.#voteUpWorkshop(workshop));
  6600. await delay(1e3);
  6601. }
  6602. }
  6603. }
  6604. if (doTask && !globalOptions.doTask.steam.curators || !doTask && !globalOptions.undoTask.steam.curators) {
  6605. scripts_echoLog({
  6606. type: 'globalOptionsSkip',
  6607. text: 'steam.curators'
  6608. });
  6609. } else {
  6610. const realCurators = this.getRealParams('curators', curatorLinks, doTask, link => link.match(/curator\/([\d]+)/)?.[1]);
  6611. const realCuratorLikes = this.getRealParams('curatorLikes', curatorLikeLinks, doTask, link => link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3).join('/'));
  6612. if (realCurators.length > 0) {
  6613. for (const curator of realCurators) {
  6614. prom.push(this.#toggleCurator(curator, doTask));
  6615. await delay(1e3);
  6616. }
  6617. }
  6618. if (realCuratorLikes.length > 0) {
  6619. for (const curatorLike of realCuratorLikes) {
  6620. prom.push(this.#toggleCuratorLike(curatorLike, doTask));
  6621. await delay(1e3);
  6622. }
  6623. }
  6624. }
  6625. if (doTask && !globalOptions.doTask.steam.announcements) {
  6626. scripts_echoLog({
  6627. type: 'globalOptionsSkip',
  6628. text: 'steam.announcements'
  6629. });
  6630. } else {
  6631. const realAnnouncements = this.getRealParams('announcements', announcementLinks, doTask, link => {
  6632. if (link.includes('store.steampowered.com')) {
  6633. return link.match(/store\.steampowered\.com\/news\/app\/([\d]+)\/view\/([\d]+)/)?.slice(1, 3).join('/');
  6634. }
  6635. return link.match(/steamcommunity\.com\/games\/([\d]+)\/announcements\/detail\/([\d]+)/)?.slice(1, 3).join('/');
  6636. });
  6637. if (doTask && realAnnouncements.length > 0) {
  6638. for (const id of realAnnouncements) {
  6639. prom.push(this.#likeAnnouncement(id));
  6640. await delay(1e3);
  6641. }
  6642. }
  6643. }
  6644. if (doTask && !globalOptions.doTask.steam.licenses) {
  6645. scripts_echoLog({
  6646. type: 'globalOptionsSkip',
  6647. text: 'steam.licenses'
  6648. });
  6649. } else if (doTask && globalOptions.doTask.steam.licenses && licenseLinks.length > 0) {
  6650. for (const ids of licenseLinks) {
  6651. const [ type, idsStr ] = ids.split('-');
  6652. const idsArr = idsStr.split(',');
  6653. for (const id of idsArr) {
  6654. prom.push(this.#addLicense(`${type}-${id}`));
  6655. await delay(1e3);
  6656. }
  6657. }
  6658. }
  6659. if (doTask && !globalOptions.doTask.steam.playtests) {
  6660. scripts_echoLog({
  6661. type: 'globalOptionsSkip',
  6662. text: 'steam.playtests'
  6663. });
  6664. } else {
  6665. const realPlaytests = this.getRealParams('playtests', playtestLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6666. if (doTask && globalOptions.doTask.steam.playtests && realPlaytests.length > 0) {
  6667. for (const id of realPlaytests) {
  6668. prom.push(this.#requestPlayTestAccess(id));
  6669. await delay(1e3);
  6670. }
  6671. }
  6672. }
  6673. return Promise.all(prom).then(async () => {
  6674. if (this.#oldArea && this.#area !== this.#oldArea) {
  6675. scripts_echoLog({}).warning(i18n('steamFinishNotice') + this.#oldArea);
  6676. await this.#changeArea(this.#oldArea);
  6677. }
  6678. return true;
  6679. });
  6680. } catch (error) {
  6681. throwError(error, 'Steam.toggle');
  6682. return false;
  6683. }
  6684. }
  6685. #setCache(type, name, id) {
  6686. try {
  6687. this.#cache[type][name] = id;
  6688. GM_setValue('steamCache', this.#cache);
  6689. } catch (error) {
  6690. throwError(error, 'Steam.setCache');
  6691. }
  6692. }
  6693. }
  6694. const social_Steam = Steam;
  6695. class Website {
  6696. undoneTasks;
  6697. socialTasks;
  6698. giveawayId;
  6699. socialInitialized = {
  6700. discord: false,
  6701. instagram: false,
  6702. reddit: false,
  6703. twitch: false,
  6704. twitter: false,
  6705. vk: false,
  6706. youtube: false,
  6707. steamStore: false,
  6708. steamCommunity: false
  6709. };
  6710. initialized = false;
  6711. steamTaskType = {
  6712. steamStore: false,
  6713. steamCommunity: false
  6714. };
  6715. social = {};
  6716. async #bind(name, init) {
  6717. try {
  6718. return {
  6719. name: name,
  6720. result: await init
  6721. };
  6722. } catch (error) {
  6723. throwError(error, 'Website.bind');
  6724. return {
  6725. name: name,
  6726. result: false
  6727. };
  6728. }
  6729. }
  6730. async initSocial(action) {
  6731. try {
  6732. const pro = [];
  6733. const tasks = action === 'do' ? this.undoneTasks : this.socialTasks;
  6734. if (tasks.discord) {
  6735. const hasDiscord = Object.values(tasks.discord).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6736. if (hasDiscord && (!this.socialInitialized.discord || !this.social.discord)) {
  6737. this.social.discord = new social_Discord();
  6738. pro.push(this.#bind('discord', this.social.discord.init(action)));
  6739. }
  6740. }
  6741. if (tasks.instagram) {
  6742. const hasInstagram = Object.values(tasks.instagram).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6743. if (hasInstagram && (!this.socialInitialized.instagram || !this.social.instagram)) {
  6744. this.social.instagram = new social_Instagram();
  6745. pro.push(this.#bind('instagram', this.social.instagram.init()));
  6746. }
  6747. }
  6748. if (tasks.reddit) {
  6749. const hasReddit = Object.values(tasks.reddit).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6750. if (hasReddit && (!this.socialInitialized.reddit || !this.social.reddit)) {
  6751. this.social.reddit = new social_Reddit();
  6752. pro.push(this.#bind('reddit', this.social.reddit.init()));
  6753. }
  6754. }
  6755. if (tasks.twitch) {
  6756. const hasTwitch = Object.values(tasks.twitch).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6757. if (hasTwitch && (!this.socialInitialized.twitch || !this.social.twitch)) {
  6758. this.social.twitch = new social_Twitch();
  6759. pro.push(this.#bind('twitch', this.social.twitch.init()));
  6760. }
  6761. }
  6762. if (tasks.twitter) {
  6763. const hasTwitter = Object.values(tasks.twitter).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6764. if (hasTwitter && (!this.socialInitialized.twitter || !this.social.twitter)) {
  6765. this.social.twitter = new social_Twitter();
  6766. pro.push(this.#bind('twitter', this.social.twitter.init()));
  6767. }
  6768. }
  6769. if (tasks.vk) {
  6770. const hasVk = Object.values(tasks.vk).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6771. if (hasVk && (!this.socialInitialized.vk || !this.social.vk)) {
  6772. this.social.vk = new social_Vk();
  6773. pro.push(this.#bind('vk', this.social.vk.init()));
  6774. }
  6775. }
  6776. if (tasks.youtube) {
  6777. const hasYoutube = Object.values(tasks.youtube).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6778. if (hasYoutube && (!this.socialInitialized.youtube || !this.social.youtube)) {
  6779. this.social.youtube = new Youtube();
  6780. pro.push(this.#bind('youtube', this.social.youtube.init()));
  6781. }
  6782. }
  6783. if (tasks.steam) {
  6784. const steamLength = Object.values(tasks.steam).reduce((total, arr) => [ ...total, ...arr ]).length;
  6785. if (steamLength > 0) {
  6786. if (!this.social.steam) {
  6787. this.social.steam = new social_Steam();
  6788. }
  6789. 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);
  6790. if (steamLength - steamCommunityLength > 0) {
  6791. this.steamTaskType.steamStore = true;
  6792. if (!this.socialInitialized.steamStore) {
  6793. pro.push(this.#bind('steamStore', this.social.steam.init('store')));
  6794. }
  6795. }
  6796. if (steamCommunityLength > 0) {
  6797. if (!this.socialInitialized.steamCommunity) {
  6798. this.steamTaskType.steamCommunity = true;
  6799. pro.push(this.#bind('steamCommunity', this.social.steam.init('community')));
  6800. }
  6801. }
  6802. }
  6803. }
  6804. if (tasks.links && tasks.links.length > 0) {
  6805. this.social.visitLink = visitLink;
  6806. }
  6807. return await Promise.all(pro).then(result => {
  6808. let checked = true;
  6809. for (const data of result) {
  6810. if (data.result) {
  6811. this.socialInitialized[data.name] = data.result;
  6812. } else {
  6813. checked = false;
  6814. }
  6815. }
  6816. return checked;
  6817. });
  6818. } catch (error) {
  6819. throwError(error, 'Website.initSocial');
  6820. return false;
  6821. }
  6822. }
  6823. uniqueTasks(allTasks) {
  6824. try {
  6825. const result = {};
  6826. for (const [ social, types ] of Object.entries(allTasks)) {
  6827. result[social] = {};
  6828. for (const [ type, tasks ] of Object.entries(types)) {
  6829. result[social][type] = unique(tasks);
  6830. }
  6831. }
  6832. return result;
  6833. } catch (error) {
  6834. throwError(error, 'Website.uniqueTasks');
  6835. return allTasks;
  6836. }
  6837. }
  6838. async toggleTask(action) {
  6839. try {
  6840. if (!this.initialized && !this.init()) {
  6841. return false;
  6842. }
  6843. if (!await this.classifyTask(action)) {
  6844. return false;
  6845. }
  6846. await this.initSocial(action);
  6847. const pro = [];
  6848. const doTask = action === 'do';
  6849. const tasks = doTask ? this.undoneTasks : this.socialTasks;
  6850. if (this.socialInitialized.discord === true && this.social.discord) {
  6851. pro.push(this.social.discord.toggle({
  6852. doTask: doTask,
  6853. ...tasks.discord
  6854. }));
  6855. }
  6856. if (this.socialInitialized.instagram === true && this.social.instagram) {
  6857. pro.push(this.social.instagram.toggle({
  6858. doTask: doTask,
  6859. ...tasks.instagram
  6860. }));
  6861. }
  6862. if (this.socialInitialized.reddit === true && this.social.reddit) {
  6863. pro.push(this.social.reddit.toggle({
  6864. doTask: doTask,
  6865. ...tasks.reddit
  6866. }));
  6867. }
  6868. if (this.socialInitialized.twitch === true && this.social.twitch) {
  6869. pro.push(this.social.twitch.toggle({
  6870. doTask: doTask,
  6871. ...tasks.twitch
  6872. }));
  6873. }
  6874. if (this.socialInitialized.twitter === true && this.social.twitter) {
  6875. pro.push(this.social.twitter.toggle({
  6876. doTask: doTask,
  6877. ...tasks.twitter
  6878. }));
  6879. }
  6880. if (this.socialInitialized.vk === true && this.social.vk) {
  6881. pro.push(this.social.vk.toggle({
  6882. doTask: doTask,
  6883. ...tasks.vk
  6884. }));
  6885. }
  6886. if (this.socialInitialized.youtube === true && this.social.youtube) {
  6887. pro.push(this.social.youtube.toggle({
  6888. doTask: doTask,
  6889. ...tasks.youtube
  6890. }));
  6891. }
  6892. if ((this.steamTaskType.steamCommunity ? this.socialInitialized.steamCommunity === true : true) && (this.steamTaskType.steamStore ? this.socialInitialized.steamStore === true : true) && this.social.steam) {
  6893. pro.push(this.social.steam.toggle({
  6894. doTask: doTask,
  6895. ...tasks.steam
  6896. }));
  6897. }
  6898. if (this.social.visitLink && tasks.links && doTask) {
  6899. for (const link of tasks.links) {
  6900. pro.push(this.social.visitLink(link));
  6901. }
  6902. }
  6903. if (doTask && tasks.extra && this.extraDoTask) {
  6904. const hasExtra = Object.values(tasks.extra).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6905. if (hasExtra) {
  6906. pro.push(this.extraDoTask(tasks.extra));
  6907. }
  6908. }
  6909. await Promise.all(pro);
  6910. scripts_echoLog({}).success(i18n('allTasksComplete'));
  6911. return true;
  6912. } catch (error) {
  6913. throwError(error, 'Website.toggleTask');
  6914. return false;
  6915. }
  6916. }
  6917. async doTask() {
  6918. try {
  6919. return await this.toggleTask('do');
  6920. } catch (error) {
  6921. throwError(error, 'Website.doTask');
  6922. return false;
  6923. }
  6924. }
  6925. async undoTask() {
  6926. try {
  6927. return await this.toggleTask('undo');
  6928. } catch (error) {
  6929. throwError(error, 'Website.undoTask');
  6930. return false;
  6931. }
  6932. }
  6933. }
  6934. const website_Website = Website;
  6935. const defaultTasksTemplate = {
  6936. steam: {
  6937. groupLinks: [],
  6938. wishlistLinks: [],
  6939. curatorLinks: [],
  6940. followLinks: []
  6941. },
  6942. discord: {
  6943. serverLinks: []
  6944. },
  6945. vk: {
  6946. nameLinks: []
  6947. },
  6948. extra: {
  6949. website: []
  6950. }
  6951. };
  6952. const defaultTasks = JSON.stringify(defaultTasksTemplate);
  6953. class FreeAnyWhere extends website_Website {
  6954. name = 'FreeAnyWhere';
  6955. tasks = [];
  6956. socialTasks = JSON.parse(defaultTasks);
  6957. undoneTasks = JSON.parse(defaultTasks);
  6958. buttons = [ 'doTask', 'undoTask', 'verifyTask', 'getKey' ];
  6959. static test() {
  6960. return window.location.host === 'freeanywhere.net';
  6961. }
  6962. async init() {
  6963. try {
  6964. const logStatus = scripts_echoLog({
  6965. text: i18n('initing')
  6966. });
  6967. debug('检测登录按钮');
  6968. if ($('div.header__login a[href*=logout]').length === 0) {
  6969. window.open('https://freeanywhere.net/game.php?steam_login', '_self');
  6970. logStatus.warning(i18n('needLogin'));
  6971. return false;
  6972. }
  6973. debug('检测是否为登录页面');
  6974. if (window.location.href.includes('/login')) {
  6975. logStatus.warning(i18n('needLogin'));
  6976. return false;
  6977. }
  6978. this.initialized = true;
  6979. logStatus.success();
  6980. return true;
  6981. } catch (error) {
  6982. throwError(error, 'Freeanywhere.init');
  6983. return false;
  6984. }
  6985. }
  6986. async classifyTask(action) {
  6987. try {
  6988. const logStatus = scripts_echoLog({
  6989. text: i18n('getTasksInfo')
  6990. });
  6991. if (action === 'undo') {
  6992. this.socialTasks = GM_getValue(`fawTasks-${this.giveawayId}`)?.tasks || JSON.parse(defaultTasks);
  6993. }
  6994. const tasks = $('div.game__content-tasks__task').map((index, element) => ({
  6995. id: $(element).attr('data-id'),
  6996. social: $(element).find('div.task-img img').attr('alt'),
  6997. link: $(element).find('div.task-link a').attr('href'),
  6998. title: $(element).find('div.task-link').text().trim(),
  6999. type: $(element).attr('data-type'),
  7000. isSuccess: $(element).hasClass('done')
  7001. })).toArray();
  7002. if (tasks.length === 0) {
  7003. logStatus.success();
  7004. return false;
  7005. }
  7006. if (action === 'verify') {
  7007. this.tasks = [];
  7008. }
  7009. for (const task of tasks) {
  7010. debug('任务分类', task);
  7011. const {
  7012. id,
  7013. social,
  7014. title,
  7015. type,
  7016. link,
  7017. isSuccess
  7018. } = task;
  7019. const taskInfo = {
  7020. id: id,
  7021. title: title,
  7022. social: social,
  7023. type: type
  7024. };
  7025. if (action === 'verify' && !isSuccess) {
  7026. this.tasks.push(taskInfo);
  7027. continue;
  7028. }
  7029. switch (type) {
  7030. case 'steam_account_verify':
  7031. break;
  7032.  
  7033. case 'steam_game_wishlist':
  7034. if (action === 'undo' && link) {
  7035. this.socialTasks.steam.wishlistLinks.push(link);
  7036. }
  7037. if (action === 'do' && !isSuccess && link) {
  7038. this.undoneTasks.steam.wishlistLinks.push(link);
  7039. }
  7040. break;
  7041.  
  7042. case 'steam_group_sub':
  7043. if (action === 'undo' && link) {
  7044. this.socialTasks.steam.groupLinks.push(link);
  7045. }
  7046. if (action === 'do' && !isSuccess && link) {
  7047. this.undoneTasks.steam.groupLinks.push(link);
  7048. }
  7049. break;
  7050.  
  7051. case 'site_visit':
  7052. if (action === 'do' && !isSuccess) {
  7053. this.undoneTasks.extra.website.push(`id=${id}&type=${type}&task=true`);
  7054. }
  7055. break;
  7056.  
  7057. case 'vk_community_sub':
  7058. if (action === 'undo' && link) {
  7059. this.socialTasks.vk.nameLinks.push(link);
  7060. }
  7061. if (action === 'do' && !isSuccess && link) {
  7062. this.undoneTasks.vk.nameLinks.push(link);
  7063. }
  7064. break;
  7065.  
  7066. case 'vk_post_like':
  7067. if (action === 'undo' && link) {
  7068. this.socialTasks.vk.nameLinks.push(`${link}&action=like`);
  7069. }
  7070. if (action === 'do' && !isSuccess && link) {
  7071. this.undoneTasks.vk.nameLinks.push(`${link}&action=like`);
  7072. }
  7073. break;
  7074.  
  7075. case 'discord_server_sub':
  7076. if (action === 'undo' && link) {
  7077. this.socialTasks.discord.serverLinks.push(link);
  7078. }
  7079. if (action === 'do' && !isSuccess && link) {
  7080. this.undoneTasks.discord.serverLinks.push(link);
  7081. }
  7082. break;
  7083.  
  7084. case 'telegram_channel_sub':
  7085. scripts_echoLog({}).warning(`${i18n('tgTaskNotice')}`);
  7086. break;
  7087.  
  7088. case 'none':
  7089. scripts_echoLog({}).warning(`${i18n('notConnect')}`);
  7090. break;
  7091.  
  7092. default:
  7093. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${type}`);
  7094. break;
  7095. }
  7096. }
  7097. logStatus.success();
  7098. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7099. this.socialTasks = this.uniqueTasks(this.socialTasks);
  7100. if (window.DEBUG) {
  7101. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7102. }
  7103. GM_setValue(`fawTasks-${this.giveawayId}`, {
  7104. tasks: this.socialTasks,
  7105. time: new Date().getTime()
  7106. });
  7107. return true;
  7108. } catch (error) {
  7109. throwError(error, 'Freeanywhere.classifyTask');
  7110. return false;
  7111. }
  7112. }
  7113. async verifyTask() {
  7114. try {
  7115. if (!this.initialized && !this.init()) {
  7116. debug('未初始化');
  7117. return false;
  7118. }
  7119. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  7120. debug('任务列表为空', this.tasks);
  7121. return false;
  7122. }
  7123. const pro = [];
  7124. for (const task of this.tasks) {
  7125. pro.push(this.#verify(task));
  7126. await delay(1e3);
  7127. }
  7128. await Promise.all(pro);
  7129. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7130. return !!await this.getKey(true);
  7131. } catch (error) {
  7132. throwError(error, 'Freeanywhere.verifyTask');
  7133. return false;
  7134. }
  7135. }
  7136. async extraDoTask({
  7137. website
  7138. }) {
  7139. try {
  7140. const pro = [];
  7141. for (const link of website) {
  7142. pro.push(this.#doVisitWebsite(link));
  7143. }
  7144. return Promise.all(pro).then(() => true);
  7145. } catch (error) {
  7146. throwError(error, 'FreeAnyWhere.extraDoTask');
  7147. return false;
  7148. }
  7149. }
  7150. async #doVisitWebsite(link) {
  7151. try {
  7152. const logStatus = scripts_echoLog({
  7153. text: i18n('visitingLink')
  7154. });
  7155. const {
  7156. result,
  7157. statusText,
  7158. status,
  7159. data
  7160. } = await tools_httpRequest({
  7161. url: 'https://freeanywhere.net/php/task_site_visit_done.php',
  7162. method: 'POST',
  7163. headers: {
  7164. 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  7165. },
  7166. data: link
  7167. });
  7168. if (result === 'Success') {
  7169. logStatus.success();
  7170. return true;
  7171. }
  7172. logStatus.error(`${result}:${statusText}(${status})`);
  7173. return false;
  7174. } catch (error) {
  7175. throwError(error, 'FreeAnyWhere.doVisitWebsite');
  7176. return false;
  7177. }
  7178. }
  7179. async getKey(initialized) {
  7180. try {
  7181. if (!initialized && !this.initialized && !this.init()) {
  7182. debug('未初始化');
  7183. return false;
  7184. }
  7185. const logStatus = scripts_echoLog({
  7186. text: i18n('gettingKey')
  7187. });
  7188. const {
  7189. result,
  7190. statusText,
  7191. status,
  7192. data
  7193. } = await tools_httpRequest({
  7194. url: 'https://freeanywhere.net/php/user_get_key.php',
  7195. method: 'POST'
  7196. });
  7197. if (result === 'Success') {
  7198. if (data?.responseText.indexOf('bad') !== -1 || data?.responseText.length > 50) {
  7199. logStatus.error(data?.responseText);
  7200. return false;
  7201. }
  7202. logStatus.success();
  7203. scripts_echoLog({}).success(data.responseText);
  7204. return data.responseText;
  7205. }
  7206. logStatus.error(`${result}:${statusText}(${status})`);
  7207. return false;
  7208. } catch (error) {
  7209. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7210. return false;
  7211. }
  7212. }
  7213. #getGiveawayId() {
  7214. try {
  7215. const giveawayId = new URLSearchParams(window.location.search).get('n');
  7216. if (giveawayId) {
  7217. this.giveawayId = giveawayId;
  7218. return true;
  7219. }
  7220. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  7221. return false;
  7222. } catch (error) {
  7223. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7224. return false;
  7225. }
  7226. }
  7227. async #verify(task) {
  7228. try {
  7229. const logStatus = scripts_echoLog({
  7230. html: `<li>${i18n('verifyingTask')}${task.title.trim()}...<font></font></li>`
  7231. });
  7232. const {
  7233. result,
  7234. statusText,
  7235. status,
  7236. data
  7237. } = await tools_httpRequest({
  7238. url: 'https://freeanywhere.net/php/user_task_update.php',
  7239. method: 'POST',
  7240. headers: {
  7241. 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  7242. },
  7243. data: `id=${task.id}&type=${task.type}`
  7244. });
  7245. if (result === 'Success') {
  7246. if (data?.responseText.trim() === 'good') {
  7247. logStatus.success();
  7248. return true;
  7249. }
  7250. debug('任务验证结果', data?.response);
  7251. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7252. return false;
  7253. }
  7254. logStatus.error(`${result}:${statusText}(${status})`);
  7255. return false;
  7256. } catch (error) {
  7257. throwError(error, 'Freeanywhere.verify');
  7258. return false;
  7259. }
  7260. }
  7261. async #checkLeftKey() {
  7262. try {
  7263. if (!globalOptions.other.checkLeftKey) {
  7264. return true;
  7265. }
  7266. debug('检测剩余Key');
  7267. const {
  7268. data
  7269. } = await tools_httpRequest({
  7270. url: 'https://freeanywhere.net/api/v1/widget/?format=json',
  7271. method: 'GET',
  7272. dataType: 'json',
  7273. headers: {
  7274. authorization: `Token ${window.localStorage.getItem('token')}`
  7275. }
  7276. });
  7277. if (data?.response?.giveaways.find(giveaway => `${giveaway?.id}` === this.giveawayId)) {
  7278. return true;
  7279. }
  7280. await external_Swal_default().fire({
  7281. icon: 'warning',
  7282. title: i18n('notice'),
  7283. text: i18n('noKeysLeft'),
  7284. confirmButtonText: i18n('confirm'),
  7285. cancelButtonText: i18n('cancel'),
  7286. showCancelButton: true
  7287. }).then(({
  7288. value
  7289. }) => {
  7290. if (value) {
  7291. window.close();
  7292. }
  7293. });
  7294. return true;
  7295. } catch (error) {
  7296. throwError(error, 'Giveawaysu.checkLeftKey');
  7297. return false;
  7298. }
  7299. }
  7300. }
  7301. const Freeanywhere = FreeAnyWhere;
  7302. const Giveawaysu_defaultTasks = {
  7303. steam: {
  7304. groupLinks: [],
  7305. wishlistLinks: [],
  7306. curatorLinks: [],
  7307. curatorLikeLinks: [],
  7308. followLinks: [],
  7309. forumLinks: [],
  7310. announcementLinks: [],
  7311. workshopVoteLinks: [],
  7312. playtestLinks: []
  7313. },
  7314. discord: {
  7315. serverLinks: []
  7316. },
  7317. instagram: {
  7318. userLinks: []
  7319. },
  7320. vk: {
  7321. nameLinks: []
  7322. },
  7323. twitch: {
  7324. channelLinks: []
  7325. },
  7326. reddit: {
  7327. redditLinks: []
  7328. },
  7329. youtube: {
  7330. channelLinks: [],
  7331. likeLinks: []
  7332. },
  7333. twitter: {
  7334. userLinks: [],
  7335. retweetLinks: []
  7336. }
  7337. };
  7338. class GiveawaySu extends website_Website {
  7339. name = 'GiveawaySu';
  7340. socialTasks = Giveawaysu_defaultTasks;
  7341. undoneTasks = Giveawaysu_defaultTasks;
  7342. buttons = [ 'doTask', 'undoTask' ];
  7343. static test() {
  7344. return /^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(window.location.href);
  7345. }
  7346. async after() {
  7347. try {
  7348. if (!this.#checkLogin()) {
  7349. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7350. }
  7351. if (!await this.#checkLeftKey()) {
  7352. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7353. }
  7354. scripts_echoLog({}).warning(i18n('gsNotice'));
  7355. } catch (error) {
  7356. throwError(error, 'Giveawaysu.after');
  7357. }
  7358. }
  7359. init() {
  7360. try {
  7361. const logStatus = scripts_echoLog({
  7362. text: i18n('initing')
  7363. });
  7364. if ($('a.steam-login').length > 0) {
  7365. window.open('/steam/redirect', '_self');
  7366. logStatus.warning(i18n('needLogin'));
  7367. return false;
  7368. }
  7369. if (!this.#getGiveawayId()) {
  7370. return false;
  7371. }
  7372. this.initialized = true;
  7373. logStatus.success();
  7374. return true;
  7375. } catch (error) {
  7376. throwError(error, 'Giveawaysu.init');
  7377. return false;
  7378. }
  7379. }
  7380. async classifyTask(action) {
  7381. try {
  7382. const logStatus = scripts_echoLog({
  7383. text: i18n('getTasksInfo')
  7384. });
  7385. if (action === 'undo') {
  7386. this.socialTasks = GM_getValue(`gasTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  7387. return true;
  7388. }
  7389. const pro = [];
  7390. const tasks = $('#actions tr');
  7391. if ($('div.bind-discord').is(':visible')) {
  7392. $('div.bind-discord a')[0].click();
  7393. }
  7394. if ($('div.bind-twitch').is(':visible')) {
  7395. $('div.bind-twitch a')[0].click();
  7396. }
  7397. for (const task of tasks) {
  7398. pro.push(new Promise(resolve => {
  7399. const td = $(task).find('td:not(".hidden")');
  7400. const colorfulTask = td.eq(1).find('a:not([data-trigger="link"])');
  7401. const colorlessTask = td.eq(2).find('a:not([data-trigger="link"])');
  7402. const taskDes = colorfulTask.length > 0 ? colorfulTask : colorlessTask;
  7403. const taskIcon = td.eq(0).find('i').attr('class') || '';
  7404. const taskName = taskDes.text().trim();
  7405. if (taskIcon.includes('ban') || /disable adblock/gi.test(taskName)) {
  7406. return resolve(true);
  7407. }
  7408. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  7409. if (!taskLink) {
  7410. return resolve(false);
  7411. }
  7412. if (taskIcon.includes('steam') && /join/gi.test(taskName)) {
  7413. this.undoneTasks.steam.groupLinks.push(taskLink);
  7414. } else if (/like.*announcement/gi.test(taskName)) {
  7415. this.undoneTasks.steam.announcementLinks.push(taskLink);
  7416. } else if (/(follow|subscribe).*curator/gim.test(taskName) && /^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  7417. this.undoneTasks.steam.curatorLinks.push(taskLink);
  7418. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  7419. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  7420. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  7421. this.undoneTasks.steam.forumLinks.push(taskLink);
  7422. } else if (taskIcon.includes('thumbs-up') && /^https?:\/\/steamcommunity\.com\/sharedfiles\/filedetails\/\?id=[\d]+/.test(taskLink)) {
  7423. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7424. } else if (taskIcon.includes('plus') && /request.*playtest/gim.test(taskName)) {
  7425. this.undoneTasks.steam.playtestLinks.push(taskLink);
  7426. } else if (taskIcon.includes('discord') || /join.*discord/gim.test(taskName)) {
  7427. this.undoneTasks.discord.serverLinks.push(taskLink);
  7428. } else if (taskIcon.includes('instagram') || /follow.*instagram/gim.test(taskName)) {
  7429. this.undoneTasks.instagram.userLinks.push(taskLink);
  7430. } else if (taskIcon.includes('twitch') || /follow.*twitch.*channel/gim.test(taskName)) {
  7431. this.undoneTasks.twitch.channelLinks.push(taskLink);
  7432. } else if (taskIcon.includes('reddit') || /subscribe.*subreddit/gim.test(taskName) || /follow.*reddit/gim.test(taskName)) {
  7433. this.undoneTasks.reddit.redditLinks.push(taskLink);
  7434. } else if (/watch.*art/gim.test(taskName)) {
  7435. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7436. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  7437. this.undoneTasks.youtube.channelLinks.push(taskLink);
  7438. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  7439. this.undoneTasks.youtube.likeLinks.push(taskLink);
  7440. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  7441. this.undoneTasks.vk.nameLinks.push(taskLink);
  7442. } else {
  7443. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  7444. if (/wishlist.*game|add.*wishlist/gim.test(taskName)) {
  7445. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  7446. }
  7447. if (/follow.*button/gim.test(taskName)) {
  7448. this.undoneTasks.steam.followLinks.push(taskLink);
  7449. }
  7450. }
  7451. }
  7452. resolve(true);
  7453. }).catch(error => {
  7454. throwError(error, 'Giveawaysu.classifyTask->getRedirectLink');
  7455. return false;
  7456. });
  7457. }));
  7458. }
  7459. await Promise.all(pro);
  7460. logStatus.success();
  7461. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7462. this.socialTasks = this.undoneTasks;
  7463. if (window.DEBUG) {
  7464. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7465. }
  7466. GM_setValue(`gasTasks-${this.giveawayId}`, {
  7467. tasks: this.socialTasks,
  7468. time: new Date().getTime()
  7469. });
  7470. return true;
  7471. } catch (error) {
  7472. throwError(error, 'Giveawaysu.classifyTask');
  7473. return false;
  7474. }
  7475. }
  7476. #checkLogin() {
  7477. try {
  7478. if (!globalOptions.other.checkLogin) {
  7479. return true;
  7480. }
  7481. if ($('a.steam-login').length > 0) {
  7482. window.open('/steam/redirect', '_self');
  7483. }
  7484. return true;
  7485. } catch (error) {
  7486. throwError(error, 'Giveawaysu.checkLogin');
  7487. return false;
  7488. }
  7489. }
  7490. async #checkLeftKey() {
  7491. try {
  7492. if (!globalOptions.other.checkLeftKey) {
  7493. return true;
  7494. }
  7495. if ($('.giveaway-ended').length > 0 && $('.giveaway-key').length === 0) {
  7496. await external_Swal_default().fire({
  7497. icon: 'warning',
  7498. title: i18n('notice'),
  7499. text: i18n('noKeysLeft'),
  7500. confirmButtonText: i18n('confirm'),
  7501. cancelButtonText: i18n('cancel'),
  7502. showCancelButton: true
  7503. }).then(({
  7504. value
  7505. }) => {
  7506. if (value) {
  7507. window.close();
  7508. }
  7509. });
  7510. }
  7511. return true;
  7512. } catch (error) {
  7513. throwError(error, 'Giveawaysu.checkLeftKey');
  7514. return false;
  7515. }
  7516. }
  7517. #getGiveawayId() {
  7518. try {
  7519. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  7520. if (giveawayId) {
  7521. this.giveawayId = giveawayId;
  7522. return true;
  7523. }
  7524. scripts_echoLog({
  7525. text: i18n('getFailed', 'GiveawayId')
  7526. });
  7527. return false;
  7528. } catch (error) {
  7529. throwError(error, 'Giveawaysu.getGiveawayId');
  7530. return false;
  7531. }
  7532. }
  7533. }
  7534. class Indiedb {
  7535. name = 'Indiedb';
  7536. buttons = [ 'doTask' ];
  7537. static test() {
  7538. return window.location.host === 'www.indiedb.com';
  7539. }
  7540. async after() {
  7541. try {
  7542. if (!this.#checkLogin()) {
  7543. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7544. }
  7545. if (!await this.#checkLeftKey()) {
  7546. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7547. }
  7548. } catch (error) {
  7549. throwError(error, 'Indiedb.after');
  7550. }
  7551. }
  7552. async doTask() {
  7553. try {
  7554. if (!await this.#join()) {
  7555. return false;
  7556. }
  7557. return await this.#do();
  7558. } catch (error) {
  7559. throwError(error, 'Indiedb.doTask');
  7560. return false;
  7561. }
  7562. }
  7563. async #join() {
  7564. try {
  7565. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7566. scripts_echoLog({}).error(i18n('needLogin'));
  7567. return false;
  7568. }
  7569. const currentoption = $('a.buttonenter.buttongiveaway');
  7570. if (/join giveaway/gim.test(currentoption.text())) {
  7571. const logStatus = scripts_echoLog({
  7572. text: `${i18n('joiningGiveaway')}...`
  7573. });
  7574. const {
  7575. result,
  7576. statusText,
  7577. status,
  7578. data
  7579. } = await tools_httpRequest({
  7580. url: currentoption.attr('href'),
  7581. method: 'POST',
  7582. data: 'ajax=t',
  7583. dataType: 'json',
  7584. headers: {
  7585. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  7586. Accept: 'application/json, text/javascript, */*; q=0.01',
  7587. Origin: window.location.origin,
  7588. referer: window.location.href
  7589. }
  7590. });
  7591. if (result === 'Success') {
  7592. if (data?.status === 200) {
  7593. if (data.response?.success) {
  7594. currentoption.addClass('buttonentered').text('Success - Giveaway joined');
  7595. $('#giveawaysjoined').slideDown();
  7596. $('#giveawaysrecommend').slideDown();
  7597. logStatus.success(`Success${data.response?.text ? `:${data.response?.text}` : ''}`);
  7598. return true;
  7599. }
  7600. logStatus.error(`Error${data.response?.text ? `:${data.response?.text}` : ''}`);
  7601. return false;
  7602. }
  7603. if (await this.#join2()) {
  7604. logStatus.success('Success');
  7605. return true;
  7606. }
  7607. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7608. return false;
  7609. }
  7610. logStatus.error(`${result}:${statusText}(${status})`);
  7611. return false;
  7612. } else if (/success/gim.test($('a.buttonenter.buttongiveaway').text())) {
  7613. return true;
  7614. }
  7615. scripts_echoLog({}).warning(i18n('needJoinGiveaway'));
  7616. return false;
  7617. } catch (error) {
  7618. throwError(error, 'Indiedb.join');
  7619. return false;
  7620. }
  7621. }
  7622. async #join2() {
  7623. try {
  7624. return await new Promise(resolve => {
  7625. const targetNode = document.getElementById('giveawaysjoined');
  7626. const config = {
  7627. attributes: true
  7628. };
  7629. const observer = new MutationObserver(() => {
  7630. if ($('#giveawaysjoined').is(':visible')) {
  7631. resolve(true);
  7632. observer.disconnect();
  7633. }
  7634. });
  7635. observer.observe(targetNode, config);
  7636. $('a.buttonenter.buttongiveaway')[0]?.click();
  7637. setTimeout(() => {
  7638. resolve(false);
  7639. observer.disconnect();
  7640. }, 3e4);
  7641. });
  7642. } catch (error) {
  7643. throwError(error, 'Indiedb.join2');
  7644. return false;
  7645. }
  7646. }
  7647. async #do() {
  7648. try {
  7649. const id = $('script').map((index, script) => {
  7650. if (/\$\(document\)/gim.test(script.innerHTML)) {
  7651. return [ script.innerHTML.match(/"\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0], script.innerHTML.match(/"\/newsletter\/ajax\/subscribeprofile\/optin\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0] ];
  7652. }
  7653. return null;
  7654. });
  7655. if (id.length === 2) {
  7656. const pro = [];
  7657. const tasks = $('#giveawaysjoined a[class*=promo]');
  7658. for (const task of tasks) {
  7659. const promo = $(task);
  7660. if (!promo.hasClass('buttonentered')) {
  7661. const status = scripts_echoLog({
  7662. text: `${i18n('doing')}:${promo.parents('p').text()}...`
  7663. });
  7664. if (/facebookpromo|twitterpromo|visitpromo/gim.test(task.className)) {
  7665. let text = '';
  7666. if (promo.hasClass('facebookpromo')) {
  7667. text = 'facebookpromo';
  7668. } else if (promo.hasClass('twitterpromo')) {
  7669. text = 'twitterpromo';
  7670. } else {
  7671. text = 'visitpromo';
  7672. }
  7673. pro.push(new Promise(resolve => {
  7674. $.ajax({
  7675. type: 'POST',
  7676. url: urlPath(`/giveaways/ajax/${text}/${id[0]}`),
  7677. timeout: 6e4,
  7678. dataType: 'json',
  7679. data: {
  7680. ajax: 't'
  7681. },
  7682. error(response, error, exception) {
  7683. if (window.DEBUG) {
  7684. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7685. response: response,
  7686. error: error,
  7687. exception: exception
  7688. });
  7689. }
  7690. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7691. resolve(true);
  7692. },
  7693. success(response) {
  7694. if (response.success) {
  7695. status.success(`Success:${response.text}`);
  7696. promo.addClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7697. resolve(true);
  7698. } else {
  7699. status.error(`Error:${response.text}`);
  7700. resolve(true);
  7701. }
  7702. }
  7703. });
  7704. }));
  7705. } else if (promo.hasClass('emailoptinpromo')) {
  7706. pro.push(new Promise(resolve => {
  7707. $.ajax({
  7708. type: 'POST',
  7709. url: urlPath(`/newsletter/ajax/subscribeprofile/optin/${id[1]}`),
  7710. timeout: 6e4,
  7711. dataType: 'json',
  7712. data: {
  7713. ajax: 't',
  7714. emailsystoggle: 4
  7715. },
  7716. error(response, error, exception) {
  7717. if (window.DEBUG) {
  7718. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7719. response: response,
  7720. error: error,
  7721. exception: exception
  7722. });
  7723. }
  7724. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7725. resolve(true);
  7726. },
  7727. success(response) {
  7728. if (response.success) {
  7729. status.success(`Success:${response.text}`);
  7730. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7731. resolve(true);
  7732. } else {
  7733. status.error(`Error:${response.text}`);
  7734. resolve(true);
  7735. }
  7736. }
  7737. });
  7738. }));
  7739. } else if (promo.hasClass('watchingpromo')) {
  7740. pro.push(new Promise(resolve => {
  7741. const data = getUrlQuery(promo.attr('href'));
  7742. data.ajax = 't';
  7743. $.ajax({
  7744. type: 'POST',
  7745. url: urlPath(promo.attr('href')?.split(/[?#]/)[0]),
  7746. timeout: 6e4,
  7747. dataType: 'json',
  7748. data: data,
  7749. error(response, error, exception) {
  7750. if (window.DEBUG) {
  7751. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7752. response: response,
  7753. error: error,
  7754. exception: exception
  7755. });
  7756. }
  7757. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7758. resolve(true);
  7759. },
  7760. success(response) {
  7761. if (response.success) {
  7762. status.success(`Success:${response.text}`);
  7763. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7764. resolve(true);
  7765. } else {
  7766. status.error(`Error:${response.text}`);
  7767. resolve(true);
  7768. }
  7769. }
  7770. });
  7771. }));
  7772. } else if (!/the-challenge-of-adblock/gim.test(promo.attr('href'))) {
  7773. pro.push(new Promise(resolve => {
  7774. $.ajax({
  7775. type: 'POST',
  7776. url: urlPath(promo.attr('href')),
  7777. timeout: 6e4,
  7778. dataType: 'json',
  7779. data: {
  7780. ajax: 't'
  7781. },
  7782. error(response, error, exception) {
  7783. if (window.DEBUG) {
  7784. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7785. response: response,
  7786. error: error,
  7787. exception: exception
  7788. });
  7789. }
  7790. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7791. resolve(true);
  7792. },
  7793. success(response) {
  7794. if (response.success) {
  7795. status.success(`Success:${response.text}`);
  7796. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7797. resolve(true);
  7798. } else {
  7799. status.error(`Error:${response.text}`);
  7800. resolve(true);
  7801. }
  7802. }
  7803. });
  7804. }));
  7805. } else {
  7806. status.error(`Error:${i18n('unKnownTaskType')}`);
  7807. }
  7808. }
  7809. }
  7810. await Promise.all(pro);
  7811. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7812. return true;
  7813. }
  7814. scripts_echoLog({}).error(i18n('getFailed', 'TaskId'));
  7815. return false;
  7816. } catch (error) {
  7817. throwError(error, 'Indiedb.classifyTask');
  7818. return false;
  7819. }
  7820. }
  7821. #checkLogin() {
  7822. try {
  7823. if (!globalOptions.other.checkLogin) {
  7824. return true;
  7825. }
  7826. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7827. window.open('/members/login', '_self');
  7828. }
  7829. return true;
  7830. } catch (error) {
  7831. throwError(error, 'Indiedb.checkLogin');
  7832. return false;
  7833. }
  7834. }
  7835. async #checkLeftKey() {
  7836. try {
  7837. if (!globalOptions.other.checkLeftKey) {
  7838. return true;
  7839. }
  7840. if ($('a.buttonenter:contains("next time"), a.buttonenter:contains("Giveaway is closed")').length > 0) {
  7841. await external_Swal_default().fire({
  7842. icon: 'warning',
  7843. title: i18n('notice'),
  7844. text: i18n('giveawayEnded'),
  7845. confirmButtonText: i18n('confirm'),
  7846. cancelButtonText: i18n('cancel'),
  7847. showCancelButton: true
  7848. }).then(({
  7849. value
  7850. }) => {
  7851. if (value) {
  7852. window.close();
  7853. }
  7854. });
  7855. }
  7856. return true;
  7857. } catch (error) {
  7858. throwError(error, 'Indiedb.checkLeftKey');
  7859. return false;
  7860. }
  7861. }
  7862. }
  7863. const website_Indiedb = Indiedb;
  7864. const Keyhub_defaultTasksTemplate = {
  7865. steam: {
  7866. groupLinks: [],
  7867. officialGroupLinks: [],
  7868. wishlistLinks: [],
  7869. curatorLinks: []
  7870. },
  7871. discord: {
  7872. serverLinks: []
  7873. },
  7874. extra: {
  7875. videoTasks: []
  7876. },
  7877. links: []
  7878. };
  7879. const Keyhub_defaultTasks = JSON.stringify(Keyhub_defaultTasksTemplate);
  7880. class Keyhub extends website_Website {
  7881. name = 'Keyhub';
  7882. socialTasks = JSON.parse(Keyhub_defaultTasks);
  7883. undoneTasks = JSON.parse(Keyhub_defaultTasks);
  7884. buttons = [ 'doTask', 'undoTask' ];
  7885. static test() {
  7886. return window.location.host === 'key-hub.eu';
  7887. }
  7888. async after() {
  7889. try {
  7890. if (!this.#checkLogin()) {
  7891. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7892. }
  7893. if (!await this.#checkLeftKey()) {
  7894. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7895. }
  7896. $('.NSFW').hide();
  7897. } catch (error) {
  7898. throwError(error, 'Keyhub.after');
  7899. }
  7900. }
  7901. init() {
  7902. try {
  7903. const logStatus = scripts_echoLog({
  7904. text: i18n('initing')
  7905. });
  7906. if ($('a[href*="/connect/steam"]').length > 0) {
  7907. window.open('/connect/steam', '_self');
  7908. logStatus.warning(i18n('needLogin'));
  7909. return false;
  7910. }
  7911. if (!this.#getGiveawayId()) {
  7912. return false;
  7913. }
  7914. $('#VPNoverlay').hide();
  7915. $('#mainArticleSection').show();
  7916. this.initialized = true;
  7917. logStatus.success();
  7918. return true;
  7919. } catch (error) {
  7920. throwError(error, 'Keyhub.init');
  7921. return false;
  7922. }
  7923. }
  7924. async classifyTask(action) {
  7925. try {
  7926. const logStatus = scripts_echoLog({
  7927. text: i18n('getTasksInfo')
  7928. });
  7929. if (action === 'undo') {
  7930. this.socialTasks = GM_getValue(`khTasks-${this.giveawayId}`)?.tasks || JSON.parse(Keyhub_defaultTasks);
  7931. }
  7932. const tasks = $('.task:not(".googleads")').filter((index, element) => action === 'do' ? $(element).find('i.fa-check-circle:visible').length === 0 : true).find('a');
  7933. for (const task of tasks) {
  7934. let link = $(task).attr('href');
  7935. const taskDes = $(task).text().trim();
  7936. if (!link) {
  7937. continue;
  7938. }
  7939. if (/\/away\?data=/.test(link) || /steamcommunity\.com\/gid\//.test(link)) {
  7940. link = await getRedirectLink(link) || link;
  7941. }
  7942. if (/https?:\/\/key-hub\.eu\/connect\/discord/.test(link)) {
  7943. GM_openInTab(link, {
  7944. active: true
  7945. });
  7946. } else if (/steamcommunity\.com\/groups\//.test(link)) {
  7947. if (action === 'undo') {
  7948. this.socialTasks.steam.groupLinks.push(link);
  7949. }
  7950. if (action === 'do') {
  7951. this.undoneTasks.steam.groupLinks.push(link);
  7952. }
  7953. } else if (/steamcommunity\.com\/games\/[\d]+/.test(link)) {
  7954. if (action === 'undo') {
  7955. this.socialTasks.steam.officialGroupLinks.push(link);
  7956. }
  7957. if (action === 'do') {
  7958. this.undoneTasks.steam.officialGroupLinks.push(link);
  7959. }
  7960. } else if (/store\.steampowered\.com\/app\//.test(link) && /wishlist/gim.test(taskDes)) {
  7961. if (action === 'undo') {
  7962. this.socialTasks.steam.wishlistLinks.push(link);
  7963. }
  7964. if (action === 'do') {
  7965. this.undoneTasks.steam.wishlistLinks.push(link);
  7966. }
  7967. } else if (/store\.steampowered\.com\/curator\//.test(link)) {
  7968. if (action === 'undo') {
  7969. this.socialTasks.steam.curatorLinks.push(link);
  7970. }
  7971. if (action === 'do') {
  7972. this.undoneTasks.steam.curatorLinks.push(link);
  7973. }
  7974. } else if (/^https?:\/\/discord\.com\/invite\//.test(link)) {
  7975. if (action === 'undo') {
  7976. this.socialTasks.discord.serverLinks.push(link);
  7977. }
  7978. if (action === 'do') {
  7979. this.undoneTasks.discord.serverLinks.push(link);
  7980. }
  7981. } else if (/^javascript:videoTask.+/.test(link)) {
  7982. if (action === 'do') {
  7983. const taskData = link.match(/javascript:videoTask\('.+?','(.+?)'/)?.[1];
  7984. if (taskData) {
  7985. this.undoneTasks.extra.videoTasks.push(taskData);
  7986. }
  7987. }
  7988. } 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 {
  7989. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  7990. }
  7991. }
  7992. logStatus.success();
  7993. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7994. this.socialTasks = this.uniqueTasks(this.socialTasks);
  7995. if (window.DEBUG) {
  7996. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7997. }
  7998. GM_setValue(`khTasks-${this.giveawayId}`, {
  7999. tasks: this.socialTasks,
  8000. time: new Date().getTime()
  8001. });
  8002. return true;
  8003. } catch (error) {
  8004. throwError(error, 'Keyhub.classifyTask');
  8005. return false;
  8006. }
  8007. }
  8008. async #doScriptTask(data) {
  8009. try {
  8010. const logStatus = scripts_echoLog({
  8011. text: i18n('doingKeyhubTask')
  8012. });
  8013. const {
  8014. result,
  8015. statusText,
  8016. status,
  8017. data: response
  8018. } = await tools_httpRequest({
  8019. url: `/away?data=${data}`,
  8020. method: 'GET',
  8021. headers: {
  8022. origin: 'https://key-hub.eu',
  8023. referer: 'https://key-hub.eu/'
  8024. }
  8025. });
  8026. if (result === 'Success') {
  8027. if (response?.status === 200) {
  8028. logStatus.success();
  8029. return true;
  8030. }
  8031. logStatus.error(`Error:${response?.statusText}(${response?.status})`);
  8032. return false;
  8033. }
  8034. logStatus.error(`${result}:${statusText}(${status})`);
  8035. return false;
  8036. } catch (error) {
  8037. throwError(error, 'Keyhub.doScriptTask');
  8038. return false;
  8039. }
  8040. }
  8041. async extraDoTask({
  8042. videoTasks
  8043. }) {
  8044. try {
  8045. const pro = [];
  8046. for (const data of videoTasks) {
  8047. pro.push(this.#doScriptTask(data));
  8048. }
  8049. return Promise.all(pro).then(() => true);
  8050. } catch (error) {
  8051. throwError(error, 'Keyhub.extraDoTask');
  8052. return false;
  8053. }
  8054. }
  8055. #getGiveawayId() {
  8056. try {
  8057. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  8058. if (giveawayId) {
  8059. this.giveawayId = giveawayId;
  8060. return true;
  8061. }
  8062. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  8063. return false;
  8064. } catch (error) {
  8065. throwError(error, 'Keyhub.getGiveawayId');
  8066. return false;
  8067. }
  8068. }
  8069. async #checkLeftKey() {
  8070. try {
  8071. if (!globalOptions.other.checkLeftKey) {
  8072. return true;
  8073. }
  8074. const leftKey = $('#keysleft').text().trim();
  8075. if (leftKey === '0') {
  8076. await external_Swal_default().fire({
  8077. icon: 'warning',
  8078. title: i18n('notice'),
  8079. text: i18n('noKeysLeft'),
  8080. confirmButtonText: i18n('confirm'),
  8081. cancelButtonText: i18n('cancel'),
  8082. showCancelButton: true
  8083. }).then(({
  8084. value
  8085. }) => {
  8086. if (value) {
  8087. window.close();
  8088. }
  8089. });
  8090. }
  8091. return true;
  8092. } catch (error) {
  8093. throwError(error, 'Keyhub.checkLeftKey');
  8094. return false;
  8095. }
  8096. }
  8097. #checkLogin() {
  8098. try {
  8099. if (!globalOptions.other.checkLogin) {
  8100. return true;
  8101. }
  8102. if ($('a[href*="/connect/steam"]').length > 0) {
  8103. window.open('/connect/steam', '_self');
  8104. }
  8105. return true;
  8106. } catch (error) {
  8107. throwError(error, 'Keyhub.checkLogin');
  8108. return false;
  8109. }
  8110. }
  8111. }
  8112. const website_Keyhub = Keyhub;
  8113. const Givekey_defaultTasksTemplate = {
  8114. steam: {
  8115. groupLinks: [],
  8116. wishlistLinks: [],
  8117. curatorLinks: [],
  8118. curatorLikeLinks: []
  8119. },
  8120. twitter: {
  8121. userLinks: []
  8122. },
  8123. vk: {
  8124. nameLinks: []
  8125. },
  8126. discord: {
  8127. serverLinks: []
  8128. }
  8129. };
  8130. const Givekey_defaultTasks = JSON.stringify(Givekey_defaultTasksTemplate);
  8131. class Givekey extends website_Website {
  8132. name = 'Givekey';
  8133. tasks = [];
  8134. socialTasks = JSON.parse(Givekey_defaultTasks);
  8135. undoneTasks = JSON.parse(Givekey_defaultTasks);
  8136. userId;
  8137. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8138. static test() {
  8139. return window.location.host === 'givekey.ru';
  8140. }
  8141. async after() {
  8142. try {
  8143. await new Promise(resolve => {
  8144. const checker = setInterval(() => {
  8145. if ($('#navbarDropdown').length > 0) {
  8146. clearInterval(checker);
  8147. resolve(true);
  8148. }
  8149. }, 500);
  8150. });
  8151. if (!await this.#checkLeftKey()) {
  8152. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8153. }
  8154. } catch (error) {
  8155. throwError(error, 'Givekey.after');
  8156. }
  8157. }
  8158. init() {
  8159. try {
  8160. const logStatus = scripts_echoLog({
  8161. text: i18n('initing')
  8162. });
  8163. if ($('a[href*="/auth/steam"]').length > 0) {
  8164. window.open('/auth/steam', '_self');
  8165. logStatus.warning(i18n('needLogin'));
  8166. return false;
  8167. }
  8168. if (!this.#getGiveawayId()) {
  8169. return false;
  8170. }
  8171. const userId = $('meta[name="user-id"]').attr('content');
  8172. if (!userId) {
  8173. logStatus.error(i18n('getFailed', i18n('userId')));
  8174. return false;
  8175. }
  8176. this.userId = userId;
  8177. this.initialized = true;
  8178. logStatus.success();
  8179. return true;
  8180. } catch (error) {
  8181. throwError(error, 'Givekey.init');
  8182. return false;
  8183. }
  8184. }
  8185. async classifyTask(action) {
  8186. try {
  8187. const logStatus = scripts_echoLog({
  8188. text: i18n('getTasksInfo')
  8189. });
  8190. if (action === 'undo') {
  8191. this.socialTasks = GM_getValue(`gkTasks-${this.giveawayId}`)?.tasks || JSON.parse(Givekey_defaultTasks);
  8192. }
  8193. const tasks = $('.card-body:has("button") .row');
  8194. for (const task of tasks) {
  8195. const taskEle = $(task);
  8196. const isSuccess = /Complete/i.test(taskEle.find('button').text().trim());
  8197. if (isSuccess && action !== 'undo') {
  8198. continue;
  8199. }
  8200. const checkButton = taskEle.find('#task_check');
  8201. const taskId = checkButton.attr('data-id');
  8202. if (taskId) {
  8203. this.tasks.push(taskId);
  8204. }
  8205. if (action === 'verify') {
  8206. continue;
  8207. }
  8208. let href = taskEle.find('a').attr('href') || null;
  8209. const text = taskEle.find('a').text().trim();
  8210. const icon = taskEle.find('i');
  8211. if (!href || !text) {
  8212. continue;
  8213. }
  8214. if (/^https?:\/\/givekey\.ru\/giveaway\/[\d]+\/execution_task/.test(href)) {
  8215. href = await getRedirectLink(href);
  8216. }
  8217. if (!href) {
  8218. continue;
  8219. }
  8220. if (/^https?:\/\/vk\.com\//.test(href)) {
  8221. this.socialTasks.vk.nameLinks.push(href);
  8222. if (action === 'do' && !isSuccess) {
  8223. this.undoneTasks.vk.nameLinks.push(href);
  8224. }
  8225. } else if (/^https?:\/\/steamcommunity\.com\/groups/.test(href)) {
  8226. this.socialTasks.steam.groupLinks.push(href);
  8227. if (action === 'do' && !isSuccess) {
  8228. this.undoneTasks.steam.groupLinks.push(href);
  8229. }
  8230. } else if (/^https?:\/\/store\.steampowered\.com\/app\//.test(href)) {
  8231. this.socialTasks.steam.wishlistLinks.push(href);
  8232. if (action === 'do' && !isSuccess) {
  8233. this.undoneTasks.steam.wishlistLinks.push(href);
  8234. }
  8235. } else if (/Subscribe/gi.test(text) && icon.hasClass('fa-steam-square')) {
  8236. if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(href)) {
  8237. this.socialTasks.steam.curatorLinks.push(href);
  8238. if (action === 'do' && !isSuccess) {
  8239. this.undoneTasks.steam.curatorLinks.push(href);
  8240. }
  8241. } else {
  8242. this.socialTasks.steam.curatorLikeLinks.push(href);
  8243. if (action === 'do' && !isSuccess) {
  8244. this.undoneTasks.steam.curatorLikeLinks.push(href);
  8245. }
  8246. }
  8247. } else if (/^https?:\/\/twitter\.com\//.test(href) && /Subscribe/gi.test(text)) {
  8248. this.socialTasks.twitter.userLinks.push(href);
  8249. if (action === 'do' && !isSuccess) {
  8250. this.undoneTasks.twitter.userLinks.push(href);
  8251. }
  8252. } else if (icon.hasClass('fa-discord') || /^https?:\/\/discord\.com\/invite\//.test(href)) {
  8253. this.socialTasks.discord.serverLinks.push(href);
  8254. if (action === 'do' && !isSuccess) {
  8255. this.undoneTasks.discord.serverLinks.push(href);
  8256. }
  8257. } else {
  8258. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${text}(${href})`);
  8259. }
  8260. }
  8261. logStatus.success();
  8262. this.tasks = unique(this.tasks);
  8263. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8264. this.socialTasks = this.uniqueTasks(this.socialTasks);
  8265. if (window.DEBUG) {
  8266. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8267. }
  8268. GM_setValue(`gkTasks-${this.giveawayId}`, {
  8269. tasks: this.socialTasks,
  8270. time: new Date().getTime()
  8271. });
  8272. return true;
  8273. } catch (error) {
  8274. throwError(error, 'Givekey.classifyTask');
  8275. return false;
  8276. }
  8277. }
  8278. async verifyTask() {
  8279. try {
  8280. if (!this.initialized && !this.init()) {
  8281. return false;
  8282. }
  8283. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  8284. return false;
  8285. }
  8286. scripts_echoLog({}).warning(i18n('giveKeyNoticeBefore'));
  8287. const taskLength = this.tasks.length;
  8288. for (let i = 0; i < taskLength; i++) {
  8289. await this.#verify(this.tasks[i]);
  8290. if (i < taskLength - 1) {
  8291. await delay(15e3);
  8292. }
  8293. }
  8294. scripts_echoLog({}).success(i18n('allTasksComplete'));
  8295. scripts_echoLog({
  8296. html: `<li><font class="warning">${i18n('giveKeyNoticeAfter')}</font></li>`
  8297. });
  8298. return true;
  8299. } catch (error) {
  8300. throwError(error, 'Givekey.verifyTask');
  8301. return false;
  8302. }
  8303. }
  8304. async #verify(task) {
  8305. try {
  8306. const logStatus = scripts_echoLog({
  8307. html: `<li>${i18n('verifyingTask')}${task}...<font></font></li>`
  8308. });
  8309. return await new Promise(resolve => {
  8310. $.ajax({
  8311. url: 'https://givekey.ru/giveaway/task',
  8312. method: 'POST',
  8313. data: `id=${task}&user_id=${this.userId}`,
  8314. dataType: 'json',
  8315. headers: {
  8316. 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  8317. },
  8318. success: data => {
  8319. if (data.btn) {
  8320. $(`button[data-id=${this.userId}]`).html(data.btn);
  8321. }
  8322. if (data.status === 'ok') {
  8323. $(`.task_check_${data.id}`).html(`<button class="btn btn-success mb-2 btn-block" disabled>${data.btn}</button>`);
  8324. logStatus.success();
  8325. resolve(true);
  8326. } else if (data.status === 'end') {
  8327. logStatus.success();
  8328. scripts_echoLog({}).success(data.key);
  8329. resolve(true);
  8330. } else {
  8331. logStatus.error(`Error:${data.msg}`);
  8332. resolve(false);
  8333. }
  8334. },
  8335. error: xhr => {
  8336. logStatus.error(`Error:${xhr.statusText}(${xhr.status})`);
  8337. resolve(false);
  8338. }
  8339. });
  8340. });
  8341. } catch (error) {
  8342. throwError(error, 'Givekey.verify');
  8343. return false;
  8344. }
  8345. }
  8346. #getGiveawayId() {
  8347. try {
  8348. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  8349. if (giveawayId) {
  8350. this.giveawayId = giveawayId;
  8351. return true;
  8352. }
  8353. scripts_echoLog({
  8354. text: i18n('getFailed', 'GiveawayId')
  8355. });
  8356. return false;
  8357. } catch (error) {
  8358. throwError(error, 'Givekey.getGiveawayId');
  8359. return false;
  8360. }
  8361. }
  8362. async #checkLeftKey() {
  8363. try {
  8364. if (!globalOptions.other.checkLeftKey) {
  8365. return true;
  8366. }
  8367. if (!$('#keys_count').text()) {
  8368. await external_Swal_default().fire({
  8369. icon: 'warning',
  8370. title: i18n('notice'),
  8371. text: i18n('noKeysLeft'),
  8372. confirmButtonText: i18n('confirm'),
  8373. cancelButtonText: i18n('cancel'),
  8374. showCancelButton: true
  8375. }).then(({
  8376. value
  8377. }) => {
  8378. if (value) {
  8379. window.close();
  8380. }
  8381. });
  8382. }
  8383. return true;
  8384. } catch (error) {
  8385. throwError(error, 'Givekey.checkLeftKey');
  8386. return false;
  8387. }
  8388. }
  8389. }
  8390. const website_Givekey = Givekey;
  8391. class GiveeClub extends GiveawaySu {
  8392. name = 'GiveeClub';
  8393. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8394. static test() {
  8395. return /^https?:\/\/givee\.club\/.*?\/event\/[\d]+/.test(window.location.href);
  8396. }
  8397. async after() {
  8398. try {
  8399. if (!this.#checkLogin()) {
  8400. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8401. }
  8402. if (!await this.#checkLeftKey()) {
  8403. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8404. }
  8405. } catch (error) {
  8406. throwError(error, 'GiveeClub.after');
  8407. }
  8408. }
  8409. init() {
  8410. try {
  8411. const logStatus = scripts_echoLog({
  8412. text: i18n('initing')
  8413. });
  8414. if (!this.#checkLogin()) {
  8415. logStatus.warning(i18n('needLogin'));
  8416. return false;
  8417. }
  8418. if (!this.#getGiveawayId()) {
  8419. return false;
  8420. }
  8421. this.initialized = true;
  8422. logStatus.success();
  8423. return true;
  8424. } catch (error) {
  8425. throwError(error, 'GiveeClub.init');
  8426. return false;
  8427. }
  8428. }
  8429. async classifyTask(action) {
  8430. try {
  8431. const logStatus = scripts_echoLog({
  8432. text: i18n('getTasksInfo')
  8433. });
  8434. if (action === 'undo') {
  8435. this.socialTasks = GM_getValue(`gcTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  8436. return true;
  8437. }
  8438. this.undoneTasks = Giveawaysu_defaultTasks;
  8439. const pro = [];
  8440. const tasks = $('.event-actions tr');
  8441. for (const task of tasks) {
  8442. pro.push(new Promise(resolve => {
  8443. const taskDes = $(task).find('.event-action-label a');
  8444. const taskIcon = $(task).find('.event-action-icon i').attr('class') || '';
  8445. const taskName = taskDes.text().trim();
  8446. const taskType = $(task).find('button[data-type]')?.attr('data-type');
  8447. const taskFinished = $(task).find('.event-action-buttons .btn-success')?.length;
  8448. if (taskIcon.includes('ban') || /AdBlock/i.test(taskName) || taskIcon.includes('envelope') || taskFinished) {
  8449. return resolve(true);
  8450. }
  8451. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  8452. if (!taskLink) {
  8453. return resolve(false);
  8454. }
  8455. if (taskType === 'steam.group.join' && /^https?:\/\/steamcommunity\.com\/groups/.test(taskLink)) {
  8456. this.undoneTasks.steam.groupLinks.push(taskLink);
  8457. } else if (/like.*announcement/gi.test(taskName)) {
  8458. this.undoneTasks.steam.announcementLinks.push(taskLink);
  8459. } else if (taskType === 'steam.game.wishlist' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8460. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  8461. } else if (taskType === 'steam.game.wishlist' && taskDes.attr('data-steam-wishlist-appid')) {
  8462. this.undoneTasks.steam.wishlistLinks.push(`https://store.steampowered.com/app/${taskDes.attr('data-steam-wishlist-appid')}`);
  8463. } else if (taskType === 'steam.game.follow' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8464. this.undoneTasks.steam.followLinks.push(taskLink);
  8465. } else if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  8466. this.undoneTasks.steam.curatorLinks.push(taskLink);
  8467. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  8468. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  8469. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  8470. this.undoneTasks.steam.forumLinks.push(taskLink);
  8471. } else if (taskIcon.includes('discord')) {
  8472. this.undoneTasks.discord.serverLinks.push(taskLink);
  8473. } else if (taskIcon.includes('instagram')) {
  8474. this.undoneTasks.instagram.userLinks.push(taskLink);
  8475. } else if (taskIcon.includes('twitch')) {
  8476. this.undoneTasks.twitch.channelLinks.push(taskLink);
  8477. } else if (taskIcon.includes('reddit')) {
  8478. this.undoneTasks.reddit.redditLinks.push(taskLink);
  8479. } else if (/watch.*art/gim.test(taskName)) {
  8480. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  8481. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  8482. this.undoneTasks.youtube.channelLinks.push(taskLink);
  8483. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  8484. this.undoneTasks.youtube.likeLinks.push(taskLink);
  8485. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  8486. this.undoneTasks.vk.nameLinks.push(taskLink);
  8487. } else if (taskIcon.includes('twitter')) {
  8488. if (/https?:\/\/(twitter|x)\.com\/[^/]+\/?$/gim.test(taskLink)) {
  8489. this.undoneTasks.twitter.userLinks.push(taskLink);
  8490. } else if (/https?:\/\/(twitter|x)\.com\/[^/]+?\/status\/[\d]+/gim.test(taskLink)) {
  8491. this.undoneTasks.twitter.retweetLinks.push(taskLink);
  8492. }
  8493. } else {
  8494. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  8495. if (/follow.*button/gim.test(taskName)) {
  8496. this.undoneTasks.steam.followLinks.push(taskLink);
  8497. }
  8498. }
  8499. }
  8500. resolve(true);
  8501. }).catch(error => {
  8502. throwError(error, 'GiveeClub.classifyTask->getRedirectLink');
  8503. return false;
  8504. });
  8505. }));
  8506. }
  8507. await Promise.all(pro);
  8508. logStatus.success();
  8509. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8510. this.socialTasks = this.undoneTasks;
  8511. if (window.DEBUG) {
  8512. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8513. }
  8514. GM_setValue(`gcTasks-${this.giveawayId}`, {
  8515. tasks: this.socialTasks,
  8516. time: new Date().getTime()
  8517. });
  8518. return true;
  8519. } catch (error) {
  8520. throwError(error, 'GiveeClub.classifyTask');
  8521. return false;
  8522. }
  8523. }
  8524. async verifyTask() {
  8525. try {
  8526. const logStatus = scripts_echoLog({
  8527. text: i18n('giveeClubVerifyNotice')
  8528. });
  8529. const taskButtons = $('.event-actions tr button').has('i.glyphicon-refresh').not('[data-type="user.adblock"]');
  8530. for (const button of taskButtons) {
  8531. button.click();
  8532. if ($(button).attr('data-type') !== 'steam.game.wishlist') {
  8533. await delay(1e3);
  8534. }
  8535. }
  8536. logStatus.warning(i18n('giveeClubVerifyFinished'));
  8537. return true;
  8538. } catch (error) {
  8539. throwError(error, 'Givekey.verifyTask');
  8540. return false;
  8541. }
  8542. }
  8543. #checkLogin() {
  8544. try {
  8545. if (!globalOptions.other.checkLogin) {
  8546. return true;
  8547. }
  8548. if ($('a[href*="/account/auth"]').length > 0) {
  8549. window.open($('a[href*="/account/auth"]').attr('href'), '_self');
  8550. }
  8551. return true;
  8552. } catch (error) {
  8553. throwError(error, 'GiveeClub.checkLogin');
  8554. return false;
  8555. }
  8556. }
  8557. #getGiveawayId() {
  8558. const giveawayId = window.location.href.match(/\/event\/([\d]+)/)?.[1];
  8559. if (giveawayId) {
  8560. this.giveawayId = giveawayId;
  8561. return true;
  8562. }
  8563. scripts_echoLog({
  8564. text: i18n('getFailed', 'GiveawayId')
  8565. });
  8566. return false;
  8567. }
  8568. async #checkLeftKey() {
  8569. try {
  8570. if (!globalOptions.other.checkLeftKey) {
  8571. return true;
  8572. }
  8573. if ($('.event-ended').length > 0 && $('.event-winner').length === 0) {
  8574. await external_Swal_default().fire({
  8575. icon: 'warning',
  8576. title: i18n('notice'),
  8577. text: i18n('giveawayEnded'),
  8578. confirmButtonText: i18n('confirm'),
  8579. cancelButtonText: i18n('cancel'),
  8580. showCancelButton: true
  8581. }).then(({
  8582. value
  8583. }) => {
  8584. if (value) {
  8585. window.close();
  8586. }
  8587. });
  8588. }
  8589. return true;
  8590. } catch (error) {
  8591. throwError(error, 'Giveawaysu.checkLeftKey');
  8592. return false;
  8593. }
  8594. }
  8595. }
  8596. const website_GiveeClub = GiveeClub;
  8597. const defaultOptions = {
  8598. maxPoint: '99999999'
  8599. };
  8600. class OpiumPulses {
  8601. name = 'OpiumPulses';
  8602. options = {
  8603. ...defaultOptions,
  8604. ...GM_getValue('OpiumPulsesOptions')
  8605. };
  8606. maxPoints = 99999999;
  8607. myPoints = 0;
  8608. buttons = [ 'doFreeTask', 'doPointTask' ];
  8609. static test() {
  8610. return window.location.host === 'www.opiumpulses.com';
  8611. }
  8612. async after() {
  8613. try {
  8614. if (!this.#checkLogin()) {
  8615. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8616. }
  8617. this.maxPoints = parseInt(this.options.maxPoint, 10);
  8618. } catch (error) {
  8619. throwError(error, 'OpiumPulses.after');
  8620. }
  8621. }
  8622. async doFreeTask() {
  8623. try {
  8624. this.#toggleTask('FREE');
  8625. } catch (error) {
  8626. throwError(error, 'OpiumPulses.doFreeTask');
  8627. }
  8628. }
  8629. async doPointTask() {
  8630. try {
  8631. this.myPoints = parseInt($('.page-header__nav-func-user-nav-items.points-items').text().match(/[\d]+/gim)?.[0] || '0', 10);
  8632. this.#toggleTask('points');
  8633. } catch (error) {
  8634. throwError(error, 'OpiumPulses.doPointTask');
  8635. }
  8636. }
  8637. async #toggleTask(type) {
  8638. try {
  8639. const items = $(`.giveaways-page-item:contains('${type}'):not(:contains('ENTERED'))`);
  8640. for (const item of items) {
  8641. const needPoints = parseInt($(item).find('.giveaways-page-item-header-points').text().match(/[\d]+/gim)?.[0] || '999999', 10);
  8642. const name = $(item).find('.giveaways-page-item-footer-name').text().trim();
  8643. if (type === 'points' && needPoints > this.myPoints) {
  8644. scripts_echoLog({}).warning(`${i18n('noPoints')}: ${name}`);
  8645. } else if (type === 'points' && !needPoints) {
  8646. scripts_echoLog({}).warning(`${i18n('getNeedPointsFailed')}: ${name}`);
  8647. } else if (!(type === 'points' && needPoints > this.maxPoints)) {
  8648. const logStatus = scripts_echoLog({
  8649. text: `${i18n('joiningLottery')}<a href="${$(item).find('a.giveaways-page-item-img-btn-more').attr('href')}" target="_blank">${name}</a>...`
  8650. });
  8651. const aElement = $(item).find('a.giveaways-page-item-img-btn-enter:contains(\'enter\')');
  8652. if (aElement?.attr('onclick')?.includes('checkUser')) {
  8653. const giveawayId = aElement.attr('onclick')?.match(/[\d]+/)?.[0];
  8654. if (giveawayId) {
  8655. checkUser(giveawayId);
  8656. }
  8657. }
  8658. if (!aElement.attr('href')) {
  8659. logStatus.error('Error: No "href".');
  8660. continue;
  8661. }
  8662. const {
  8663. result,
  8664. statusText,
  8665. status,
  8666. data
  8667. } = await tools_httpRequest({
  8668. url: aElement.attr('href'),
  8669. method: 'GET'
  8670. });
  8671. if (result === 'Success') {
  8672. const {
  8673. result: result0,
  8674. statusText: statusText0,
  8675. status: status0,
  8676. data: data0
  8677. } = await tools_httpRequest({
  8678. url: data?.finalUrl,
  8679. method: 'GET'
  8680. });
  8681. if (data0?.responseText && /You've entered this giveaway/gim.test(data0.responseText)) {
  8682. logStatus.success();
  8683. const points = data0.responseText.match(/Points:[\s]*?([\d]+)/)?.[1];
  8684. if (type === 'points' && points) {
  8685. this.myPoints = parseInt(points, 10);
  8686. }
  8687. } else if (data0?.responseText && /You're not eligible to enter/gim.test(data0.responseText)) {
  8688. logStatus.error('You\'re not eligible to enter');
  8689. } else {
  8690. logStatus.error(`${result0}:${statusText0}(${status0})`);
  8691. }
  8692. } else {
  8693. logStatus.error(`${result}:${statusText}(${status})`);
  8694. }
  8695. }
  8696. }
  8697. scripts_echoLog({
  8698. text: '-----END-----'
  8699. });
  8700. } catch (error) {
  8701. throwError(error, 'OpiumPulses.toggleTask');
  8702. }
  8703. }
  8704. init() {
  8705. return true;
  8706. }
  8707. classifyTask() {
  8708. return true;
  8709. }
  8710. #checkLogin() {
  8711. try {
  8712. if (!globalOptions.other.checkLogin) {
  8713. return true;
  8714. }
  8715. if ($('a[href*="/site/login"]').length > 1) {
  8716. window.open('/site/login', '_self');
  8717. }
  8718. return true;
  8719. } catch (error) {
  8720. throwError(error, 'OpiumPulses.checkLogin');
  8721. return false;
  8722. }
  8723. }
  8724. }
  8725. const website_OpiumPulses = OpiumPulses;
  8726. const external_dayjs_namespaceObject = dayjs;
  8727. var external_dayjs_default = __webpack_require__.n(external_dayjs_namespaceObject);
  8728. const leftKeyChecker = {
  8729. async classify(link) {
  8730. try {
  8731. if (/^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(link)) {
  8732. return await this.giveawaySu(link);
  8733. }
  8734. if (/^https?:\/\/givee\.club\/[\w]+?\/event\/[\d]+/.test(link)) {
  8735. return await this.giveeClub(link);
  8736. }
  8737. if (/^https?:\/\/gleam\.io\/.+?\/.+/.test(link)) {
  8738. return await this.gleam(link);
  8739. }
  8740. if (/^https?:\/\/www\.indiedb\.com\/giveaways\/.+/.test(link)) {
  8741. return await this.indieDb(link);
  8742. }
  8743. if (/^https?:\/\/key-hub\.eu\/giveaway\/[\d]+/.test(link)) {
  8744. return await this.keyhub(link);
  8745. }
  8746. if (/^https?:\/\/opquests\.com\/quests\/[\d]+/.test(link)) {
  8747. return await this.opquests(link);
  8748. }
  8749. if (/^https?:\/\/itch\.io\/s\/[\d]+?\/.*/.test(link)) {
  8750. return await this.itch(link);
  8751. }
  8752. return false;
  8753. } catch (error) {
  8754. throwError(error, 'leftKeyChecker.classify');
  8755. return false;
  8756. }
  8757. },
  8758. async giveawaySu(link) {
  8759. try {
  8760. const {
  8761. result,
  8762. data
  8763. } = await tools_httpRequest({
  8764. url: link,
  8765. method: 'GET'
  8766. });
  8767. if (result === 'Success' && data?.status === 200) {
  8768. if (data.responseText.includes('class="steam-login"')) {
  8769. return false;
  8770. }
  8771. if (data.responseText.includes('class="giveaway-ended"')) {
  8772. return 'Ended';
  8773. }
  8774. return 'Active';
  8775. }
  8776. return false;
  8777. } catch (error) {
  8778. throwError(error, 'leftKeyChecker.giveawaySu');
  8779. return false;
  8780. }
  8781. },
  8782. async giveeClub(link) {
  8783. try {
  8784. const {
  8785. result,
  8786. data
  8787. } = await tools_httpRequest({
  8788. url: link,
  8789. method: 'GET'
  8790. });
  8791. if (result === 'Success' && data?.status === 200) {
  8792. if (data.responseText.includes('class="event-winner"')) {
  8793. return 'Won';
  8794. }
  8795. if (data.responseText.includes('class="event-ended"')) {
  8796. return 'Ended';
  8797. }
  8798. return 'Active';
  8799. }
  8800. return false;
  8801. } catch (error) {
  8802. throwError(error, 'leftKeyChecker.giveeClub');
  8803. return false;
  8804. }
  8805. },
  8806. async gleam(link) {
  8807. try {
  8808. const {
  8809. result,
  8810. data
  8811. } = await tools_httpRequest({
  8812. url: link,
  8813. method: 'GET'
  8814. });
  8815. if (result === 'Success' && data?.status === 200) {
  8816. if (/incentives&quot;:{&quot;[\d]+?&quot;:\[&quot;.+?&quot;\]/.test(data.responseText)) {
  8817. return 'Won';
  8818. }
  8819. const campaignDiv = data.responseText.match(/<div class='popup-blocks-container'[\w\W]+?'>/)?.[0];
  8820. if (!campaignDiv) {
  8821. return false;
  8822. }
  8823. const campaignString = $(campaignDiv).attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  8824. if (!campaignString) {
  8825. return false;
  8826. }
  8827. const {
  8828. campaign
  8829. } = JSON.parse(campaignString);
  8830. if (campaign.banned) {
  8831. return 'Banned';
  8832. }
  8833. if (campaign.finished) {
  8834. return 'Ended';
  8835. }
  8836. if (campaign.paused) {
  8837. return 'Paused';
  8838. }
  8839. if (new Date().getTime() < campaign.starts_at * 1e3) {
  8840. return 'NotStart';
  8841. }
  8842. return 'Active';
  8843. }
  8844. return false;
  8845. } catch (error) {
  8846. throwError(error, 'leftKeyChecker.gleam');
  8847. return false;
  8848. }
  8849. },
  8850. async indieDb(link) {
  8851. try {
  8852. const {
  8853. result,
  8854. data
  8855. } = await tools_httpRequest({
  8856. url: link,
  8857. method: 'GET'
  8858. });
  8859. if (result === 'Success' && data?.status === 200) {
  8860. if (data.responseText.includes('Congrats you WON')) {
  8861. return 'Won';
  8862. }
  8863. if (data.responseText.includes('Giveaway is closed') || data.responseText.includes('next time')) {
  8864. return 'Ended';
  8865. }
  8866. return 'Active';
  8867. }
  8868. return false;
  8869. } catch (error) {
  8870. throwError(error, 'leftKeyChecker.indieDb');
  8871. return false;
  8872. }
  8873. },
  8874. async keyhub(link) {
  8875. try {
  8876. const {
  8877. result,
  8878. data
  8879. } = await tools_httpRequest({
  8880. url: link,
  8881. method: 'GET'
  8882. });
  8883. if (result === 'Success' && data?.status === 200) {
  8884. const keysleft = data.responseText.match(/<span id="keysleft">([\d]+?)<\/span>/)?.[1];
  8885. if (!keysleft) {
  8886. return false;
  8887. }
  8888. if (keysleft === '0') {
  8889. return 'Ended';
  8890. }
  8891. return `Active(${keysleft})`;
  8892. }
  8893. return false;
  8894. } catch (error) {
  8895. throwError(error, 'leftKeyChecker.keyhub');
  8896. return false;
  8897. }
  8898. },
  8899. async opquests(link) {
  8900. try {
  8901. const {
  8902. result,
  8903. data
  8904. } = await tools_httpRequest({
  8905. url: link,
  8906. method: 'GET'
  8907. });
  8908. if (result === 'Success' && data?.status === 200) {
  8909. const keysleft = data.responseText.match(/<div class="">[\s]*?([\d]+?)[\s]*?of/)?.[1];
  8910. if (!keysleft) {
  8911. return false;
  8912. }
  8913. if (keysleft === '0') {
  8914. return 'Ended';
  8915. }
  8916. return `Active(${keysleft})`;
  8917. } else if (data?.status === 404) {
  8918. return 'Ended';
  8919. }
  8920. return false;
  8921. } catch (error) {
  8922. throwError(error, 'leftKeyChecker.opquests');
  8923. return false;
  8924. }
  8925. },
  8926. async itch(link) {
  8927. try {
  8928. const {
  8929. result,
  8930. data
  8931. } = await tools_httpRequest({
  8932. url: link,
  8933. method: 'GET'
  8934. });
  8935. if (result === 'Success' && data?.status === 200) {
  8936. const endDate = data.responseText.match(/{"start_date":"[0-9A-Z-:]+?".*?"end_date":"([0-9A-Z-:]+?)".*?}/)?.[1];
  8937. if (!endDate) {
  8938. return false;
  8939. }
  8940. if (new Date().getTime() > new Date(endDate).getTime()) {
  8941. return 'Ended';
  8942. }
  8943. return `Active(${external_dayjs_default()(endDate).format('YYYY-MM-DD HH:mm:ss')})`;
  8944. }
  8945. return false;
  8946. } catch (error) {
  8947. throwError(error, 'leftKeyChecker.itch');
  8948. return false;
  8949. }
  8950. }
  8951. };
  8952. const website_leftKeyChecker = leftKeyChecker;
  8953. const Keylol_defaultTasksTemplate = {
  8954. steam: {
  8955. groupLinks: [],
  8956. wishlistLinks: [],
  8957. curatorLinks: [],
  8958. curatorLikeLinks: [],
  8959. followLinks: [],
  8960. forumLinks: [],
  8961. announcementLinks: [],
  8962. workshopVoteLinks: [],
  8963. licenseLinks: []
  8964. },
  8965. discord: {
  8966. serverLinks: []
  8967. },
  8968. instagram: {
  8969. userLinks: []
  8970. },
  8971. vk: {
  8972. nameLinks: []
  8973. },
  8974. twitch: {
  8975. channelLinks: []
  8976. },
  8977. reddit: {
  8978. redditLinks: []
  8979. },
  8980. twitter: {
  8981. userLinks: [],
  8982. retweetLinks: []
  8983. },
  8984. youtube: {
  8985. channelLinks: [],
  8986. likeLinks: []
  8987. }
  8988. };
  8989. const Keylol_defaultTasks = JSON.stringify(Keylol_defaultTasksTemplate);
  8990. class Keylol extends website_Website {
  8991. name = 'Keylol';
  8992. socialTasks = JSON.parse(Keylol_defaultTasks);
  8993. undoneTasks = JSON.parse(Keylol_defaultTasks);
  8994. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect' ];
  8995. static test() {
  8996. 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'));
  8997. }
  8998. init() {
  8999. return true;
  9000. }
  9001. after() {
  9002. try {
  9003. const selector = this.name === 'Keylol' ? '#postlist>div[id^="post_"]:first' : 'div.container';
  9004. const mainPost = $(selector);
  9005. const discordLinks = mainPost.find('a[href*="discord.com"]:visible');
  9006. const redditLinks = mainPost.find('a[href*="reddit.com"]:visible');
  9007. const insLinks = mainPost.find('a[href*="instagram.com"]:visible');
  9008. const twitterLinks = mainPost.find('a[href*="twitter.com"]:visible,a[href*="x.com"]:visible');
  9009. const twitchLinks = mainPost.find('a[href*="twitch.tv"]:visible');
  9010. const vkLinks = mainPost.find('a[href*="vk.com"]:visible');
  9011. const steamStoreLinks = mainPost.find('a[href*="store.steampowered.com"]:visible');
  9012. const steamCommunityLinks = mainPost.find('a[href*="steamcommunity.com"]:visible');
  9013. const ytbLinks = mainPost.find('a[href*="youtube.com"]:visible');
  9014. if (discordLinks.length > 0) {
  9015. for (const discordLink of discordLinks) {
  9016. const link = $(discordLink).attr('href');
  9017. if (!(link && /^https?:\/\/discord\.com\/invite\/.+/.test(link))) {
  9018. continue;
  9019. }
  9020. this.#addBtn(discordLink, 'discord', 'serverLinks', link);
  9021. }
  9022. }
  9023. if (redditLinks.length > 0) {
  9024. for (const redditLink of redditLinks) {
  9025. const link = $(redditLink).attr('href');
  9026. if (!(link && /^https?:\/\/www\.reddit\.com\/(r|user)\/.+/.test(link))) {
  9027. continue;
  9028. }
  9029. this.#addBtn(redditLink, 'reddit', 'redditLinks', link);
  9030. }
  9031. }
  9032. if (insLinks.length > 0) {
  9033. for (const insLink of insLinks) {
  9034. const link = $(insLink).attr('href');
  9035. if (!(link && /^https:\/\/www\.instagram\.com\/.+/.test(link))) {
  9036. continue;
  9037. }
  9038. this.#addBtn(insLink, 'instagram', 'userLinks', link);
  9039. }
  9040. }
  9041. if (twitterLinks.length > 0) {
  9042. for (const twitterLink of twitterLinks) {
  9043. const link = $(twitterLink).attr('href');
  9044. if (!(link && /^https:\/\/twitter\.com\/.+/.test(link))) {
  9045. continue;
  9046. }
  9047. if (/https:\/\/twitter\.com\/.*?\/status\/[\d]+/.test(link)) {
  9048. this.#addBtn(twitterLink, 'twitter', 'retweetLinks', link);
  9049. } else {
  9050. this.#addBtn(twitterLink, 'twitter', 'userLinks', link);
  9051. }
  9052. }
  9053. }
  9054. if (twitchLinks.length > 0) {
  9055. for (const twitchLink of twitchLinks) {
  9056. const link = $(twitchLink).attr('href');
  9057. if (!(link && /^https:\/\/(www\.)?twitch\.tv\/.+/.test(link))) {
  9058. continue;
  9059. }
  9060. this.#addBtn(twitchLink, 'twitch', 'channelLinks', link);
  9061. }
  9062. }
  9063. if (vkLinks.length > 0) {
  9064. for (const vkLink of vkLinks) {
  9065. const link = $(vkLink).attr('href');
  9066. if (!(link && /^https:\/\/vk\.com\/.+/.test(link))) {
  9067. continue;
  9068. }
  9069. this.#addBtn(vkLink, 'vk', 'nameLinks', link);
  9070. }
  9071. }
  9072. if (steamStoreLinks.length > 0) {
  9073. for (const steamStoreLink of steamStoreLinks) {
  9074. const link = $(steamStoreLink).attr('href');
  9075. if (!link) {
  9076. continue;
  9077. }
  9078. if (/curator\/[\d]+/.test(link)) {
  9079. this.#addBtn(steamStoreLink, 'steam', 'curatorLinks', link);
  9080. } else if (/(publisher|developer|franchise)\/.+/.test(link)) {
  9081. this.#addBtn(steamStoreLink, 'steam', 'curatorLikeLinks', link);
  9082. } else if (/news(hub)?\/app\/[\d]+\/view\/[\d]+/.test(link)) {
  9083. this.#addBtn(steamStoreLink, 'steam', 'announcementLinks', link);
  9084. } else if (/app\/[\d]+/.test(link)) {
  9085. this.#addBtn(steamStoreLink, 'steam', 'followLinks', link);
  9086. this.#addBtn(steamStoreLink, 'steam', 'wishlistLinks', link);
  9087. }
  9088. }
  9089. }
  9090. if (steamCommunityLinks.length > 0) {
  9091. for (const steamCommunityLink of steamCommunityLinks) {
  9092. const link = $(steamCommunityLink).attr('href');
  9093. if (!link) {
  9094. continue;
  9095. }
  9096. if (/groups\/.+/.test(link)) {
  9097. this.#addBtn(steamCommunityLink, 'steam', 'groupLinks', link);
  9098. } else if (/announcements\/detail\/[\d]+/.test(link)) {
  9099. this.#addBtn(steamCommunityLink, 'steam', 'announcementLinks', link);
  9100. }
  9101. }
  9102. }
  9103. if (ytbLinks.length > 0) {
  9104. for (const ytbLink of ytbLinks) {
  9105. const link = $(ytbLink).attr('href');
  9106. if (!link) {
  9107. continue;
  9108. }
  9109. this.#addBtn(ytbLink, 'youtube', 'channelLinks', link);
  9110. this.#addBtn(ytbLink, 'youtube', 'likeLinks', link);
  9111. }
  9112. }
  9113. 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');
  9114. if (giveawayLinks.length > 0) {
  9115. for (const giveawayLink of giveawayLinks) {
  9116. const link = $(giveawayLink).attr('href');
  9117. if (!link) {
  9118. continue;
  9119. }
  9120. website_leftKeyChecker.classify(link).then(status => {
  9121. if (!status) {
  9122. return;
  9123. }
  9124. if (/^Active/.test(status)) {
  9125. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status active" title="${i18n('Active')}">${status}</font>`);
  9126. return;
  9127. }
  9128. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status not-active" title="${i18n(status)}">${status}</font>`);
  9129. }).catch(error => {
  9130. throwError(error, 'keylol.after -> leftKeyChecker');
  9131. });
  9132. }
  9133. }
  9134. if (this.name === 'Keylol') {
  9135. const asfLinks = mainPost.find('a[href^="#asf"]:visible');
  9136. if (asfLinks.length > 0) {
  9137. for (const asfLink of asfLinks) {
  9138. const link = $(asfLink).attr('href');
  9139. if (!link) {
  9140. continue;
  9141. }
  9142. this.#addBtn($(`a[href="${link}"]`).after('<span style="color: #ccc; margin: 0 -5px 0 5px"> | </span>').next()[0], 'steam', 'licenseLinks', `appid-${link.replace('#asf', '')}`);
  9143. }
  9144. }
  9145. const subLinks = mainPost.find('a[href*="steamdb.info/sub/"]:visible');
  9146. if (subLinks.length > 0) {
  9147. for (const subLink of subLinks) {
  9148. const link = $(subLink).attr('href');
  9149. if (!link) {
  9150. continue;
  9151. }
  9152. const subid = link.match(/^https:\/\/steamdb\.info\/sub\/([\d]+)/)?.[1];
  9153. if (!subid) {
  9154. continue;
  9155. }
  9156. this.#addBtn(subLink, 'steam', 'licenseLinks', `subid-${subid}`);
  9157. }
  9158. }
  9159. const asfLinks2 = mainPost.find('.blockcode:contains("addlicense"):visible');
  9160. if (asfLinks2.length > 0) {
  9161. for (const asfLink of asfLinks2) {
  9162. const appid = [ ...asfLink.innerText.matchAll(/a(pp)?\/([\d]+)/g) ].map(matched => matched?.[2]).filter(id => id) || [];
  9163. if (appid.length > 0) {
  9164. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `appid-${appid.join(',')}`);
  9165. }
  9166. const subid = asfLink.innerText.match(/[\d]+/g)?.filter(matched => !appid.includes(matched));
  9167. if (!subid || subid.length === 0) {
  9168. continue;
  9169. }
  9170. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `subid-${subid.join(',')}`);
  9171. }
  9172. }
  9173. }
  9174. if ($('#threadindex').length > 0) {
  9175. const [ targetNode ] = $('#postlist').children('div[id^="post_"]');
  9176. const config = {
  9177. childList: true
  9178. };
  9179. const observer = new MutationObserver(() => {
  9180. observer.disconnect();
  9181. this.after();
  9182. });
  9183. observer.observe(targetNode, config);
  9184. }
  9185. } catch (error) {
  9186. throwError(error, 'keylol.after');
  9187. }
  9188. }
  9189. classifyTask(action) {
  9190. try {
  9191. this.socialTasks = JSON.parse(Keylol_defaultTasks);
  9192. this.undoneTasks = JSON.parse(Keylol_defaultTasks);
  9193. const selectedBtns = $('.auto-task-keylol[selected="selected"]:visible');
  9194. for (const btn of selectedBtns) {
  9195. const button = $(btn);
  9196. const social = button.attr('data-social');
  9197. const type = button.attr('data-type');
  9198. const link = button.attr('data-link');
  9199. if (!(social && type && link)) {
  9200. continue;
  9201. }
  9202. if (action === 'do') {
  9203. this.undoneTasks[social][type].push(link);
  9204. }
  9205. if (action === 'undo') {
  9206. this.socialTasks[social][type].push(link);
  9207. }
  9208. }
  9209. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9210. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9211. if (window.DEBUG) {
  9212. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9213. }
  9214. return true;
  9215. } catch (error) {
  9216. throwError(error, 'Keylol.classifyTask');
  9217. return false;
  9218. }
  9219. }
  9220. selectAll() {
  9221. try {
  9222. $('.auto-task-keylol:visible').attr('selected', 'selected');
  9223. } catch (error) {
  9224. throwError(error, 'Keylol.selectAll');
  9225. }
  9226. }
  9227. selectNone() {
  9228. try {
  9229. $('.auto-task-keylol:visible').removeAttr('selected');
  9230. } catch (error) {
  9231. throwError(error, 'Keylol.selectNone');
  9232. }
  9233. }
  9234. invertSelect() {
  9235. try {
  9236. $('.auto-task-keylol:visible').each((index, element) => {
  9237. element.getAttribute('selected') ? element.removeAttribute('selected') : element.setAttribute('selected', 'selected');
  9238. });
  9239. } catch (error) {
  9240. throwError(error, 'Keylol.invertSelect');
  9241. }
  9242. }
  9243. #addBtn(before, social, linkType, link) {
  9244. try {
  9245. $(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>`);
  9246. } catch (error) {
  9247. throwError(error, 'keylol.addBtn');
  9248. }
  9249. }
  9250. }
  9251. const website_Keylol = Keylol;
  9252. const Opquests_defaultTasks = {
  9253. steam: {
  9254. groupLinks: [],
  9255. wishlistLinks: [],
  9256. followLinks: [],
  9257. curatorLikeLinks: []
  9258. }
  9259. };
  9260. class Opquests extends website_Website {
  9261. name = 'Opquests';
  9262. undoneTasks = {
  9263. ...Opquests_defaultTasks
  9264. };
  9265. buttons = [ 'doTask', 'verifyTask', 'getKey' ];
  9266. static test() {
  9267. return window.location.host === 'opquests.com';
  9268. }
  9269. async after() {
  9270. try {
  9271. if (!this.#checkLogin()) {
  9272. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9273. }
  9274. const opquestsVerifyTasks = GM_getValue('opquestsVerifyTasks') || [];
  9275. if (opquestsVerifyTasks.length > 0) {
  9276. const taskId = opquestsVerifyTasks.pop();
  9277. GM_setValue('opquestsVerifyTasks', opquestsVerifyTasks);
  9278. const [ verifyBtn ] = $(`#task_id[value="${taskId}"]`).parent().find('button[type="button"]').has('i.fa-check');
  9279. if (verifyBtn) {
  9280. verifyBtn.click();
  9281. return;
  9282. }
  9283. this.after();
  9284. return;
  9285. }
  9286. if (GM_getValue('opquestsVerifyTasks')) {
  9287. GM_deleteValue('opquestsVerifyTasks');
  9288. }
  9289. } catch (error) {
  9290. throwError(error, 'Opquests.after');
  9291. }
  9292. }
  9293. init() {
  9294. try {
  9295. const logStatus = scripts_echoLog({
  9296. text: i18n('initing')
  9297. });
  9298. if ($('a[href*="/auth/redirect"]').length > 0) {
  9299. window.open('/auth/redirect', '_self');
  9300. logStatus.warning(i18n('needLogin'));
  9301. return false;
  9302. }
  9303. if (!this.#getGiveawayId()) {
  9304. return false;
  9305. }
  9306. this.initialized = true;
  9307. logStatus.success();
  9308. return true;
  9309. } catch (error) {
  9310. throwError(error, 'Opquests.init');
  9311. return false;
  9312. }
  9313. }
  9314. async classifyTask(action) {
  9315. try {
  9316. if (action === 'undo') {
  9317. scripts_echoLog({
  9318. text: i18n('cannotUndo')
  9319. });
  9320. return false;
  9321. }
  9322. const logStatus = scripts_echoLog({
  9323. text: i18n('getTasksInfo')
  9324. });
  9325. const tasks = $('.w-full:contains("Validate") .items-center');
  9326. for (const task of tasks) {
  9327. const link = $(task).find('a:contains("Open")').attr('href');
  9328. const taskDes = $(task).find('div').eq(1).text().trim();
  9329. if (!link) {
  9330. continue;
  9331. }
  9332. if (/steamcommunity\.com\/groups\//.test(link)) {
  9333. this.undoneTasks.steam.groupLinks.push(link);
  9334. } else if (/store\.steampowered\.com\/app\//.test(link)) {
  9335. if (/wishlist/gim.test(taskDes)) {
  9336. this.undoneTasks.steam.wishlistLinks.push(link);
  9337. } else if (/follow/gim.test(taskDes)) {
  9338. this.undoneTasks.steam.followLinks.push(link);
  9339. }
  9340. } else if (/store\.steampowered\.com\/(publisher|developer|curator)\//.test(link) && /follow/gim.test(taskDes)) {
  9341. this.undoneTasks.steam.curatorLikeLinks.push(link);
  9342. } else {
  9343. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  9344. }
  9345. }
  9346. logStatus.success();
  9347. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9348. if (window.DEBUG) {
  9349. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9350. }
  9351. return true;
  9352. } catch (error) {
  9353. throwError(error, 'Opquests.classifyTask');
  9354. return false;
  9355. }
  9356. }
  9357. async verifyTask() {
  9358. try {
  9359. if (!this.initialized) {
  9360. this.init();
  9361. }
  9362. const tasks = $.makeArray($('.items-center').has('input[name="task_id"]')).map(ele => $(ele).find('input[name="task_id"]').val());
  9363. GM_setValue('opquestsVerifyTasks', tasks);
  9364. await this.#confirm();
  9365. this.after();
  9366. return true;
  9367. } catch (error) {
  9368. throwError(error, 'Opquests.verifyTask');
  9369. return false;
  9370. }
  9371. }
  9372. async #confirm() {
  9373. try {
  9374. const logStatus = scripts_echoLog({
  9375. html: `<li>${i18n('confirmingTask')}...<font></font></li>`
  9376. });
  9377. const {
  9378. result,
  9379. statusText,
  9380. status,
  9381. data
  9382. } = await tools_httpRequest({
  9383. url: `https://opquests.com/quests/${this.giveawayId}?confirm=1`,
  9384. method: 'GET',
  9385. nochche: true,
  9386. headers: {
  9387. origin: 'https://opquests.com',
  9388. referer: `https://opquests.com/warning?id=${this.giveawayId}`
  9389. }
  9390. });
  9391. if (result === 'Success') {
  9392. if (data?.status === 200) {
  9393. logStatus.success();
  9394. return true;
  9395. }
  9396. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9397. return false;
  9398. }
  9399. logStatus.error(`${result}:${statusText}(${status})`);
  9400. return false;
  9401. } catch (error) {
  9402. throwError(error, 'Opquests.confirm');
  9403. return false;
  9404. }
  9405. }
  9406. async getKey(isButton) {
  9407. try {
  9408. const logStatus = scripts_echoLog({
  9409. text: i18n('gettingKey')
  9410. });
  9411. const {
  9412. result,
  9413. statusText,
  9414. status,
  9415. data
  9416. } = await tools_httpRequest({
  9417. url: 'https://opquests.com/keys',
  9418. method: 'GET'
  9419. });
  9420. if (result === 'Success') {
  9421. if (data?.responseText) {
  9422. const key = $(data?.responseText).find(`div.items-center:contains("${$('h1.font-bold').text().trim().replace(' Quest', '')}")`).find('div.font-bold').next().text();
  9423. if (!key) {
  9424. logStatus.error('Error: Key was not found');
  9425. if (isButton) {
  9426. window.open('https://opquests.com/keys', '_self');
  9427. }
  9428. return false;
  9429. }
  9430. logStatus.success();
  9431. scripts_echoLog({}).success(key);
  9432. return true;
  9433. }
  9434. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9435. return false;
  9436. }
  9437. logStatus.error(`${result}:${statusText}(${status})`);
  9438. return false;
  9439. } catch (error) {
  9440. throwError(error, 'Opquests.getGiveawayId');
  9441. return false;
  9442. }
  9443. }
  9444. #getGiveawayId() {
  9445. try {
  9446. const giveawayId = window.location.href.match(/quests\/([\d]+)/)?.[1];
  9447. if (giveawayId) {
  9448. this.giveawayId = giveawayId;
  9449. return true;
  9450. }
  9451. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  9452. return false;
  9453. } catch (error) {
  9454. throwError(error, 'Opquests.getGiveawayId');
  9455. return false;
  9456. }
  9457. }
  9458. #checkLogin() {
  9459. try {
  9460. if (!globalOptions.other.checkLogin) {
  9461. return true;
  9462. }
  9463. if ($('a[href*="/auth/redirect"]').length > 0) {
  9464. window.open('/auth/redirect', '_self');
  9465. }
  9466. return true;
  9467. } catch (error) {
  9468. throwError(error, 'Opquests.checkLogin');
  9469. return false;
  9470. }
  9471. }
  9472. }
  9473. const website_Opquests = Opquests;
  9474. const Gleam_defaultTasksTemplate = {
  9475. steam: {
  9476. groupLinks: [],
  9477. wishlistLinks: [],
  9478. followLinks: [],
  9479. curatorLinks: [],
  9480. curatorLikeLinks: []
  9481. },
  9482. twitter: {
  9483. userLinks: [],
  9484. retweetLinks: []
  9485. },
  9486. twitch: {
  9487. channelLinks: []
  9488. },
  9489. discord: {
  9490. serverLinks: []
  9491. },
  9492. youtube: {
  9493. channelLinks: []
  9494. },
  9495. extra: {
  9496. gleam: []
  9497. }
  9498. };
  9499. const Gleam_defaultTasks = JSON.stringify(Gleam_defaultTasksTemplate);
  9500. class Gleam extends website_Website {
  9501. name = 'Gleam';
  9502. undoneTasks = JSON.parse(Gleam_defaultTasks);
  9503. socialTasks = JSON.parse(Gleam_defaultTasks);
  9504. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  9505. static test() {
  9506. return window.location.host === 'gleam.io';
  9507. }
  9508. before() {
  9509. try {
  9510. unsafeWindow.confirm = () => {};
  9511. unsafeWindow.alert = () => {};
  9512. unsafeWindow.prompt = () => {};
  9513. } catch (error) {
  9514. throwError(error, 'Gleam.before');
  9515. }
  9516. }
  9517. async after() {
  9518. try {
  9519. if (window.location.search.includes('8b07d23f4bfa65f9')) {
  9520. const checkComplete = setInterval(() => {
  9521. if ($('.entry-content .entry-method i.fa-check').length > 0) {
  9522. clearInterval(checkComplete);
  9523. window.close();
  9524. }
  9525. });
  9526. for (const task of $('.entry-content .entry-method')) {
  9527. const taskInfo = $(task).find('.user-links');
  9528. const expandInfo = $(task).find('.expandable');
  9529. const aElements = expandInfo.find('a.btn,a:contains(Continue),button:contains(Continue)');
  9530. if (aElements.length > 0) {
  9531. for (const element of aElements) {
  9532. const $element = $(element);
  9533. const href = $element.attr('href');
  9534. $element.removeAttr('href')[0].click();
  9535. $element.attr('href', href);
  9536. await delay(1e3);
  9537. }
  9538. }
  9539. taskInfo[0].click();
  9540. await delay(1e3);
  9541. }
  9542. scripts_echoLog({}).warning(i18n('gleamTaskNotice'));
  9543. } else if (!await this.#checkLeftKey()) {
  9544. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  9545. }
  9546. } catch (error) {
  9547. throwError(error, 'Gleam.after');
  9548. }
  9549. }
  9550. init() {
  9551. try {
  9552. const logStatus = scripts_echoLog({
  9553. text: i18n('initing')
  9554. });
  9555. if (!this.#getGiveawayId()) {
  9556. return false;
  9557. }
  9558. this.initialized = true;
  9559. logStatus.success();
  9560. return true;
  9561. } catch (error) {
  9562. throwError(error, 'Gleam.init');
  9563. return false;
  9564. }
  9565. }
  9566. async classifyTask(action) {
  9567. try {
  9568. const logStatus = scripts_echoLog({
  9569. text: i18n('getTasksInfo')
  9570. });
  9571. if (action === 'undo') {
  9572. this.socialTasks = GM_getValue(`gleamTasks-${this.giveawayId}`)?.tasks || JSON.parse(Gleam_defaultTasks);
  9573. }
  9574. const tasks = $('.entry-content .entry-method');
  9575. for (const task of tasks) {
  9576. const $task = $(task);
  9577. if (action === 'do' && $task.find('i.fa-question').length === 0) {
  9578. continue;
  9579. }
  9580. const socialIcon = $task.find('.icon-wrapper i');
  9581. const taskInfo = $task.find('.user-links');
  9582. const taskText = taskInfo.text().trim();
  9583. const expandInfo = $task.find('.expandable');
  9584. const aElements = expandInfo.find('a.btn');
  9585. if (aElements.length > 0) {
  9586. for (const element of aElements) {
  9587. const $element = $(element);
  9588. const href = $element.attr('href');
  9589. $element.removeAttr('href')[0].click();
  9590. $element.attr('href', href);
  9591. }
  9592. }
  9593. if (socialIcon.hasClass('fa-twitter') || socialIcon.hasClass('fa-x-twitter')) {
  9594. const link = $task.find('a[href^="https://twitter.com/"],a[href^="https://x.com/"]').attr('href');
  9595. if (!link) {
  9596. continue;
  9597. }
  9598. if (/follow/gi.test(taskText)) {
  9599. if (action === 'undo') {
  9600. this.socialTasks.twitter.userLinks.push(link);
  9601. }
  9602. if (action === 'do') {
  9603. this.undoneTasks.twitter.userLinks.push(link);
  9604. }
  9605. } else if (/retweet/gim.test(taskText)) {
  9606. if (action === 'undo') {
  9607. this.socialTasks.twitter.retweetLinks.push(link);
  9608. }
  9609. if (action === 'do') {
  9610. this.undoneTasks.twitter.retweetLinks.push(link);
  9611. }
  9612. }
  9613. } else if (socialIcon.hasClass('fa-twitch')) {
  9614. if (/follow/gim.test(taskText)) {
  9615. const link = $task.find('a[href^="https://twitch.tv/"]').attr('href');
  9616. if (!link) {
  9617. continue;
  9618. }
  9619. if (action === 'undo') {
  9620. this.socialTasks.twitch.channelLinks.push(link);
  9621. }
  9622. if (action === 'do') {
  9623. this.undoneTasks.twitch.channelLinks.push(link);
  9624. }
  9625. }
  9626. } else if (socialIcon.hasClass('fa-discord')) {
  9627. if (/join/gim.test(taskText)) {
  9628. let link = $task.find('a[href^="https://discord.com/invite/"]').attr('href');
  9629. if (!link) {
  9630. const ggLink = $task.find('a[href^="https://discord.gg/"]').attr('href')?.match(/discord\.gg\/([^/]+)/)?.[1];
  9631. if (!ggLink) {
  9632. continue;
  9633. }
  9634. link = `https://discord.com/invite/${ggLink}`;
  9635. }
  9636. if (action === 'undo') {
  9637. this.socialTasks.discord.serverLinks.push(link);
  9638. }
  9639. if (action === 'do') {
  9640. this.undoneTasks.discord.serverLinks.push(link);
  9641. }
  9642. }
  9643. } else if (socialIcon.hasClass('fa-external-link-square-alt')) {
  9644. continue;
  9645. } else if (socialIcon.hasClass('fa-youtube')) {
  9646. if (/subscribe/gim.test(taskText)) {
  9647. const link = $task.find('a[href^="https://www.youtube.com/channel/"]').attr('href');
  9648. if (!link) {
  9649. continue;
  9650. }
  9651. if (action === 'undo') {
  9652. this.socialTasks.youtube.channelLinks.push(link);
  9653. }
  9654. if (action === 'do') {
  9655. this.undoneTasks.youtube.channelLinks.push(link);
  9656. }
  9657. }
  9658. } else if (socialIcon.attr('class')?.includes('steam')) {
  9659. if (/join.*group/gi.test(taskText)) {
  9660. const link = $task.find('a[href^="https://steamcommunity.com/groups/"]').attr('href');
  9661. if (!link) {
  9662. continue;
  9663. }
  9664. if (action === 'undo') {
  9665. this.socialTasks.steam.groupLinks.push(link);
  9666. }
  9667. if (action === 'do') {
  9668. this.undoneTasks.steam.groupLinks.push(link);
  9669. }
  9670. } else if (/follow.*curator/gi.test(taskText)) {
  9671. const link = $task.find('a[href^="https://store.steampowered.com/curator/"]').attr('href');
  9672. if (!link) {
  9673. continue;
  9674. }
  9675. if (action === 'undo') {
  9676. this.socialTasks.steam.curatorLinks.push(link);
  9677. }
  9678. if (action === 'do') {
  9679. this.undoneTasks.steam.curatorLinks.push(link);
  9680. }
  9681. }
  9682. } else if (socialIcon.hasClass('fa-bullhorn') && /Complete|Increase/gi.test(taskText)) {
  9683. if (action !== 'do') {
  9684. continue;
  9685. }
  9686. const gleamLink = await this.#getGleamLink(taskText);
  9687. if (!gleamLink) {
  9688. continue;
  9689. }
  9690. this.undoneTasks.extra.gleam.push(gleamLink);
  9691. } 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 {
  9692. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskText}`);
  9693. }
  9694. }
  9695. logStatus.success();
  9696. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9697. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9698. if (window.DEBUG) {
  9699. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9700. }
  9701. GM_setValue(`gleamTasks-${this.giveawayId}`, {
  9702. tasks: this.socialTasks,
  9703. time: new Date().getTime()
  9704. });
  9705. return true;
  9706. } catch (error) {
  9707. throwError(error, 'Gleam.classifyTask');
  9708. return false;
  9709. }
  9710. }
  9711. async extraDoTask({
  9712. gleam
  9713. }) {
  9714. try {
  9715. const pro = [];
  9716. for (const link of gleam) {
  9717. pro.push(this.#doGleamTask(link));
  9718. }
  9719. return Promise.all(pro).then(() => true);
  9720. } catch (error) {
  9721. throwError(error, 'Gleam.extraDoTask');
  9722. return false;
  9723. }
  9724. }
  9725. async verifyTask() {
  9726. try {
  9727. scripts_echoLog({
  9728. text: `${i18n('verifyingTask')}...`
  9729. });
  9730. const tasks = $('.entry-content .entry-method');
  9731. unsafeWindow._OxA = '_OxA';
  9732. for (const task of tasks) {
  9733. if ($('[campaign-key="campaign.key"]').length > 0) {
  9734. return scripts_echoLog({
  9735. text: i18n('campaign')
  9736. });
  9737. }
  9738. const $task = $(task);
  9739. if ($task.find('i.fa-question').length === 0) {
  9740. continue;
  9741. }
  9742. const taskInfo = $task.find('.user-links');
  9743. taskInfo[0].click();
  9744. const aElements = $task.find('.expandable').find('a.btn');
  9745. if (aElements.length > 0) {
  9746. for (const element of aElements) {
  9747. const $element = $(element);
  9748. const href = $element.attr('href');
  9749. $element.removeAttr('href')[0].click();
  9750. $element.attr('href', href);
  9751. }
  9752. }
  9753. unsafeWindow.$hookTimer?.setSpeed(1e3);
  9754. const visitBtn = $task.find('.expandable').find('span:contains(more seconds),button:contains(more seconds)').filter(':visible');
  9755. if (visitBtn.length > 0 && unsafeWindow.$hookTimer) {
  9756. const newTab = GM_openInTab('', {
  9757. active: true
  9758. });
  9759. await delay(1e3);
  9760. newTab?.close();
  9761. window.focus();
  9762. }
  9763. await delay(3e3);
  9764. unsafeWindow.$hookTimer?.setSpeed(1);
  9765. const expandInfo = $task.find('.expandable');
  9766. const [ input ] = expandInfo.find('input');
  9767. if (input) {
  9768. const evt = new Event('input', {
  9769. bubbles: true,
  9770. cancelable: true,
  9771. composed: true
  9772. });
  9773. const valuelimit = [ ...expandInfo.text().matchAll(/"(.+?)"/g) ].at(-1)?.[1];
  9774. input.value = valuelimit || 'vloot';
  9775. input.dispatchEvent(evt);
  9776. await delay(1e3);
  9777. }
  9778. await this.#checkSync();
  9779. const continueBtn = $task.find('.expandable').find('span:contains(Continue),button:contains(Continue)');
  9780. for (const button of continueBtn) {
  9781. button.click();
  9782. await delay(500);
  9783. await this.#checkSync();
  9784. }
  9785. }
  9786. scripts_echoLog({
  9787. text: i18n('verifiedGleamTasks')
  9788. });
  9789. } catch (error) {
  9790. throwError(error, 'Gleam.verifyTask');
  9791. return false;
  9792. }
  9793. }
  9794. async #checkSync() {
  9795. try {
  9796. return await new Promise(resolve => {
  9797. const checker = setInterval(() => {
  9798. if ($('.entry-content .entry-method i.fa-sync').length === 0) {
  9799. clearInterval(checker);
  9800. resolve(true);
  9801. }
  9802. }, 500);
  9803. });
  9804. } catch (error) {
  9805. throwError(error, 'Gleam.checkSync');
  9806. return false;
  9807. }
  9808. }
  9809. async #doGleamTask(link) {
  9810. try {
  9811. const logStatus = scripts_echoLog({
  9812. text: i18n('doingGleamTask')
  9813. });
  9814. return await new Promise(resolve => {
  9815. GM_openInTab(`${link}?8b07d23f4bfa65f9`, {
  9816. active: true,
  9817. insert: true,
  9818. setParent: true
  9819. }).onclose = () => {
  9820. logStatus.success();
  9821. resolve(true);
  9822. };
  9823. });
  9824. } catch (error) {
  9825. throwError(error, 'Gleam.doGleamTask');
  9826. return false;
  9827. }
  9828. }
  9829. #getGiveawayId() {
  9830. try {
  9831. const giveawayId = window.location.pathname;
  9832. if (giveawayId) {
  9833. this.giveawayId = giveawayId;
  9834. return true;
  9835. }
  9836. scripts_echoLog({
  9837. text: i18n('getFailed', 'GiveawayId')
  9838. });
  9839. return false;
  9840. } catch (error) {
  9841. throwError(error, 'Gleam.getGiveawayId');
  9842. return false;
  9843. }
  9844. }
  9845. async #getGleamLink(title) {
  9846. try {
  9847. const logStatus = scripts_echoLog({
  9848. text: i18n('gettingGleamLink')
  9849. });
  9850. const {
  9851. result,
  9852. statusText,
  9853. status,
  9854. data
  9855. } = await tools_httpRequest({
  9856. url: 'https://www.vloot.io/api/v1/giveaways',
  9857. method: 'GET',
  9858. responseType: 'json'
  9859. });
  9860. if (result === 'Success') {
  9861. if (data?.status === 200 && data?.response?.Success === true && data?.response?.Data) {
  9862. const {
  9863. link
  9864. } = data.response.Data.find(giveaway => title.replace(/[\s]/g, '').toLowerCase().includes(giveaway.title.replace(/[\s]/g, '').toLowerCase())) || {};
  9865. if (link) {
  9866. logStatus.success();
  9867. return link;
  9868. }
  9869. logStatus.error(`Error:${i18n('getLinkFailed')}`);
  9870. return false;
  9871. }
  9872. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9873. return false;
  9874. }
  9875. logStatus.error(`${result}:${statusText}(${status})`);
  9876. return false;
  9877. } catch (error) {
  9878. throwError(error, 'Gleam.getGleamLink');
  9879. return false;
  9880. }
  9881. }
  9882. async #checkLeftKey() {
  9883. try {
  9884. if (!globalOptions.other.checkLeftKey) {
  9885. return true;
  9886. }
  9887. const campaignString = $('div.popup-blocks-container').attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  9888. if (!campaignString) {
  9889. return false;
  9890. }
  9891. const {
  9892. campaign,
  9893. incentive
  9894. } = JSON.parse(campaignString);
  9895. const controllerString = $('div.campaign.reward').attr('ng-init')?.match(/initContestant\(([\w\W]+?)\);/)?.[1];
  9896. let ownedKey = false;
  9897. if (controllerString) {
  9898. if (JSON.parse(controllerString).contestant?.claims?.incentives?.[incentive.id]?.length) {
  9899. ownedKey = true;
  9900. }
  9901. }
  9902. if (campaign.banned || campaign.finished && !ownedKey || campaign.paused || new Date().getTime() < campaign.starts_at * 1e3) {
  9903. await external_Swal_default().fire({
  9904. icon: 'warning',
  9905. title: i18n('notice'),
  9906. text: i18n('giveawayNotWork'),
  9907. confirmButtonText: i18n('confirm'),
  9908. cancelButtonText: i18n('cancel'),
  9909. showCancelButton: true
  9910. }).then(({
  9911. value
  9912. }) => {
  9913. if (value) {
  9914. window.close();
  9915. }
  9916. });
  9917. }
  9918. return true;
  9919. } catch (error) {
  9920. throwError(error, 'Gleam.checkLeftKey');
  9921. return false;
  9922. }
  9923. }
  9924. }
  9925. const website_Gleam = Gleam;
  9926. const SweepWidget_defaultOptions = {
  9927. username: '',
  9928. email: ''
  9929. };
  9930. class SweepWidget extends website_Website {
  9931. name = 'SweepWidget';
  9932. options = {
  9933. ...SweepWidget_defaultOptions,
  9934. ...GM_getValue('SweepWidgetOptions')
  9935. };
  9936. buttons = [ 'doTask' ];
  9937. static test() {
  9938. return /^https?:\/\/sweepwidget\.com\/view\/[\d]+/.test(window.location.href);
  9939. }
  9940. async after() {
  9941. try {
  9942. if (!this.#checkLogin()) {
  9943. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9944. }
  9945. } catch (error) {
  9946. throwError(error, 'SweepWidget.after');
  9947. }
  9948. }
  9949. init() {
  9950. try {
  9951. const logStatus = scripts_echoLog({
  9952. text: i18n('initing')
  9953. });
  9954. if (!this.#checkLogin()) {
  9955. logStatus.warning(i18n('needLogin'));
  9956. return false;
  9957. }
  9958. if (!this.#getGiveawayId()) {
  9959. return false;
  9960. }
  9961. this.initialized = true;
  9962. logStatus.success();
  9963. return true;
  9964. } catch (error) {
  9965. throwError(error, 'SweepWidget.init');
  9966. return false;
  9967. }
  9968. }
  9969. classifyTask() {
  9970. return true;
  9971. }
  9972. async doTask() {
  9973. try {
  9974. if ($('#unlock_rewards_main_wrapper').length === 0) {
  9975. if ($('input[name="sw__login_name"]:visible').length > 0) {
  9976. $('input[name="sw__login_name"]').val(this.options.username);
  9977. }
  9978. if ($('input[name="sw__login_email"]:visible').length > 0) {
  9979. $('input[name="sw__login_email"]').val(this.options.email);
  9980. }
  9981. if ($('#sw_login_button:visible').length > 0) {
  9982. $('#sw_login_button')[0].click();
  9983. }
  9984. if (!await this.#checkEnter()) {
  9985. return false;
  9986. }
  9987. }
  9988. const logStatus = scripts_echoLog({
  9989. text: i18n('SweepWidgetNotice')
  9990. });
  9991. const tasks = $('#sw_inner_entry_methods_l2_wrapper>div.sw_entry');
  9992. for (const task of tasks) {
  9993. const $task = $(task);
  9994. if ($task.find('i.fa-check:visible').length > 0) {
  9995. continue;
  9996. }
  9997. const title = $task.find('.sw_text_inner');
  9998. title[0].click();
  9999. const aElement = $task.find('a.sw_link');
  10000. const link = aElement.attr('href');
  10001. aElement.attr('href', '#a').attr('target', '_self');
  10002. aElement[0]?.click();
  10003. await delay(300);
  10004. aElement.attr('href', link).attr('target', '_blank');
  10005. $task.find('input[type="text"]').val('test');
  10006. const verifyBtn = $task.find('input.sw_verify');
  10007. if (verifyBtn.prop('disabled') === true) {
  10008. title[0].click();
  10009. await delay(300);
  10010. title[0].click();
  10011. await delay(300);
  10012. }
  10013. $task.find('input.sw_verify').removeAttr('disabled')[0]?.click();
  10014. await this.#checkFinish($task);
  10015. await delay(parseInt(`${Math.random() * (3e3 - 1e3 + 1) + 1e3}`, 10));
  10016. }
  10017. logStatus.success();
  10018. return true;
  10019. } catch (error) {
  10020. throwError(error, 'SweepWidget.doTask');
  10021. return false;
  10022. }
  10023. }
  10024. #checkLogin() {
  10025. try {
  10026. if ($('#twitter_login_button').length > 0) {
  10027. $('#twitter_login_button')[0].click();
  10028. }
  10029. return true;
  10030. } catch (error) {
  10031. throwError(error, 'SweepWidget.checkLogin');
  10032. return false;
  10033. }
  10034. }
  10035. #getGiveawayId() {
  10036. try {
  10037. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  10038. if (giveawayId) {
  10039. this.giveawayId = giveawayId;
  10040. return true;
  10041. }
  10042. scripts_echoLog({
  10043. text: i18n('getFailed', 'GiveawayId')
  10044. });
  10045. return false;
  10046. } catch (error) {
  10047. throwError(error, 'SweepWidget.getGiveawayId');
  10048. return false;
  10049. }
  10050. }
  10051. async #checkEnter() {
  10052. try {
  10053. return new Promise(resolve => {
  10054. const checker = setInterval(() => {
  10055. if ($('#unlock_rewards_main_wrapper').length > 0) {
  10056. clearInterval(checker);
  10057. resolve(true);
  10058. }
  10059. }, 500);
  10060. });
  10061. } catch (error) {
  10062. throwError(error, 'SweepWidget.checkEnter');
  10063. return false;
  10064. }
  10065. }
  10066. async #checkFinish($task) {
  10067. try {
  10068. return new Promise(resolve => {
  10069. const checker = setInterval(() => {
  10070. if ($task.find('i.fa-check:visible').length > 0 || $task.find('.sw_entry_input:visible').length === 0) {
  10071. clearInterval(checker);
  10072. resolve(true);
  10073. }
  10074. }, 500);
  10075. });
  10076. } catch (error) {
  10077. throwError(error, 'SweepWidget.checkFinish');
  10078. return false;
  10079. }
  10080. }
  10081. }
  10082. const website_SweepWidget = SweepWidget;
  10083. const defaultWhiteList = {
  10084. discord: {
  10085. servers: []
  10086. },
  10087. instagram: {
  10088. users: []
  10089. },
  10090. twitch: {
  10091. channels: []
  10092. },
  10093. twitter: {
  10094. users: [],
  10095. retweets: [],
  10096. likes: []
  10097. },
  10098. vk: {
  10099. names: []
  10100. },
  10101. youtube: {
  10102. channels: [],
  10103. likes: []
  10104. },
  10105. reddit: {
  10106. reddits: []
  10107. },
  10108. steam: {
  10109. groups: [],
  10110. officialGroups: [],
  10111. wishlists: [],
  10112. follows: [],
  10113. forums: [],
  10114. workshops: [],
  10115. curators: [],
  10116. workshopVotes: [],
  10117. curatorLikes: [],
  10118. announcements: [],
  10119. licenses: [],
  10120. playtests: []
  10121. }
  10122. };
  10123. const link2id = async function(type) {
  10124. try {
  10125. const link = $('#socialLink').val();
  10126. let id = '';
  10127. switch (type) {
  10128. case 'discord.servers':
  10129. id = link.match(/invite\/(.+)/)?.[1] || '';
  10130. break;
  10131.  
  10132. case 'instagram.users':
  10133. id = link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1] || '';
  10134. break;
  10135.  
  10136. case 'twitch.channels':
  10137. id = link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2] || '';
  10138. break;
  10139.  
  10140. case 'twitter.users':
  10141. id = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || '';
  10142. break;
  10143.  
  10144. case 'twitter.retweets':
  10145. id = link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1] || '';
  10146. break;
  10147.  
  10148. case 'vk.names':
  10149. id = link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1] || '';
  10150. break;
  10151.  
  10152. case 'youtube.channels':
  10153. id = (await getInfo(link, 'channel'))?.params?.channelId || '';
  10154. break;
  10155.  
  10156. case 'youtube.likes':
  10157. id = (await getInfo(link, 'likeVideo'))?.params?.videoId || '';
  10158. break;
  10159.  
  10160. case 'reddit.reddits':
  10161. id = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1] || link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1] || '';
  10162. break;
  10163.  
  10164. case 'steam.groups':
  10165. id = link.match(/groups\/(.+)\/?/)?.[1] || '';
  10166. break;
  10167.  
  10168. case 'steam.wishlists':
  10169. case 'steam.follows':
  10170. case 'steam.forums':
  10171. id = link.match(/app\/([\d]+)/)?.[1] || '';
  10172. break;
  10173.  
  10174. case 'steam.workshops':
  10175. id = link.match(/\?id=([\d]+)/)?.[1] || '';
  10176. break;
  10177.  
  10178. case 'steam.curators':
  10179. {
  10180. if (link.includes('curator')) {
  10181. id = link.match(/curator\/([\d]+)/)?.[1] || '';
  10182. } else {
  10183. const param = link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3);
  10184. if (!param || param.length !== 2) {
  10185. break;
  10186. }
  10187. const steam = new social_Steam();
  10188. if (await steam.init()) {
  10189. id = await steam.getCuratorId(param[0], param[1]) || '';
  10190. }
  10191. }
  10192. }
  10193. break;
  10194. }
  10195. return id;
  10196. } catch (error) {
  10197. throwError(error, 'link2id');
  10198. return i18n('getFailed', 'id');
  10199. }
  10200. };
  10201. const disabledType = {
  10202. steam: [ 'workshopVotes', 'curatorLikes', 'announcements' ],
  10203. twitter: [ 'likes' ]
  10204. };
  10205. const assignWhiteList = whiteList => {
  10206. try {
  10207. const newWhiteList = {};
  10208. for (const [ key, value ] of Object.entries(defaultWhiteList)) {
  10209. newWhiteList[key] = {
  10210. ...value,
  10211. ...whiteList[key]
  10212. };
  10213. }
  10214. return newWhiteList;
  10215. } catch (error) {
  10216. throwError(error, 'assignWhiteList');
  10217. return defaultWhiteList;
  10218. }
  10219. };
  10220. const whiteListOptions = function(showType) {
  10221. try {
  10222. const whiteList = assignWhiteList(GM_getValue('whiteList') || {});
  10223. let whiteListOptionsForm = `<form id="whiteListForm" class="auto-task-form">
  10224. <table class="auto-task-table"><thead><tr><td>${i18n('website')}</td><td>${i18n('type')}</td><td>${i18n('edit')}</td></tr></thead><tbody>`;
  10225. for (const [ social, types ] of Object.entries(whiteList)) {
  10226. 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('');
  10227. }
  10228. whiteListOptionsForm += '</tbody></table></form>';
  10229. if (showType === 'swal') {
  10230. external_Swal_default().fire({
  10231. title: i18n('whiteListOptions'),
  10232. html: whiteListOptionsForm,
  10233. showConfirmButton: false,
  10234. showCloseButton: true
  10235. });
  10236. } else {
  10237. $('body').append(`<h2>${i18n('whiteList')}</h2>${whiteListOptionsForm}`);
  10238. }
  10239. $('.editWhiteList').on('click', function() {
  10240. const value = $(this).attr('data-value');
  10241. if (!value) {
  10242. return;
  10243. }
  10244. const [ social, type ] = value.split('.');
  10245. if (!whiteList?.[social]?.[type]) {
  10246. scripts_echoLog({}).warning(i18n('whiteListNotFound', value));
  10247. return;
  10248. }
  10249. external_Swal_default().fire({
  10250. title: i18n('changeWhiteListOption', value),
  10251. input: 'textarea',
  10252. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10253. <button id="link2id" data-type="${value}" class="swal2-confirm swal2-styled">获取id</button>
  10254. <p style="margin-bottom:0 !important;">在下方填写白名单,每行一个</p>`,
  10255. inputValue: whiteList[social][type].join('\n'),
  10256. showConfirmButton: true,
  10257. confirmButtonText: i18n('save'),
  10258. showCancelButton: true,
  10259. cancelButtonText: i18n('close'),
  10260. showDenyButton: true,
  10261. denyButtonText: i18n('return')
  10262. }).then(({
  10263. isDenied,
  10264. isConfirmed,
  10265. value
  10266. }) => {
  10267. if (isDenied) {
  10268. if (showType === 'swal') {
  10269. whiteListOptions(showType);
  10270. }
  10271. return;
  10272. } else if (isConfirmed) {
  10273. whiteList[social][type] = value.split('\n');
  10274. GM_setValue('whiteList', whiteList);
  10275. external_Swal_default().fire({
  10276. title: i18n('changeWhiteListSuccess'),
  10277. icon: 'success'
  10278. });
  10279. }
  10280. });
  10281. $('#link2id').on('click', async function() {
  10282. const type = $(this).attr('data-type');
  10283. $('#socialLink').val(await link2id(type));
  10284. });
  10285. });
  10286. } catch (error) {
  10287. throwError(error, 'whiteListOptions');
  10288. }
  10289. };
  10290. const whiteList = whiteListOptions;
  10291. const setGistData = async (token, gistId, fileName, content) => {
  10292. try {
  10293. const logStatus = scripts_echoLog({
  10294. text: i18n('settingData')
  10295. });
  10296. const contentData = JSON.stringify({
  10297. files: {
  10298. [fileName]: {
  10299. content: JSON.stringify(content)
  10300. }
  10301. }
  10302. });
  10303. const {
  10304. result,
  10305. statusText,
  10306. status,
  10307. data
  10308. } = await tools_httpRequest({
  10309. url: `https://api.github.com/gists/${gistId}`,
  10310. headers: {
  10311. Accept: 'application/vnd.github.v3+json',
  10312. Authorization: `token ${token}`
  10313. },
  10314. data: contentData,
  10315. responseType: 'json',
  10316. method: 'POST',
  10317. timeout: 3e4
  10318. });
  10319. if (result === 'Success') {
  10320. if (data?.status === 200 && data.response.files?.[fileName]?.content === JSON.stringify(content)) {
  10321. logStatus.success();
  10322. return true;
  10323. }
  10324. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10325. return false;
  10326. }
  10327. logStatus.error(`${result}:${statusText}(${status})`);
  10328. return false;
  10329. } catch (error) {
  10330. throwError(error, 'setGistData');
  10331. return false;
  10332. }
  10333. };
  10334. const getGistData = async (token, gistId, fileName, test = false) => {
  10335. try {
  10336. const logStatus = scripts_echoLog({
  10337. text: i18n('gettingData')
  10338. });
  10339. const {
  10340. result,
  10341. statusText,
  10342. status,
  10343. data
  10344. } = await tools_httpRequest({
  10345. url: `https://api.github.com/gists/${gistId}`,
  10346. headers: {
  10347. Accept: 'application/vnd.github.v3+json',
  10348. Authorization: `token ${token}`
  10349. },
  10350. responseType: 'json',
  10351. method: 'GET',
  10352. timeout: 3e4
  10353. });
  10354. if (result === 'Success') {
  10355. if (data?.status === 200) {
  10356. const content = data.response?.files?.[fileName]?.content;
  10357. let formatedContent;
  10358. if (!content) {
  10359. logStatus.error(`Error:${i18n('noRemoteData')}`);
  10360. return false;
  10361. }
  10362. if (test) {
  10363. logStatus.success();
  10364. return true;
  10365. }
  10366. try {
  10367. formatedContent = JSON.parse(content);
  10368. } catch (error) {
  10369. logStatus.error(`Error:${i18n('errorRemoteDataFormat')}`);
  10370. return false;
  10371. }
  10372. logStatus.success();
  10373. return formatedContent;
  10374. }
  10375. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10376. return false;
  10377. }
  10378. logStatus.error(`${result}:${statusText}(${status})`);
  10379. return false;
  10380. } catch (error) {
  10381. throwError(error, 'getGistData');
  10382. return false;
  10383. }
  10384. };
  10385. const syncOptions = () => {
  10386. try {
  10387. const {
  10388. TOKEN,
  10389. GIST_ID,
  10390. FILE_NAME,
  10391. SYNC_HISTORY
  10392. } = GM_getValue('gistOptions') || {
  10393. TOKEN: '',
  10394. GIST_ID: '',
  10395. FILE_NAME: '',
  10396. SYNC_HISTORY: true
  10397. };
  10398. external_Swal_default().fire({
  10399. title: i18n('gistOptions'),
  10400. 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;">
  10401. ${i18n('upload2gist')}</button>` + `<button id="download-data" type="button" class="swal2-confirm swal2-styled" style="display: inline-block;">
  10402. ${i18n('downloadFromGist')}</button></p>`,
  10403. focusConfirm: false,
  10404. showLoaderOnConfirm: true,
  10405. 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>`,
  10406. preConfirm: async () => {
  10407. const token = $('#github-token').val();
  10408. const gistId = $('#gist-id').val();
  10409. const fileName = $('#file-name').val();
  10410. const syncHistory = $('#sync-history').prop('checked');
  10411. GM_setValue('gistOptions', {
  10412. TOKEN: token,
  10413. GIST_ID: gistId,
  10414. FILE_NAME: fileName,
  10415. SYNC_HISTORY: syncHistory
  10416. });
  10417. return await getGistData(token, gistId, fileName, true);
  10418. },
  10419. allowOutsideClick: () => !external_Swal_default().isLoading(),
  10420. confirmButtonText: i18n('saveAndTest'),
  10421. showCancelButton: true,
  10422. cancelButtonText: i18n('close')
  10423. }).then(({
  10424. value
  10425. }) => {
  10426. if (value) {
  10427. external_Swal_default().fire({
  10428. icon: 'success',
  10429. title: i18n('testSuccess')
  10430. }).then(syncOptions);
  10431. } else if (value !== undefined) {
  10432. external_Swal_default().fire({
  10433. icon: 'error',
  10434. title: i18n('testFailed')
  10435. }).then(syncOptions);
  10436. }
  10437. });
  10438. $('#upload-data').on('click', async () => {
  10439. const {
  10440. TOKEN,
  10441. GIST_ID,
  10442. FILE_NAME
  10443. } = GM_getValue('gistOptions') || {};
  10444. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10445. return external_Swal_default().fire({
  10446. icon: 'error',
  10447. title: i18n('saveAndTestNotice')
  10448. }).then(syncOptions);
  10449. }
  10450. external_Swal_default().fire({
  10451. icon: 'info',
  10452. title: i18n('processingData')
  10453. });
  10454. const data = {};
  10455. const names = GM_listValues();
  10456. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10457. for (const name of names) {
  10458. if (name === 'gistOptions' || /^[\w]+?Auth$/.test(name)) {
  10459. continue;
  10460. }
  10461. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10462. continue;
  10463. }
  10464. data[name] = GM_getValue(name);
  10465. }
  10466. external_Swal_default().update({
  10467. icon: 'info',
  10468. title: i18n('updatingData')
  10469. });
  10470. if (await setGistData(TOKEN, GIST_ID, FILE_NAME, data)) {
  10471. external_Swal_default().fire({
  10472. icon: 'success',
  10473. title: i18n('syncDataSuccess')
  10474. });
  10475. } else {
  10476. external_Swal_default().fire({
  10477. icon: 'error',
  10478. title: i18n('syncDataFailed')
  10479. });
  10480. }
  10481. });
  10482. $('#download-data').on('click', async () => {
  10483. const {
  10484. TOKEN,
  10485. GIST_ID,
  10486. FILE_NAME
  10487. } = GM_getValue('gistOptions') || {};
  10488. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10489. return external_Swal_default().fire({
  10490. icon: 'error',
  10491. title: i18n('saveAndTestNotice')
  10492. }).then(syncOptions);
  10493. }
  10494. external_Swal_default().fire({
  10495. icon: 'info',
  10496. title: i18n('downloadingData')
  10497. });
  10498. const data = await getGistData(TOKEN, GIST_ID, FILE_NAME);
  10499. if (!data) {
  10500. return external_Swal_default().fire({
  10501. icon: 'error',
  10502. title: i18n('checkedNoData')
  10503. }).then(syncOptions);
  10504. }
  10505. external_Swal_default().update({
  10506. icon: 'info',
  10507. title: i18n('savingData')
  10508. });
  10509. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10510. for (const [ name, value ] of Object.entries(data)) {
  10511. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10512. continue;
  10513. }
  10514. GM_setValue(name, value);
  10515. }
  10516. external_Swal_default().fire({
  10517. icon: 'success',
  10518. title: i18n('syncDataSuccess')
  10519. });
  10520. });
  10521. } catch (error) {
  10522. throwError(error, 'syncOptions');
  10523. }
  10524. };
  10525. const dataSync = syncOptions;
  10526. class Setting {
  10527. name = 'Setting';
  10528. buttons = [ 'saveGlobalOptions', 'syncData', 'tasksHistory' ];
  10529. syncData = dataSync;
  10530. tasksHistory() {
  10531. GM_openInTab('https://auto-task-v4.hclonely.com/history.html', {
  10532. active: true
  10533. });
  10534. }
  10535. static test() {
  10536. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/setting.html';
  10537. }
  10538. before() {
  10539. try {
  10540. $('body').html('').addClass('auto-task-options');
  10541. } catch (error) {
  10542. throwError(error, 'Setting.before');
  10543. }
  10544. }
  10545. after() {
  10546. try {
  10547. this.#environment();
  10548. changeGlobalOptions('page');
  10549. whiteList('page');
  10550. $('input[name="other.twitterVerifyId"]').after(`<button id="getTwitterUserId" type="button">${i18n('getTwitterUserId')}</button>`);
  10551. $('#getTwitterUserId').on('click', () => {
  10552. this.#getId('twitterUser');
  10553. });
  10554. $('input[name="other.youtubeVerifyChannel"]').after(`<button id="getYoutubeChannelId" type="button">${i18n('getYoutubeChannelId')}</button>`);
  10555. $('#getYoutubeChannelId').on('click', () => {
  10556. this.#getId('youtubeChannel');
  10557. });
  10558. $('input[name^="position"]').on('input', function() {
  10559. const type = $(this).attr('name').replace('position.', '');
  10560. const xLabel = 'rightleft';
  10561. const yLabel = 'topbottpm';
  10562. switch (type) {
  10563. case 'buttonSideX':
  10564. case 'buttonSideY':
  10565. case 'buttonDistance':
  10566. {
  10567. const distance = $('input[name="position.buttonDistance"]').val();
  10568. const sideX = $('input[name="position.buttonSideX"]').val();
  10569. const sideY = $('input[name="position.buttonSideY"]').val();
  10570. if (![ 'right', 'left' ].includes(sideX)) {
  10571. break;
  10572. }
  10573. if (![ 'top', 'bottom' ].includes(sideY)) {
  10574. break;
  10575. }
  10576. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10577. break;
  10578. }
  10579. const distanceArr = distance.split(',');
  10580. $('#auto-task-buttons').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10581. break;
  10582. }
  10583.  
  10584. case 'showButtonSideX':
  10585. case 'showButtonSideY':
  10586. case 'showButtonDistance':
  10587. {
  10588. const distance = $('input[name="position.showButtonDistance"]').val();
  10589. const sideX = $('input[name="position.showButtonSideX"]').val();
  10590. const sideY = $('input[name="position.showButtonSideY"]').val();
  10591. if (![ 'right', 'left' ].includes(sideX)) {
  10592. break;
  10593. }
  10594. if (![ 'top', 'bottom' ].includes(sideY)) {
  10595. break;
  10596. }
  10597. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10598. break;
  10599. }
  10600. const distanceArr = distance.split(',');
  10601. $('div.show-button-div').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10602. break;
  10603. }
  10604.  
  10605. case 'logSideX':
  10606. case 'logSideY':
  10607. case 'logDistance':
  10608. {
  10609. const distance = $('input[name="position.logDistance"]').val();
  10610. const sideX = $('input[name="position.logSideX"]').val();
  10611. const sideY = $('input[name="position.logSideY"]').val();
  10612. if (![ 'right', 'left' ].includes(sideX)) {
  10613. break;
  10614. }
  10615. if (![ 'top', 'bottom' ].includes(sideY)) {
  10616. break;
  10617. }
  10618. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10619. break;
  10620. }
  10621. const distanceArr = distance.split(',');
  10622. $('#auto-task-info').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10623. break;
  10624. }
  10625.  
  10626. default:
  10627. break;
  10628. }
  10629. });
  10630. $('input[name^="hotKey"]').attr('readonly', 'readonly').off('keydown').on('keydown', function(event) {
  10631. let functionKey = '';
  10632. if (event.altKey) {
  10633. functionKey += 'alt + ';
  10634. } else if (event.ctrlKey) {
  10635. functionKey += 'ctrl + ';
  10636. } else if (event.shiftKey) {
  10637. functionKey += 'shift + ';
  10638. }
  10639. $(this).val(functionKey + (event.key.length === 1 ? event.key.toLowerCase() : ''));
  10640. });
  10641. } catch (error) {
  10642. throwError(error, 'Setting.after');
  10643. }
  10644. }
  10645. saveGlobalOptions() {
  10646. try {
  10647. saveData();
  10648. } catch (error) {
  10649. throwError(error, 'Setting.saveGlobalOptions');
  10650. }
  10651. }
  10652. #getId(social) {
  10653. try {
  10654. external_Swal_default().fire({
  10655. title: i18n('getId', i18n(social)),
  10656. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10657. <button id="link2id" data-type="${social}" class="swal2-confirm swal2-styled">获取id</button>`,
  10658. showCancelButton: true,
  10659. cancelButtonText: i18n('close'),
  10660. showConfirmButton: false
  10661. });
  10662. $('#link2id').on('click', async function() {
  10663. const link = $('#socialLink').val();
  10664. if (!link) {
  10665. return;
  10666. }
  10667. const type = $(this).attr('data-type');
  10668. if (type === 'twitterUser') {
  10669. const name = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || link;
  10670. $('#socialLink').val(await new social_Twitter().userName2id(name) || '');
  10671. } else if (type === 'youtubeChannel') {
  10672. const name = /^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www.youtube.com\/.*/.test(link) ? link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1] : link;
  10673. $('#socialLink').val((await getInfo(name, 'channel'))?.params?.channelId || '');
  10674. }
  10675. });
  10676. } catch (error) {
  10677. throwError(error, 'Setting.getId');
  10678. }
  10679. }
  10680. #environment() {
  10681. try {
  10682. const userAgent = (0, javascript_utils_umd_min.ua)();
  10683. const environmentForm = `<form id="environmentForm" class="auto-task-form">
  10684. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('name')}</td><td>${i18n('version')}</td></tr></thead><tbody>
  10685. <tr><td>${i18n('os')}</td><td>${userAgent.os}</td><td>${userAgent.osVersion}</td></tr>
  10686. <tr><td>${i18n('browser')}</td><td>${userAgent.browserZH}</td><td>${userAgent.browserVersion}</td></tr>
  10687. <tr><td>${i18n('scriptManager')}</td><td>${GM_info.scriptHandler}</td><td>${GM_info.version}</td></tr>
  10688. <tr><td>${i18n('script')}</td><td>${GM_info.script.name}</td><td>${GM_info.script.version}</td></tr>
  10689. </tbody></table></form>`;
  10690. $('body').append(`<h2>${i18n('environment')}</h2>${environmentForm}`);
  10691. } catch (error) {
  10692. throwError(error, 'Setting.environment');
  10693. }
  10694. }
  10695. }
  10696. const website_Setting = Setting;
  10697. class History extends website_Keylol {
  10698. name = 'History';
  10699. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect', 'clearHistory' ];
  10700. static test() {
  10701. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/history.html';
  10702. }
  10703. before() {
  10704. try {
  10705. $('body').html('<div class="container"></div>').addClass('auto-task-history');
  10706. const data = GM_listValues() || [];
  10707. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  10708. for (const item of tasksHistory) {
  10709. this.#addItem(item);
  10710. }
  10711. } catch (error) {
  10712. throwError(error, 'History.before');
  10713. }
  10714. }
  10715. clearHistory() {
  10716. try {
  10717. const data = GM_listValues() || [];
  10718. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  10719. for (const item of tasksHistory) {
  10720. GM_deleteValue(item);
  10721. }
  10722. external_Swal_default().fire({
  10723. title: i18n('clearHistoryFinished'),
  10724. icon: 'success'
  10725. });
  10726. } catch (error) {
  10727. throwError(error, 'History.clearHistory');
  10728. }
  10729. }
  10730. #addItem(item) {
  10731. try {
  10732. const tasksData = GM_getValue(item);
  10733. if (!tasksData?.tasks) {
  10734. return;
  10735. }
  10736. let html = '';
  10737. let title = '';
  10738. let link = '';
  10739. const [ website, id ] = item.split('-');
  10740. switch (website) {
  10741. case 'fawTasks':
  10742. title = `Freeanywhere[${id}]`;
  10743. link = `https://freeanywhere.net/#/giveaway/${id}`;
  10744. break;
  10745.  
  10746. case 'gasTasks':
  10747. title = `Giveawaysu[${id}]`;
  10748. link = `https://giveaway.su/giveaway/view/${id}`;
  10749. break;
  10750.  
  10751. case 'gcTasks':
  10752. title = `GiveeClub[${id}]`;
  10753. link = `https://givee.club/event/${id}`;
  10754. break;
  10755.  
  10756. case 'gkTasks':
  10757. title = `Givekey[${id}]`;
  10758. link = `https://givekey.ru/giveaway/${id}`;
  10759. break;
  10760.  
  10761. case 'gleamTasks':
  10762. title = `Gleam[${id}]`;
  10763. link = `https://gleam.io${id}`;
  10764. break;
  10765.  
  10766. case 'khTasks':
  10767. title = `keyhub[${id}]`;
  10768. link = `https://key-hub.eu/giveaway/${id}`;
  10769. break;
  10770.  
  10771. case 'prysTasks':
  10772. title = `Prys[${id}]`;
  10773. link = `https://prys.revadike.com/giveaway/?id=${id}`;
  10774. break;
  10775.  
  10776. default:
  10777. return;
  10778. }
  10779. for (const [ social, types ] of Object.entries(tasksData.tasks)) {
  10780. for (const [ type, tasks ] of Object.entries(types)) {
  10781. for (const task of tasks) {
  10782. 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>`;
  10783. }
  10784. }
  10785. }
  10786. $('.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>`);
  10787. $('span.delete-task').on('click', function() {
  10788. const itemName = $(this).attr('data-name');
  10789. if (itemName) {
  10790. GM_deleteValue(itemName);
  10791. $(`div.card[data-name="${itemName}"]`).remove();
  10792. external_Swal_default().fire({
  10793. title: i18n('clearTaskFinished'),
  10794. text: itemName,
  10795. icon: 'success'
  10796. });
  10797. } else {
  10798. external_Swal_default().fire({
  10799. title: i18n('clearTaskFailed'),
  10800. icon: 'error'
  10801. });
  10802. }
  10803. });
  10804. } catch (error) {
  10805. throwError(error, 'History.addItem');
  10806. }
  10807. }
  10808. }
  10809. const website_History = History;
  10810. const GiveawayHopper_defaultTasksTemplate = {
  10811. steam: {
  10812. groupLinks: [],
  10813. wishlistLinks: [],
  10814. followLinks: [],
  10815. curatorLinks: [],
  10816. curatorLikeLinks: []
  10817. },
  10818. twitter: {
  10819. userLinks: [],
  10820. retweetLinks: []
  10821. },
  10822. twitch: {
  10823. channelLinks: []
  10824. },
  10825. discord: {
  10826. serverLinks: []
  10827. },
  10828. youtube: {
  10829. channelLinks: []
  10830. },
  10831. extra: {
  10832. giveawayHopper: []
  10833. }
  10834. };
  10835. const GiveawayHopper_defaultTasks = JSON.stringify(GiveawayHopper_defaultTasksTemplate);
  10836. class GiveawayHopper extends website_Website {
  10837. name = 'GiveawayHopper';
  10838. undoneTasks = JSON.parse(GiveawayHopper_defaultTasks);
  10839. socialTasks = JSON.parse(GiveawayHopper_defaultTasks);
  10840. tasks = [];
  10841. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  10842. static test() {
  10843. return window.location.host === 'giveawayhopper.com';
  10844. }
  10845. async after() {
  10846. try {
  10847. if (!this.#checkLogin()) {
  10848. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  10849. }
  10850. this.#getGiveawayId();
  10851. } catch (error) {
  10852. throwError(error, 'GiveawayHopper.after');
  10853. }
  10854. }
  10855. async init() {
  10856. try {
  10857. const logStatus = scripts_echoLog({
  10858. text: i18n('initing')
  10859. });
  10860. if (!await this.#checkLeftKey()) {
  10861. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  10862. }
  10863. this.initialized = true;
  10864. logStatus.success();
  10865. return true;
  10866. } catch (error) {
  10867. throwError(error, 'GiveawayHopper.init');
  10868. return false;
  10869. }
  10870. }
  10871. async classifyTask(action) {
  10872. try {
  10873. if (!this.giveawayId) {
  10874. await this.#getGiveawayId();
  10875. }
  10876. const logStatus = scripts_echoLog({
  10877. text: i18n('getTasksInfo')
  10878. });
  10879. if (action === 'undo') {
  10880. this.socialTasks = GM_getValue(`giveawayHopperTasks-${this.giveawayId}`)?.tasks || JSON.parse(GiveawayHopper_defaultTasks);
  10881. }
  10882. const {
  10883. result,
  10884. statusText,
  10885. status,
  10886. data
  10887. } = await tools_httpRequest({
  10888. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/with-auth`,
  10889. method: 'GET',
  10890. responseType: 'json',
  10891. fetch: true,
  10892. headers: {
  10893. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10894. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10895. }
  10896. });
  10897. if (result === 'Success') {
  10898. if (data?.status === 200 && data?.response?.tasks) {
  10899. this.tasks = data.response.tasks;
  10900. for (const task of data.response.tasks) {
  10901. if (task.isDone) {
  10902. continue;
  10903. }
  10904. await tools_httpRequest({
  10905. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/visited`,
  10906. method: 'GET',
  10907. responseType: 'json',
  10908. fetch: true,
  10909. headers: {
  10910. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10911. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10912. }
  10913. });
  10914. if (task.category === 'Steam' && task.type === 'JoinGroup') {
  10915. const steamGroupLink = await getRedirectLink(`https://steamcommunity.com/gid/${task.group_id}`);
  10916. if (!steamGroupLink) {
  10917. continue;
  10918. }
  10919. if (action === 'undo') {
  10920. this.socialTasks.steam.groupLinks.push(steamGroupLink);
  10921. }
  10922. if (action === 'do') {
  10923. this.undoneTasks.steam.groupLinks.push(steamGroupLink);
  10924. }
  10925. continue;
  10926. }
  10927. if (task.category === 'Discord' && task.type === 'JoinServer') {
  10928. if (action === 'undo') {
  10929. this.socialTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  10930. }
  10931. if (action === 'do') {
  10932. this.undoneTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  10933. }
  10934. continue;
  10935. }
  10936. if ([ 'TikTok', 'YouTube', 'General' ].includes(task.category)) {
  10937. continue;
  10938. }
  10939. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${task.category}-${task.type}`);
  10940. }
  10941. logStatus.success();
  10942. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  10943. this.socialTasks = this.uniqueTasks(this.socialTasks);
  10944. if (window.DEBUG) {
  10945. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  10946. }
  10947. GM_setValue(`giveawayHopperTasks-${this.giveawayId}`, {
  10948. tasks: this.socialTasks,
  10949. time: new Date().getTime()
  10950. });
  10951. return true;
  10952. }
  10953. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10954. return false;
  10955. }
  10956. logStatus.error(`${result}:${statusText}(${status})`);
  10957. return false;
  10958. } catch (error) {
  10959. throwError(error, 'GiveawayHopper.classifyTask');
  10960. return false;
  10961. }
  10962. }
  10963. async verifyTask() {
  10964. try {
  10965. for (const task of this.tasks) {
  10966. if (task.isDone) {
  10967. continue;
  10968. }
  10969. const logStatus = scripts_echoLog({
  10970. text: `${i18n('verifyingTask')}[${task.displayName?.replace(':target', task.targetName) || task.name}]...`
  10971. });
  10972. if (!task.link) {
  10973. if (task.category === 'YouTube' && task.type === 'FollowAccount') {
  10974. task.link = `https://www.youtube.com/@${task.targetName}`;
  10975. } else if (task.category === 'TikTok' && task.type === 'FollowAccount') {
  10976. task.link = `https://www.tiktok.com/@${task.targetName}`;
  10977. } else if (task.category === 'Steam' && task.type === 'JoinGroup') {
  10978. task.link = '';
  10979. } else if (task.category === 'Discord' && task.type === 'JoinServer') {
  10980. task.link = '';
  10981. }
  10982. }
  10983. if (task.link) {
  10984. await tools_httpRequest({
  10985. 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}`,
  10986. method: 'GET',
  10987. fetch: true,
  10988. headers: {
  10989. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10990. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10991. }
  10992. });
  10993. }
  10994. await delay(1e3);
  10995. const postData = {
  10996. taskcategory: task.category,
  10997. taskname: task.type
  10998. };
  10999. if ([ 'YouTube', 'TikTok' ].includes(task.category)) {
  11000. postData.username = '1';
  11001. }
  11002. const {
  11003. result,
  11004. statusText,
  11005. status,
  11006. data
  11007. } = await tools_httpRequest({
  11008. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/complete`,
  11009. method: 'POST',
  11010. fetch: true,
  11011. headers: {
  11012. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  11013. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1]),
  11014. 'content-type': 'application/json'
  11015. },
  11016. dataType: 'json',
  11017. data: JSON.stringify(postData)
  11018. });
  11019. if (result === 'Success') {
  11020. if (data?.status === 200 && data?.response?.completed) {
  11021. logStatus.success();
  11022. continue;
  11023. }
  11024. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  11025. continue;
  11026. }
  11027. logStatus.error(`${result}:${statusText}(${status})`);
  11028. continue;
  11029. }
  11030. } catch (error) {
  11031. throwError(error, 'GiveawayHopper.verifyTask');
  11032. return false;
  11033. }
  11034. }
  11035. #getGiveawayId() {
  11036. try {
  11037. const giveawayId = window.location.pathname.split('/').at(-1);
  11038. if (giveawayId) {
  11039. this.giveawayId = giveawayId;
  11040. return true;
  11041. }
  11042. scripts_echoLog({
  11043. text: i18n('getFailed', 'GiveawayId')
  11044. });
  11045. return false;
  11046. } catch (error) {
  11047. throwError(error, 'GiveawayHopper.getGiveawayId');
  11048. return false;
  11049. }
  11050. }
  11051. #checkLogin() {
  11052. try {
  11053. if (!globalOptions.other.checkLogin) {
  11054. return true;
  11055. }
  11056. if ($('div.widget-connections-edit:contains("Log in")').length > 0) {
  11057. $('div.widget-connections-edit:contains("Log in") a')[0].click();
  11058. }
  11059. return true;
  11060. } catch (error) {
  11061. throwError(error, 'GiveawayHopper.checkLogin');
  11062. return false;
  11063. }
  11064. }
  11065. async #checkLeftKey() {
  11066. try {
  11067. if (!globalOptions.other.checkLeftKey) {
  11068. return true;
  11069. }
  11070. if ($('p.widget-single-prize span').length > 0 && parseInt($('p.widget-single-prize span').text()?.match(/\d+/)?.[0] || '0', 10) > 0) {
  11071. return true;
  11072. }
  11073. await external_Swal_default().fire({
  11074. icon: 'warning',
  11075. title: i18n('notice'),
  11076. text: i18n('noKeysLeft'),
  11077. confirmButtonText: i18n('confirm'),
  11078. cancelButtonText: i18n('cancel'),
  11079. showCancelButton: true
  11080. }).then(({
  11081. value
  11082. }) => {
  11083. if (value) {
  11084. window.close();
  11085. }
  11086. });
  11087. return true;
  11088. } catch (error) {
  11089. throwError(error, 'GiveawayHopper.checkLeftKey');
  11090. return false;
  11091. }
  11092. }
  11093. }
  11094. const website_GiveawayHopper = GiveawayHopper;
  11095. 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 ];
  11096. const websiteOptions = function(website, options) {
  11097. try {
  11098. let websiteOptionsForm = `<form id="websiteOptionsForm" class="auto-task-form">
  11099. <table class="auto-task-table"><thead><tr><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  11100. for (const [ option, value ] of Object.entries(options)) {
  11101. websiteOptionsForm += `<tr><td>${option}</td><td><input class="editOption" type="text" name="${option}" value="${value}"/></td></tr>`;
  11102. }
  11103. websiteOptionsForm += '</tbody></table></form>';
  11104. external_Swal_default().fire({
  11105. title: i18n('websiteOptions'),
  11106. html: websiteOptionsForm,
  11107. showConfirmButton: true,
  11108. confirmButtonText: i18n('save'),
  11109. showCancelButton: true,
  11110. cancelButtonText: i18n('close')
  11111. }).then(({
  11112. isConfirmed
  11113. }) => {
  11114. if (isConfirmed) {
  11115. $('#websiteOptionsForm').serializeArray().map(value => {
  11116. options[value.name] = value.value;
  11117. return value;
  11118. });
  11119. GM_setValue(`${website}Options`, options);
  11120. external_Swal_default().fire({
  11121. title: i18n('changeWebsiteOptionsSuccess'),
  11122. icon: 'success'
  11123. });
  11124. }
  11125. });
  11126. } catch (error) {
  11127. throwError(error, 'websiteOptions');
  11128. }
  11129. };
  11130. const options = websiteOptions;
  11131. const external_keyboardJS_namespaceObject = keyboardJS;
  11132. var external_keyboardJS_default = __webpack_require__.n(external_keyboardJS_namespaceObject);
  11133. const checkUpdate = async (updateLink, auto) => {
  11134. try {
  11135. const checkUrl = `${updateLink}package.json?time=${new Date().getTime()}`;
  11136. const {
  11137. result,
  11138. statusText,
  11139. status,
  11140. data
  11141. } = await tools_httpRequest({
  11142. url: checkUrl,
  11143. responseType: 'json',
  11144. method: 'GET',
  11145. timeout: 3e4
  11146. });
  11147. if (result === 'Success') {
  11148. if (data?.response?.version) {
  11149. return data.response;
  11150. }
  11151. if (!auto) {
  11152. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${data?.statusText}(${data?.status})]`);
  11153. }
  11154. return false;
  11155. }
  11156. if (!auto) {
  11157. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${result}:${statusText}(${status})]`);
  11158. }
  11159. return false;
  11160. } catch (error) {
  11161. throwError(error, 'checkUpdate');
  11162. return false;
  11163. }
  11164. };
  11165. const hasNewVersion = (currentVersion, remoteVersion) => {
  11166. try {
  11167. const [ currentRealVersion ] = currentVersion.split('-');
  11168. const [ remoteRealVersion, isPreview ] = remoteVersion.split('-');
  11169. if (isPreview && !globalOptions.other.receivePreview) {
  11170. return false;
  11171. }
  11172. const [ currentVersion1, currentVersion2, currentVersion3 ] = currentRealVersion.split('.').map(value => parseInt(value, 10));
  11173. const [ remoteVersion1, remoteVersion2, remoteVersion3 ] = remoteRealVersion.split('.').map(value => parseInt(value, 10));
  11174. if (remoteVersion1 > currentVersion1) {
  11175. return true;
  11176. }
  11177. if (remoteVersion1 < currentVersion1) {
  11178. return false;
  11179. }
  11180. if (remoteVersion2 > currentVersion2) {
  11181. return true;
  11182. }
  11183. if (remoteVersion2 < currentVersion2) {
  11184. return false;
  11185. }
  11186. if (remoteVersion3 > currentVersion3) {
  11187. return true;
  11188. }
  11189. return false;
  11190. } catch (error) {
  11191. throwError(error, 'compareVersion');
  11192. return false;
  11193. }
  11194. };
  11195. const updateChecker = async () => {
  11196. try {
  11197. const currentVersion = GM_info.script.version;
  11198. const updateSource = globalOptions.other.autoUpdateSource.toLowerCase();
  11199. const updateLinks = {
  11200. github: 'https://github.com/HCLonely/auto-task-new/raw/main/',
  11201. jsdelivr: 'https://cdn.jsdelivr.net/gh/HCLonely/auto-task-v4@main/',
  11202. standby: 'https://auto-task-v4.hclonely.com/'
  11203. };
  11204. let version;
  11205. let updateLink = '';
  11206. let packageData;
  11207. if ([ 'github', 'jsdelivr', 'standby' ].includes(updateSource)) {
  11208. updateLink = updateLinks[updateSource];
  11209. packageData = await checkUpdate(updateLink, false);
  11210. } else {
  11211. updateLink = updateLinks.github;
  11212. packageData = await checkUpdate(updateLink, true);
  11213. if (!packageData) {
  11214. updateLink = updateLinks.jsdelivr;
  11215. packageData = await checkUpdate(updateLink, true);
  11216. if (!packageData) {
  11217. updateLink = updateLinks.standby;
  11218. packageData = await checkUpdate(updateLink, true);
  11219. }
  11220. }
  11221. }
  11222. if (packageData) {
  11223. version = packageData.version || currentVersion;
  11224. } else {
  11225. version = currentVersion;
  11226. scripts_echoLog({}).error(i18n('checkUpdateFailed'));
  11227. }
  11228. if (packageData && hasNewVersion(currentVersion, version)) {
  11229. scripts_echoLog({
  11230. html: `<li><font>${i18n('newVersionNotice', version, `${updateLink}dist/${GM_info.script.name}.user.js`)}</font></li>`
  11231. });
  11232. scripts_echoLog({
  11233. html: `<li>${i18n('updateText', version)}</li><ol class="update-text">${packageData.change?.map(change => `<li>${change}</li>`).join('')}<li>${i18n('updateHistory')}</li></ol>`
  11234. });
  11235. }
  11236. } catch (error) {
  11237. throwError(error, 'updateChecker');
  11238. }
  11239. };
  11240. const scripts_updateChecker = updateChecker;
  11241. window.STYLE = GM_addStyle(auto_task.A + GM_getResourceText('style'));
  11242. window.DEBUG = !!globalOptions.other?.debug;
  11243. window.TRACE = !!globalOptions.other?.debug && typeof console.trace === 'function';
  11244. const loadScript = async () => {
  11245. if (window.name === 'ATv4_twitchAuth' && window.location.hostname === 'www.twitch.tv') {
  11246. const authToken = external_Cookies_default().get('auth-token');
  11247. const isLogin = !!external_Cookies_default().get('login');
  11248. if (isLogin) {
  11249. GM_setValue('twitchAuth', {
  11250. authToken: authToken,
  11251. clientVersion: __twilightBuildID,
  11252. clientId: commonOptions?.headers?.['Client-ID'],
  11253. deviceId: commonOptions?.headers?.['Device-ID'],
  11254. clientSessionId: window.localStorage.local_storage_app_session_id.replace(/"/g, '')
  11255. });
  11256. window.close();
  11257. external_Swal_default().fire('', i18n('closePageNotice'));
  11258. } else {
  11259. external_Swal_default().fire('', i18n('needLogin'));
  11260. }
  11261. return;
  11262. }
  11263. if (window.name === 'ATv4_redditAuth' && window.location.hostname === 'www.reddit.com') {
  11264. const betaButton = $('#redesign-beta-optin-btn');
  11265. if (betaButton.length > 0) {
  11266. return betaButton[0].click();
  11267. }
  11268. window.close();
  11269. external_Swal_default().fire('', i18n('closePageNotice'));
  11270. return;
  11271. }
  11272. let website;
  11273. for (const Website of Websites) {
  11274. if (Website.test()) {
  11275. website = new Website();
  11276. break;
  11277. }
  11278. }
  11279. if (!website) {
  11280. console.log('%c%s', 'color:#ff0000', 'Auto-Task[Warning]: 脚本停止加载,当前网站不支持!');
  11281. return;
  11282. }
  11283. if (website?.before) {
  11284. await website?.before();
  11285. }
  11286. $('body').append(`
  11287. <div id="auto-task-info"
  11288. style="display:${globalOptions.other.defaultShowLog ? 'block' : 'none'};
  11289. ${globalOptions.position.logSideX}:${globalOptions.position.logDistance.split(',')[0]}px;
  11290. ${globalOptions.position.logSideY}:${globalOptions.position.logDistance.split(',')[1]}px;">
  11291. </div>
  11292. <div id="auto-task-buttons"
  11293. style="display:${globalOptions.other.defaultShowButton ? 'block' : 'none'};
  11294. ${globalOptions.position.buttonSideX}:${globalOptions.position.buttonDistance.split(',')[0]}px;
  11295. ${globalOptions.position.buttonSideY}:${globalOptions.position.buttonDistance.split(',')[1]}px;">
  11296. </div>
  11297. <div class="show-button-div"
  11298. style="display:${globalOptions.other.defaultShowButton ? 'none' : 'block'};
  11299. ${globalOptions.position.showButtonSideX}:${globalOptions.position.showButtonDistance.split(',')[0]}px;
  11300. ${globalOptions.position.showButtonSideY}:${globalOptions.position.showButtonDistance.split(',')[1]}px;">
  11301. <a class="auto-task-website-btn"
  11302. href="javascript:void(0);"
  11303. target="_self"
  11304. title="${i18n('showButton')}"> </a>
  11305. </div>
  11306. `);
  11307. $('div.show-button-div').on('click', () => {
  11308. $('#auto-task-buttons').show();
  11309. $('div.show-button-div').hide();
  11310. });
  11311. const toggleLog = () => {
  11312. const $this = $('#toggle-log');
  11313. const status = $this.attr('data-status');
  11314. if (status === 'show') {
  11315. $('#auto-task-info').hide();
  11316. $this.attr('data-status', 'hide').text(i18n('showLog'));
  11317. } else {
  11318. $('#auto-task-info').show();
  11319. $this.attr('data-status', 'show').text(i18n('hideLog'));
  11320. }
  11321. };
  11322. external_keyboardJS_default().bind(globalOptions.hotKey.doTaskKey, () => {
  11323. if (website.doTask) {
  11324. website.doTask();
  11325. }
  11326. });
  11327. external_keyboardJS_default().bind(globalOptions.hotKey.undoTaskKey, () => {
  11328. if (website.undoTask) {
  11329. website.undoTask();
  11330. }
  11331. });
  11332. external_keyboardJS_default().bind(globalOptions.hotKey.toggleLogKey, toggleLog);
  11333. if (website?.after) {
  11334. await website?.after();
  11335. }
  11336. if (website?.buttons && $('#auto-task-buttons').children().length === 0) {
  11337. $('#auto-task-buttons').addClass(`${website.name}-buttons`);
  11338. for (const button of website.buttons) {
  11339. if (website[button]) {
  11340. const btnElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">${i18n(button)}</a></p>`);
  11341. btnElement.find('a.auto-task-website-btn').on('click', () => {
  11342. website[button]();
  11343. });
  11344. $('#auto-task-buttons').append(btnElement);
  11345. }
  11346. }
  11347. }
  11348. const hideButtonElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">
  11349. ${i18n('hideButton')}</a></p>`);
  11350. hideButtonElement.find('a.auto-task-website-btn').on('click', () => {
  11351. $('#auto-task-buttons').hide();
  11352. $('div.show-button-div').show();
  11353. });
  11354. 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'}">
  11355. ${globalOptions.other.defaultShowLog ? i18n('hideLog') : i18n('showLog')}</a></p>`);
  11356. toggleLogElement.find('a.auto-task-website-btn').on('click', toggleLog);
  11357. $('#auto-task-buttons').append(hideButtonElement).append(toggleLogElement);
  11358. if (website?.options) {
  11359. GM_registerMenuCommand(i18n('changeWebsiteOptions'), () => {
  11360. options(website.name, website.options);
  11361. });
  11362. }
  11363. if (website.name !== 'Setting') {
  11364. GM_registerMenuCommand(i18n('changeGlobalOptions'), () => {
  11365. changeGlobalOptions('swal');
  11366. });
  11367. GM_registerMenuCommand(i18n('settingPage'), () => {
  11368. GM_openInTab('https://auto-task-v4.hclonely.com/setting.html', {
  11369. active: true
  11370. });
  11371. });
  11372. }
  11373. console.log('%c%s', 'color:#1bbe1a', 'Auto-Task[Load]: 脚本加载完成');
  11374. const [ v1, v2 ] = GM_info.version.split('.');
  11375. if (!(parseInt(v1, 10) >= 5 && parseInt(v2, 10) >= 2)) {
  11376. scripts_echoLog({}).error(i18n('versionNotMatched'));
  11377. }
  11378. if (!GM_getValue('notice')) {
  11379. external_Swal_default().fire({
  11380. title: i18n('swalNotice'),
  11381. icon: 'warning'
  11382. }).then(() => {
  11383. GM_openInTab(i18n('noticeLink'), {
  11384. active: true
  11385. });
  11386. GM_setValue('notice', new Date().getTime());
  11387. });
  11388. scripts_echoLog({
  11389. html: `<li><font class="warning">${i18n('echoNotice', i18n('noticeLink'))}</font></li>`
  11390. }).font?.find('a').on('click', () => {
  11391. GM_setValue('notice', new Date().getTime());
  11392. });
  11393. }
  11394. scripts_updateChecker();
  11395. };
  11396. if (window.location.hostname === 'discord.com') {
  11397. const LocalStorage = window.localStorage;
  11398. if (window.name === 'ATv4_discordAuth') {
  11399. window.localStorage.removeItem = () => true;
  11400. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11401. if (discordAuth && discordAuth.length > 0) {
  11402. GM_setValue('discordAuth', {
  11403. auth: discordAuth
  11404. });
  11405. window.close();
  11406. external_Swal_default().fire('', i18n('closePageNotice'));
  11407. } else {
  11408. external_Swal_default().fire({
  11409. text: i18n('getDiscordAuthFailed'),
  11410. icon: 'error'
  11411. });
  11412. }
  11413. } else {
  11414. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11415. if (discordAuth && discordAuth.length > 0) {
  11416. GM_setValue('discordAuth', {
  11417. auth: discordAuth
  11418. });
  11419. }
  11420. }
  11421. } else if (window.location.hostname === 'opquests.com') {
  11422. loadScript();
  11423. } else if ((window.name === 'ATv4_updateStoreAuth' || GM_getValue('ATv4_updateStoreAuth')) && window.location.host === 'store.steampowered.com') {
  11424. $(() => {
  11425. if ($('[data-miniprofile]').length === 0) {
  11426. return;
  11427. }
  11428. const storeSessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11429. if (storeSessionID) {
  11430. GM_deleteValue('ATv4_updateStoreAuth');
  11431. GM_setValue('steamStoreAuth', {
  11432. storeSessionID: storeSessionID
  11433. });
  11434. window.close();
  11435. external_Swal_default().fire('', i18n('closePageNotice'));
  11436. } else {
  11437. external_Swal_default().fire({
  11438. title: 'Error: Get "sessionID" failed',
  11439. icon: 'error'
  11440. });
  11441. }
  11442. });
  11443. } else if ((window.name === 'ATv4_updateCommunityAuth' || GM_getValue('ATv4_updateCommunityAuth')) && window.location.host === 'steamcommunity.com') {
  11444. $(() => {
  11445. const steam64Id = document.body.innerHTML.match(/g_steamID = "(.+?)";/)?.[1];
  11446. const communitySessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11447. if (steam64Id && communitySessionID) {
  11448. GM_deleteValue('ATv4_updateCommunityAuth');
  11449. GM_setValue('steamCommunityAuth', {
  11450. steam64Id: steam64Id,
  11451. communitySessionID: communitySessionID
  11452. });
  11453. window.close();
  11454. external_Swal_default().fire('', i18n('closePageNotice'));
  11455. } else {
  11456. setTimeout(() => {
  11457. external_Swal_default().fire({
  11458. title: 'Error: Get "sessionID" failed',
  11459. icon: 'error'
  11460. });
  11461. }, 3e3);
  11462. }
  11463. });
  11464. } else {
  11465. if (window.location.hostname === 'key-hub.eu') {
  11466. unsafeWindow.keyhubtracker = 1;
  11467. unsafeWindow.gaData = {};
  11468. }
  11469. $(loadScript);
  11470. }
  11471. }();
  11472. })();