auto-task-v4

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

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

  1. // ==UserScript==
  2. // @name auto-task-v4
  3. // @namespace auto-task-v4
  4. // @version 4.5.8
  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 *://discord.com/*
  27. // @include *://www.twitch.tv/*
  28. // @include *://www.youtube.com/*
  29. // @include *://*.reddit.com/*
  30. // @include *://twitter.com/settings/account?k*
  31. // @include *://x.com/settings/account*
  32. // @include *://steamcommunity.com/*
  33. // @include *://store.steampowered.com/*
  34. // @include https://auto-task-v4.hclonely.com/setting.html
  35. // @include https://auto-task-v4.hclonely.com/history.html
  36.  
  37. // @grant GM_setValue
  38. // @grant GM_getValue
  39. // @grant GM_listValues
  40. // @grant GM_deleteValue
  41. // @grant GM_addStyle
  42. // @grant GM_xmlhttpRequest
  43. // @grant GM_registerMenuCommand
  44. // @grant GM_info
  45. // @grant GM_openInTab
  46. // @grant GM_setClipboard
  47. // @grant GM_getResourceText
  48. // @grant GM_cookie
  49. // @grant GM_addValueChangeListener
  50. // @grant GM_removeValueChangeListener
  51. // @grant unsafeWindow
  52. // @grant window.close
  53. // @grant window.localStorage
  54. // @grant window.focus
  55.  
  56. // @connect cdn.jsdelivr.net
  57. // @connect store.steampowered.com
  58. // @connect steamcommunity.com
  59. // @connect login.steampowered.com
  60. // @connect twitter.com
  61. // @connect x.com
  62. // @connect api.twitter.com
  63. // @connect youtube.com
  64. // @connect www.youtube.com
  65. // @connect facebook.com
  66. // @connect instagram.com
  67. // @connect vk.com
  68. // @connect twitch.tv
  69. // @connect www.twitch.tv
  70. // @connect gql.twitch.tv
  71. // @connect github.com
  72. // @connect discordapp.com
  73. // @connect discord.gg
  74. // @connect discord.com
  75. // @connect www.reddit.com
  76. // @connect oauth.reddit.com
  77. // @connect raw.githubusercontent.com
  78. // @connect t.me
  79. // @connect bit.ly
  80. // @connect giveaway.su
  81. // @connect google.com
  82. // @connect www.vloot.io
  83. // @connect givee.club
  84. // @connect gleam.io
  85. // @connect www.indiedb.com
  86. // @connect key-hub.eu
  87. // @connect opquests.com
  88. // @connect itch.io
  89. // @connect auto-task-v4.hclonely.com
  90. // @connect *
  91. // @require https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
  92. // @require https://cdn.jsdelivr.net/npm/js-cookie@3.0.1/dist/js.cookie.min.js
  93. // @require https://cdn.jsdelivr.net/npm/regenerator-runtime@0.13.5/runtime.min.js
  94. // @require https://cdn.jsdelivr.net/npm/js-sha1@0.6.0/src/sha1.min.js
  95. // @require https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js
  96. // @resource style https://cdn.jsdelivr.net/npm/sweetalert2@11.3.5/dist/sweetalert2.min.css
  97. // @require https://cdn.jsdelivr.net/npm/keyboardjs@2.6.4/dist/keyboard.min.js
  98. // @require https://cdn.jsdelivr.net/npm/dayjs@1.10.7/dayjs.min.js
  99.  
  100. // @noframes
  101. // ==/UserScript==
  102.  
  103. console.log('%c%s', 'color:blue', 'Auto-Task[Load]: 脚本开始加载');
  104. (function() {
  105. var __webpack_modules__ = {
  106. 991: function(__unused_webpack_module, exports) {
  107. !function(e, n) {
  108. true ? n(exports) : 0;
  109. }(this, function(e) {
  110. 'use strict';
  111. var t = function() {
  112. return (t = Object.assign || function(e) {
  113. for (var n, o = 1, t = arguments.length; o < t; o++) {
  114. for (var r in n = arguments[o]) {
  115. Object.prototype.hasOwnProperty.call(n, r) && (e[r] = n[r]);
  116. }
  117. }
  118. return e;
  119. }).apply(this, arguments);
  120. };
  121. function r(e, n, o) {
  122. if (o || 2 === arguments.length) {
  123. for (var t, r = 0, i = n.length; r < i; r++) {
  124. !t && r in n || ((t = t || Array.prototype.slice.call(n, 0, r))[r] = n[r]);
  125. }
  126. }
  127. return e.concat(t || Array.prototype.slice.call(n));
  128. }
  129. function d(e) {
  130. return '[object Object]' === n(e);
  131. }
  132. function l(e, n) {
  133. var o = r(r([], n || [], !0), [ '_' ], !1).join('|');
  134. return e.replace(new RegExp('(('.concat(o, ')[a-z])+'), 'g'), function(e, n) {
  135. return n.replace(new RegExp(o), '').toLocaleUpperCase();
  136. });
  137. }
  138. var n = function(e) {
  139. return Object.prototype.toString.call(e);
  140. };
  141. var o = (i.prototype.init = function() {
  142. try {
  143. this.getSystemName(), this.getBrowserName();
  144. } catch (e) {
  145. console.warn('[UA formatter error] '.concat(e));
  146. }
  147. }, i.prototype.getEngine = function() {
  148. var e = this.agent;
  149. return -1 !== e.indexOf('Trident') ? 'Trident' : -1 !== e.indexOf('Firefox') ? 'Gecko' : -1 !== e.indexOf('Presto') ? 'Presto' : 'WebKit';
  150. }, i.prototype.getSystemName = function() {
  151. var e, n = (this.agent.match(/^[a-z]+\/\d+\.\d+\s?\(([a-z\d\s:;./_-]+)\)/i) || [])[1];
  152. try {
  153. var o = '';
  154. if (/Windows/i.test(n)) {
  155. var t = (n.match(/NT\s(\d+\.\d+)/) || [])[1];
  156. switch (this.info.os = 'Windows', t) {
  157. case '6.3':
  158. o = '8.1';
  159. break;
  160.  
  161. case '6.2':
  162. o = '8';
  163. break;
  164.  
  165. case '6.1':
  166. o = '7';
  167. break;
  168.  
  169. case '5.2':
  170. case '5.1':
  171. o = 'XP';
  172. break;
  173.  
  174. default:
  175. o = t;
  176. }
  177. return this.info.device = 'PC', void (this.info.osVersion = o);
  178. }
  179. if (/^Macintosh/i.test(n)) {
  180. return o = (n.match(/X\s((\d+(_|\.))+\d+)/) || [])[1], this.info.os = 'Macintosh',
  181. this.info.device = 'PC', void (this.info.osVersion = null !== (e = null == o ? void 0 : o.replace(/_/g, '.')) && void 0 !== e ? e : 'Unknown');
  182. }
  183. if (/^iPad/i.test(n)) {
  184. return o = (n.match(/((\d+_)+\d+)/) || [])[1], this.info.os = 'iPad',
  185. this.info.device = 'Tablet', void (this.info.osVersion = o.replace(/_/g, '.'));
  186. }
  187. if (/^iPhone/i.test(n)) {
  188. return o = (n.match(/((\d+_)+\d+)/) || [])[1], this.info.os = 'iPhone',
  189. this.info.device = 'Mobile', void (this.info.osVersion = o.replace(/_/g, '.'));
  190. }
  191. if (-1 !== n.indexOf('Android')) {
  192. var r = (n.match(/Android\s((\d+\.?)+\d?)/) || [])[1];
  193. return this.info.device = 'Mobile', this.info.os = 'Android', void (this.info.osVersion = r);
  194. }
  195. if (/Linux\s[a-z\d_]+/.test(n)) {
  196. return this.info.os = 'Linux', void (this.info.osVersion = 'Unknown');
  197. }
  198. this.info.os = 'Unknown', this.info.osVersion = 'Unknown';
  199. } catch (e) {
  200. this.info.os = 'Unknown', this.info.osVersion = 'Unknown';
  201. }
  202. }, i.prototype.getBrowserName = function() {
  203. var e = Object.keys(this.browserNameMap).map(function(e) {
  204. return new RegExp(''.concat(e, '(\\/|\\s)(\\d+\\.)+\\d+'));
  205. }), n = 1 < (n = (this.agent.match(/[a-z\d]+(\/|\s)(\d+\.)+\d+/gi) || []).filter(function(n) {
  206. return -1 !== e.findIndex(function(e) {
  207. return e.test(n);
  208. });
  209. })).length && !/^Safari/.test(n[n.length - 1]) ? n.reverse() : n;
  210. this.info = t(t({}, this.info), this._formatBrowserVersion(n[0]));
  211. }, i.prototype._formatBrowserVersion = function(e) {
  212. var n, o, t, r;
  213. try {
  214. 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++) {
  215. var d = u[f], l = d[0], h = d[1];
  216. if (new RegExp(l).test(s)) {
  217. c = h;
  218. break;
  219. }
  220. }
  221. var p = {
  222. browserVersion: null != a ? a : 'Unknown',
  223. browser: null !== (t = c.en) && void 0 !== t ? t : 'Unknown',
  224. browserZH: null !== (r = (null == c ? void 0 : c.zh) || c.en) && void 0 !== r ? r : 'Unknown'
  225. };
  226. return 'Trident' === s && (p.browserVersion = {
  227. '4.0': 8,
  228. '5.0': 9,
  229. '6.0': 10,
  230. '7.0': 11
  231. }[a]), p;
  232. } catch (e) {
  233. return console.warn('[UA formatter error] '.concat(e)), {
  234. browser: 'Unknown',
  235. browserVersion: 'Unknown'
  236. };
  237. }
  238. }, i);
  239. function i(e) {
  240. this.agent = '', this.info = {
  241. browser: '',
  242. browserZH: '',
  243. browserVersion: '',
  244. os: '',
  245. osVersion: '',
  246. device: 'Unknown',
  247. engine: 'WebKit'
  248. }, this.browserNameMap = {
  249. MicroMessenger: {
  250. en: 'MicroMessenger',
  251. zh: '微信'
  252. },
  253. MetaSr: {
  254. en: 'MetaSr',
  255. zh: '搜狗浏览器'
  256. },
  257. 'QQ(Browser)?': {
  258. en: 'QQBrowser',
  259. zh: 'QQ浏览器'
  260. },
  261. UCBrowser: {
  262. en: 'UCBrowser',
  263. zh: 'UC浏览器'
  264. },
  265. '2345Explorer': {
  266. en: '2345Explorer',
  267. zh: '2345极速浏览器'
  268. },
  269. Mb2345Browser: {
  270. en: 'Mb2345Browser',
  271. zh: '2345手机浏览器'
  272. },
  273. Trident: {
  274. en: 'Internet Explorer'
  275. },
  276. 'Edge?': {
  277. en: 'Edge'
  278. },
  279. OPR: {
  280. en: 'Opera'
  281. },
  282. Vivaldi: {
  283. en: 'Vivaldi'
  284. },
  285. Firefox: {
  286. en: 'Firefox'
  287. },
  288. Chrome: {
  289. en: 'Chrome'
  290. },
  291. Safari: {
  292. en: 'Safari'
  293. }
  294. }, this.agent = e, this.init();
  295. var n = this.info, o = n.browser, e = n.browserVersion, n = n.osVersion;
  296. this.info = t(t({}, this.info), {
  297. engine: this.getEngine(),
  298. browserVersion: 'Safari' === o ? n : e
  299. });
  300. }
  301. function s() {
  302. this.cookies = {}, this.init();
  303. }
  304. var a = new (s.prototype.init = function() {
  305. var o = {};
  306. document.cookie.split(/;\s/).forEach(function(e) {
  307. var n = e.split(/=/), e = n[0], n = n[1];
  308. o[e] = n;
  309. }), this.cookies = o;
  310. }, s.prototype.getItem = function(e) {
  311. return this.cookies[e];
  312. }, s.prototype.getAllItems = function() {
  313. return this.cookies;
  314. }, s.prototype.setItem = function(e, n, o, t, r, i) {
  315. document.cookie = ''.concat(e, '=').concat(n).concat(o ? '; expires='.concat(o) : '').concat(t ? '; path='.concat(t) : '').concat(r ? '; domain='.concat(r) : '').concat(i ? '; secure' : '');
  316. }, s)();
  317. e.countDown = function e(n, o, t, r) {
  318. if (!window) {
  319. throw new Error('window is not defind.');
  320. }
  321. if (0 < n) {
  322. return r && r(), n--, window[o] = window.setTimeout(function() {
  323. e(n, o, t, r);
  324. }, 1e3), function() {
  325. return clearTimeout(window[o]);
  326. };
  327. }
  328. clearTimeout(window[o]), t && t();
  329. }, e.createRandomID = function(e) {
  330. void 0 === e && (e = 12);
  331. for (var n = [], o = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''), t = o.length, r = 0; r < e; r++) {
  332. n.push(o[Math.round(Math.random() * t)]);
  333. }
  334. return n.join('');
  335. }, e.dCookie = a, e.debounce = function(o, t, r) {
  336. var i;
  337. void 0 === t && (t = 0);
  338. var s = r = void 0 === r ? !1 : r;
  339. return function() {
  340. var e = this, n = arguments;
  341. s && (o.apply(this, arguments), s = !1), clearTimeout(i), i = setTimeout(function() {
  342. r ? s = !0 : o.apply(e, n);
  343. }, t);
  344. };
  345. }, e.deepCopy = function e(n) {
  346. if (d(n) || Array.isArray(n)) {
  347. var o, t = Array.isArray(n) ? [] : {};
  348. for (o in n) {
  349. t[o] = e(n[o]);
  350. }
  351. return t;
  352. }
  353. return n;
  354. }, e.formatQueryParams = function(e) {
  355. e = null === (e = /\?(?<params>(.*)=.+)/.exec(decodeURIComponent(e))) || void 0 === e ? void 0 : e.groups;
  356. if (!e) {
  357. return {};
  358. }
  359. for (var n = e.params.split('&'), t = {}, o = 0; o < n.length; o++) {
  360. n[o].replace(/([^?&]*)=([^?&]*)/, function(e, n, o) {
  361. return t[n] = o, e;
  362. });
  363. }
  364. return t;
  365. }, e.formatThousandth = function(e) {
  366. 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, '$&,');
  367. return ''.concat(e).concat(n ? '.'.concat(n) : '');
  368. }, e.generateTree = function e(n, o, t, r) {
  369. for (var i = [], s = 0; s < n.length; s++) {
  370. var a = n[s];
  371. a[t] === o && (i.push(a), a.children = e(n, a[null != r ? r : 'id'], t, r));
  372. }
  373. return i;
  374. }, e.isEmpty = function(e) {
  375. 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);
  376. }, e.isFunction = function(e) {
  377. return '[object Function]' === n(e);
  378. }, e.isImageUrl = function(e) {
  379. return /\.((png)|(jpe?g)|(gif)|(svg)|(webp))$/gi.test(e);
  380. }, e.isObject = d, e.isRegexp = function(e) {
  381. return '[object RegExp]' === n(e);
  382. }, e.objectKeyToCamelCase = function e(n, o, t) {
  383. if (Array.isArray(n)) {
  384. for (var r = [], i = 0; i < n.length; i++) {
  385. r[i] = e(o && n[i][o] ? n[i][o] : n[i], o, t);
  386. }
  387. } else if (d(n)) {
  388. r = {};
  389. for (var s = o && n[o] ? n[o] : n, a = 0, c = Object.entries(s); a < c.length; a++) {
  390. var f = (u = c[a])[0], u = u[1];
  391. Array.isArray(u) || d(s) ? r[l(f, t)] = e(u, o, t) : r[l(f, t)] = u;
  392. }
  393. } else {
  394. r = n;
  395. }
  396. return r;
  397. }, e.realType = n, e.searchParams = function(e, n) {
  398. return void 0 === e && (e = null === location || void 0 === location ? void 0 : location.search),
  399. new URLSearchParams(e).get(n);
  400. }, e.toLowerCamelCase = l, e.toUnderline = function(e) {
  401. return e.replace(/([A-Z])/g, function(e) {
  402. return '_'.concat(e.toLocaleLowerCase());
  403. });
  404. }, e.ua = function(e) {
  405. return void 0 === e && (e = navigator.userAgent), new o(e).info;
  406. }, Object.defineProperty(e, '__esModule', {
  407. value: !0
  408. });
  409. });
  410. },
  411. 675: function(module, __webpack_exports__, __webpack_require__) {
  412. 'use strict';
  413. __webpack_require__.d(__webpack_exports__, {
  414. A: function() {
  415. return __WEBPACK_DEFAULT_EXPORT__;
  416. }
  417. });
  418. var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(601);
  419. 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__);
  420. var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(314);
  421. 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__);
  422. 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());
  423. ___CSS_LOADER_EXPORT___.push([ module.id, `.colorful-button,#auto-task-buttons a.auto-task-website-btn,.show-button-div a.auto-task-website-btn,body.auto-task-options .auto-task-form table button{position:relative;padding:5px 10px;text-align:center;color:#fff;text-decoration:none;background:linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);border-radius:30px;background-size:400%;text-transform:capitalize}.colorful-button:hover,#auto-task-buttons a.auto-task-website-btn:hover,.show-button-div a.auto-task-website-btn:hover,body.auto-task-options .auto-task-form table button:hover{transform:scale(1.05);box-shadow:0 6px 20px rgba(0,0,0,.3);cursor:pointer}.colorful-button:hover::before,#auto-task-buttons a.auto-task-website-btn:hover::before,.show-button-div a.auto-task-website-btn:hover::before,body.auto-task-options .auto-task-form table button:hover::before{filter:blur(10px);opacity:1}.colorful-button::before,#auto-task-buttons a.auto-task-website-btn::before,.show-button-div a.auto-task-website-btn::before,body.auto-task-options .auto-task-form table button::before{content:"";position:absolute;top:-5px;left:-5px;right:-5px;bottom:-5px;z-index:-1;background:linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);border-radius:40px;background-size:400%;opacity:-1}#auto-task-info{z-index:999999999 !important}#auto-task-info{position:fixed;bottom:10px;right:10px;width:60%;max-width:500px;max-height:60%;overflow-y:auto;color:#000;background-color:#fff;padding-left:5px;border:solid 2px #add8e6;border-radius:10px}#auto-task-info li{text-align:left}#auto-task-info li a.high-light{color:#00aeff;font-weight:bold}#auto-task-info .success{color:green}#auto-task-info .error{color:red}#auto-task-info .warning{color:blue}#auto-task-info .info{color:#ff0}#auto-task-info .update-text{color:green;border:solid 2px #8dcb69;margin:5px 10px 5px 20px;border-radius:10px;padding:5px 20px}.auto-task-keylol{text-decoration:none !important}.auto-task-keylol{display:inline-block;text-transform:capitalize;margin-left:10px;border:solid 1px;border-radius:5px;padding:0 2px}.auto-task-keylol[selected=selected]{background-color:blue !important;color:#fff !important}.auto-task-form table{font-family:verdana,arial,sans-serif;font-size:11px;color:#333;border-width:1px;border-color:#999;border-collapse:collapse;width:100%}.auto-task-form table thead td{border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9;font-weight:bold;background-color:#fff}.auto-task-form table tbody tr{background-color:#d4e3e5}.auto-task-form table tbody tr:hover{background-color:#ff6 !important}.auto-task-form table tbody tr th{background-color:#c3dde0;border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9;text-transform:capitalize}.auto-task-form table tbody tr td{border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9}.swal2-modal{width:70% !important;max-width:1000px !important}body.auto-task-options{padding-top:10px;text-align:center}body.auto-task-options .auto-task-form{width:80%;max-width:1000px;margin:0 auto;padding-bottom:20px}body.auto-task-options .auto-task-form table input.editOption{width:80%}body.auto-task-options .auto-task-form table #getTwitterUserId,body.auto-task-options .auto-task-form table #getYoutubeChannelId{margin-top:5px}body.auto-task-options .auto-task-form table button{z-index:1}body.auto-task-options .auto-task-form table input[type=text]{outline-style:none;border:1px solid #ccc;border-radius:3px;padding:5px 10px;font-size:14px}body.auto-task-options .auto-task-form table input[type=text]:focus{border-color:#66afe9;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}body.auto-task-options .auto-task-form table label{position:relative;width:160px;height:80px;cursor:pointer;transform:scale(0.25);margin:-25% 0;top:-30px;display:inline-block}body.auto-task-options .auto-task-form table label input{position:relative;z-index:1;appearance:none}body.auto-task-options .auto-task-form table label input:checked~span{background:#05be05;box-shadow:0 15px 25px rgba(5,190,5,.4)}body.auto-task-options .auto-task-form table label input:checked~span i{left:84px}body.auto-task-options .auto-task-form table label input:checked~span i::before{background:#05be05;box-shadow:35px 0 0 #05be05}body.auto-task-options .auto-task-form table label input:checked~span i::after{bottom:12px;height:15px;border-bottom-left-radius:15px;border-bottom-right-radius:15px;background:#05be05}body.auto-task-options .auto-task-form table label span{position:absolute;top:0;left:0;width:100%;height:100%;background:#fe0000;border-radius:80px;transition:.5s;box-shadow:0 15px 25px rgba(254,0,0,.4)}body.auto-task-options .auto-task-form table label span i{position:absolute;top:4px;left:4px;width:72px;height:72px;background:#fff;border-radius:50%}body.auto-task-options .auto-task-form table label span i::before{content:"";position:absolute;top:22px;left:12px;width:12px;height:12px;border-radius:50%;background:#fe0000;box-shadow:35px 0 0 #fe0000;transition:.5s}body.auto-task-options .auto-task-form table label span i::after{content:"";position:absolute;bottom:15px;left:calc(50% - 15px);width:30px;height:6px;border-radius:6px;background:#fe0000;transition:.5s}body.auto-task-history{font-size:15px;font-weight:400;line-height:1.5}body.auto-task-history .container a{color:#007bff;text-decoration:none;background-color:rgba(0,0,0,0)}body.auto-task-history .container .card{width:80%;max-width:800px;border-radius:10px;background:rgba(118,118,118,.1019607843);border-top:1px solid rgba(255,255,255,.5019607843);-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);box-shadow:0 15px 25px rgba(0,0,0,.1019607843);margin:20px auto;position:relative;display:flex;flex-direction:column;word-wrap:break-word;-webkit-background-clip:border-box;background-clip:border-box;border:1px solid rgba(0,0,0,.125);border-radius:.25rem}body.auto-task-history .container .card .title{text-align:center;font-size:30px;font-weight:bold;margin:5px 0}body.auto-task-history .container .card .title a:hover{text-decoration:none;background:#93e1ff;border-radius:10px;padding:3px}body.auto-task-history .container .card ul{margin-bottom:25px}body.auto-task-history .container .card ul li{margin-bottom:5px;line-height:20px}body.auto-task-history .container .card ul a:hover{text-decoration:underline}body.auto-task-history .container .card .delete-task{right:10px;width:38px;height:35px;position:absolute;font-size:24px;cursor:pointer;border-radius:10px}body.auto-task-history .container .card .delete-task:hover{background:#fff}body.auto-task-history .container .card .time{right:5px;position:absolute;bottom:0;color:#e83e8c;font-family:'SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace';font-size:15px}#auto-task-buttons,.show-button-div{z-index:999999999 !important}#auto-task-buttons,.show-button-div{position:fixed;top:30px;right:15px;width:124px;transform:scale(0.85)}#auto-task-buttons p,.show-button-div p{margin:5px !important}#auto-task-buttons p,.show-button-div p{line-height:30px;height:40px;text-align:center}#auto-task-buttons a.auto-task-website-btn,.show-button-div a.auto-task-website-btn{width:105px;line-height:27px;font-size:20px;display:block}.show-button-div{width:20px}.auto-task-capitalize{text-transform:capitalize !important}.swal2-file:focus,.swal2-input:focus,.swal2-textarea:focus{box-shadow:inset 0px 0px 4px 1px rgba(100,150,200,.5) !important}.swal2-checkbox-custom{align-items:center;justify-content:center;background:#fff;color:inherit;margin:1em auto}.swal2-checkbox-custom input{flex-shrink:0;margin:0 .4em}.giveaway-actions #getKey{display:none !important}.auto-task-giveaway-status{color:#fff;border-radius:10px;padding:0 5px;margin-left:5px}.auto-task-giveaway-status.active{background-color:#5cb85c}.auto-task-giveaway-status.not-active{background-color:#d9534f}`, '' ]);
  424. const __WEBPACK_DEFAULT_EXPORT__ = ___CSS_LOADER_EXPORT___.toString();
  425. },
  426. 314: function(module) {
  427. 'use strict';
  428. module.exports = function(cssWithMappingToString) {
  429. var list = [];
  430. list.toString = function toString() {
  431. return this.map(function(item) {
  432. var content = '';
  433. var needLayer = typeof item[5] !== 'undefined';
  434. if (item[4]) {
  435. content += '@supports ('.concat(item[4], ') {');
  436. }
  437. if (item[2]) {
  438. content += '@media '.concat(item[2], ' {');
  439. }
  440. if (needLayer) {
  441. content += '@layer'.concat(item[5].length > 0 ? ' '.concat(item[5]) : '', ' {');
  442. }
  443. content += cssWithMappingToString(item);
  444. if (needLayer) {
  445. content += '}';
  446. }
  447. if (item[2]) {
  448. content += '}';
  449. }
  450. if (item[4]) {
  451. content += '}';
  452. }
  453. return content;
  454. }).join('');
  455. };
  456. list.i = function i(modules, media, dedupe, supports, layer) {
  457. if (typeof modules === 'string') {
  458. modules = [ [ null, modules, undefined ] ];
  459. }
  460. var alreadyImportedModules = {};
  461. if (dedupe) {
  462. for (var k = 0; k < this.length; k++) {
  463. var id = this[k][0];
  464. if (id != null) {
  465. alreadyImportedModules[id] = true;
  466. }
  467. }
  468. }
  469. for (var _k = 0; _k < modules.length; _k++) {
  470. var item = [].concat(modules[_k]);
  471. if (dedupe && alreadyImportedModules[item[0]]) {
  472. continue;
  473. }
  474. if (typeof layer !== 'undefined') {
  475. if (typeof item[5] === 'undefined') {
  476. item[5] = layer;
  477. } else {
  478. item[1] = '@layer'.concat(item[5].length > 0 ? ' '.concat(item[5]) : '', ' {').concat(item[1], '}');
  479. item[5] = layer;
  480. }
  481. }
  482. if (media) {
  483. if (!item[2]) {
  484. item[2] = media;
  485. } else {
  486. item[1] = '@media '.concat(item[2], ' {').concat(item[1], '}');
  487. item[2] = media;
  488. }
  489. }
  490. if (supports) {
  491. if (!item[4]) {
  492. item[4] = ''.concat(supports);
  493. } else {
  494. item[1] = '@supports ('.concat(item[4], ') {').concat(item[1], '}');
  495. item[4] = supports;
  496. }
  497. }
  498. list.push(item);
  499. }
  500. };
  501. return list;
  502. };
  503. },
  504. 601: function(module) {
  505. 'use strict';
  506. module.exports = function(i) {
  507. return i[1];
  508. };
  509. }
  510. };
  511. var __webpack_module_cache__ = {};
  512. function __webpack_require__(moduleId) {
  513. var cachedModule = __webpack_module_cache__[moduleId];
  514. if (cachedModule !== undefined) {
  515. return cachedModule.exports;
  516. }
  517. var module = __webpack_module_cache__[moduleId] = {
  518. id: moduleId,
  519. exports: {}
  520. };
  521. __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  522. return module.exports;
  523. }
  524. !function() {
  525. __webpack_require__.n = function(module) {
  526. var getter = module && module.__esModule ? function() {
  527. return module['default'];
  528. } : function() {
  529. return module;
  530. };
  531. __webpack_require__.d(getter, {
  532. a: getter
  533. });
  534. return getter;
  535. };
  536. }();
  537. !function() {
  538. __webpack_require__.d = function(exports, definition) {
  539. for (var key in definition) {
  540. if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  541. Object.defineProperty(exports, key, {
  542. enumerable: true,
  543. get: definition[key]
  544. });
  545. }
  546. }
  547. };
  548. }();
  549. !function() {
  550. __webpack_require__.o = function(obj, prop) {
  551. return Object.prototype.hasOwnProperty.call(obj, prop);
  552. };
  553. }();
  554. var __webpack_exports__ = {};
  555. !function() {
  556. 'use strict';
  557. const external_Swal_namespaceObject = Swal;
  558. var external_Swal_default = __webpack_require__.n(external_Swal_namespaceObject);
  559. const external_Cookies_namespaceObject = Cookies;
  560. var external_Cookies_default = __webpack_require__.n(external_Cookies_namespaceObject);
  561. var auto_task = __webpack_require__(675);
  562. var javascript_utils_umd_min = __webpack_require__(991);
  563. const getFinalUrl = (responseHeaders, finalUrl) => {
  564. const realFinalUrl = responseHeaders?.split('\n')?.find(header => header.includes('location') ? header.replace('loctation:', '').trim() : null);
  565. return realFinalUrl || finalUrl;
  566. };
  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. data.finalUrl = getFinalUrl(data.responseHeaders, data.finalUrl);
  608. if (options.responseType === 'json' && data?.response && typeof data.response !== 'object') {
  609. try {
  610. data.response = JSON.parse(data.responseText);
  611. } catch (error) {}
  612. }
  613. resolve({
  614. result: 'Success',
  615. statusText: 'Load',
  616. status: 600,
  617. data: data,
  618. options: options
  619. });
  620. }
  621. },
  622. ...options
  623. };
  624. GM_xmlhttpRequest(requestObj);
  625. });
  626. if (window.DEBUG) {
  627. console.log('%cAuto-Task[httpRequest]:', 'color:blue', JSON.stringify(result));
  628. }
  629. if (result.status !== 600 && times < 2) {
  630. return await httpRequest(options, times + 1);
  631. }
  632. return result;
  633. } catch (error) {
  634. console.log('%cAuto-Task[httpRequest]:', 'color:red', JSON.stringify({
  635. errorMsg: error,
  636. options: options
  637. }));
  638. throwError(error, 'httpRequest');
  639. return {
  640. result: 'JsError',
  641. statusText: 'Error',
  642. status: 604,
  643. error: error,
  644. options: options
  645. };
  646. }
  647. };
  648. const tools_httpRequest = httpRequest;
  649. const echoLog = ({
  650. type,
  651. text,
  652. html,
  653. id
  654. }) => {
  655. const emptyStatus = {
  656. success: () => emptyStatus,
  657. error: () => emptyStatus,
  658. warning: () => emptyStatus,
  659. info: () => emptyStatus,
  660. view: () => emptyStatus
  661. };
  662. try {
  663. let ele;
  664. if (type) {
  665. switch (type) {
  666. case 'joiningSteamGroup':
  667. case 'leavingSteamGroup':
  668. case 'gettingSteamGroupId':
  669. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/groups/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  670. break;
  671.  
  672. case 'joiningSteamOfficialGroup':
  673. case 'leavingSteamOfficialGroup':
  674. case 'gettingSteamOfficialGroupId':
  675. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/games/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  676. break;
  677.  
  678. case 'subscribingForum':
  679. case 'unsubscribingForum':
  680. case 'gettingForumId':
  681. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/app/${text}/discussions/" target="_blank">${text}</a>]...<font></font></li>`);
  682. break;
  683.  
  684. case 'followingCurator':
  685. case 'unfollowingCurator':
  686. case 'gettingCuratorId':
  687. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/${text?.includes('/') ? text : `curator/${text}`}" target="_blank">${text}</a>]...<font></font></li>`);
  688. break;
  689.  
  690. case 'addingToWishlist':
  691. case 'removingFromWishlist':
  692. case 'followingGame':
  693. case 'unfollowingGame':
  694. case 'gettingSubid':
  695. case 'addingFreeLicense':
  696. case 'requestingPlayTestAccess':
  697. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/app/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  698. break;
  699.  
  700. case 'addingFreeLicenseSubid':
  701. ele = $(`<li>${i18n('addingFreeLicense')}[<a href="https://steamdb.info/sub/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  702. break;
  703.  
  704. case 'favoritingWorkshop':
  705. case 'unfavoritingWorkshop':
  706. case 'gettingWorkshopAppId':
  707. case 'votingUpWorkshop':
  708. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/sharedfiles/filedetails/?id=${text}" target="_blank">
  709. ${text}</a>]...<font></font></li>`);
  710. break;
  711.  
  712. case 'gettingAnnouncementParams':
  713. case 'likingAnnouncement':
  714. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/news/app/${text}/view/${id}" target="_blank">
  715. ${id}</a>]...<font></font></li>`);
  716. break;
  717.  
  718. case 'joiningDiscordServer':
  719. case 'gettingDiscordGuild':
  720. ele = $(`<li>${i18n(type)}[<a href="https://discord.com/invite/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  721. break;
  722.  
  723. case 'leavingDiscordServer':
  724. ele = $(`<li>${i18n(type)}[<a href="https://discord.com/channels/@me/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  725. break;
  726.  
  727. case 'updateDiscordAuth':
  728. ele = $(`<li style="color:red;">${i18n('updateDiscordAuth')}</li>`);
  729. break;
  730.  
  731. case 'followingTwitchChannel':
  732. case 'unfollowingTwitchChannel':
  733. case 'gettingTwitchChannelId':
  734. ele = $(`<li>${i18n(type)}[<a href="https://www.twitch.tv/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  735. break;
  736.  
  737. case 'gettingInsUserId':
  738. case 'followingIns':
  739. case 'unfollowingIns':
  740. ele = $(`<li>${i18n(type)}[<a href="https://www.instagram.com/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  741. break;
  742.  
  743. case 'gettingTwitterUserId':
  744. case 'followingTwitterUser':
  745. case 'unfollowingTwitterUser':
  746. ele = $(`<li>${i18n(type)}[<a href="https://x.com/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  747. break;
  748.  
  749. case 'retweetting':
  750. case 'unretweetting':
  751. ele = $(`<li>${i18n(type)}${text}...<font></font></li>`);
  752. break;
  753.  
  754. case 'joiningReddit':
  755. case 'leavingReddit':
  756. ele = $(`<li>${i18n(type)}[<a href="https://www.reddit.com/r/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  757. break;
  758.  
  759. case 'followingRedditUser':
  760. case 'unfollowingRedditUser':
  761. ele = $(`<li>${i18n(type)}[<a href="https://www.reddit.com/user/${text?.replace('u_', '')}" target="_blank">
  762. ${text?.replace('u_', '')}</a>]...<font></font></li>`);
  763. break;
  764.  
  765. case 'followingYtbChannel':
  766. case 'unfollowingYtbChannel':
  767. ele = $(`<li>${i18n(type)}[<a href="https://www.youtube.com/channel/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  768. break;
  769.  
  770. case 'likingYtbVideo':
  771. case 'unlikingYtbVideo':
  772. ele = $(`<li>${i18n(type)}[<a href="https://www.youtube.com/watch?v=${text}" target="_blank">${text}</a>]...<font></font></li>`);
  773. break;
  774.  
  775. case 'gettingVkId':
  776. case 'joiningVkGroup':
  777. case 'leavingVkGroup':
  778. case 'joiningVkPublic':
  779. case 'leavingVkPublic':
  780. case 'sendingVkWall':
  781. case 'deletingVkWall':
  782. ele = $(`<li>${i18n(type)}[<a href="https://vk.com/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  783. break;
  784.  
  785. case 'visitingLink':
  786. ele = $(`<li>${i18n('visitingLink')}[<a href="${text}" target="_blank">${text}</a>]...<font></font></li>`);
  787. break;
  788.  
  789. case 'verifyingInsAuth':
  790. case 'text':
  791. ele = $(`<li>${i18n(text)}<font></font></li>`);
  792. break;
  793.  
  794. case 'html':
  795. ele = $(text || html);
  796. break;
  797.  
  798. case 'whiteList':
  799. ele = $(`<li><font class="warning">${i18n('skipTask')}[${text}(${id})](${i18n('whiteList')})</font></li>`);
  800. break;
  801.  
  802. case 'globalOptionsSkip':
  803. ele = $(`<li>${i18n('skipTaskOption')}<font class="warning">${text}</font></li>`);
  804. break;
  805.  
  806. default:
  807. ele = $(`<li>${i18n('unKnown')}:${type}(${text})...<font></font></li>`);
  808. break;
  809. }
  810. } else if (text) {
  811. ele = $(`<li>${i18n(text)}<font></font></li>`);
  812. } else if (html) {
  813. ele = $(html);
  814. } else {
  815. ele = $('<li><font></font></li>');
  816. }
  817. ele.addClass('card-text');
  818. $('#auto-task-info').append(ele);
  819. ele[0]?.scrollIntoView();
  820. const font = ele.find('font');
  821. const status = {
  822. font: font,
  823. success(text = 'Success', html = false) {
  824. this.font?.attr('class', '').addClass('success');
  825. html ? this.font?.html(text) : this.font?.text(text);
  826. return this;
  827. },
  828. error(text = 'Error', html = false) {
  829. this.font?.attr('class', '').addClass('error');
  830. html ? this.font?.html(text) : this.font?.text(text);
  831. return this;
  832. },
  833. warning(text = 'Warning', html = false) {
  834. this.font?.attr('class', '').addClass('warning');
  835. html ? this.font?.html(text) : this.font?.text(text);
  836. return this;
  837. },
  838. info(text = 'Info', html = false) {
  839. this.font?.attr('class', '').addClass('info');
  840. html ? this.font?.html(text) : this.font?.text(text);
  841. return this;
  842. },
  843. view() {
  844. this.font?.[0].scrollIntoView();
  845. return this;
  846. }
  847. };
  848. return status;
  849. } catch (error) {
  850. throwError(error, 'echoLog');
  851. return emptyStatus;
  852. }
  853. };
  854. const scripts_echoLog = echoLog;
  855. const unique = array => {
  856. try {
  857. return [ ...new Set(array) ];
  858. } catch (error) {
  859. throwError(error, 'unique');
  860. return [];
  861. }
  862. };
  863. const delay = (time = 1e3) => new Promise(resolve => {
  864. setTimeout(() => {
  865. resolve(true);
  866. }, time);
  867. });
  868. const getRedirectLink = async link => {
  869. try {
  870. if (!link) {
  871. return null;
  872. }
  873. const redirectLinksCache = GM_getValue('redirectLinks') || {};
  874. if (redirectLinksCache[link]) {
  875. redirectLinksCache[link];
  876. }
  877. return await tools_httpRequest({
  878. url: link,
  879. method: 'GET'
  880. }).then(({
  881. data
  882. }) => {
  883. if (data?.finalUrl) {
  884. redirectLinksCache[link] = data.finalUrl;
  885. GM_setValue('redirectLinks', redirectLinksCache);
  886. return data.finalUrl;
  887. }
  888. return null;
  889. });
  890. } catch (error) {
  891. throwError(error, 'getRedirectLink');
  892. return null;
  893. }
  894. };
  895. const visitLink = async (link, options) => {
  896. try {
  897. const logStatus = scripts_echoLog({
  898. type: 'visitLink',
  899. text: link
  900. });
  901. return await tools_httpRequest({
  902. url: link,
  903. method: 'GET',
  904. ...options
  905. }).then(({
  906. result,
  907. statusText,
  908. status
  909. }) => {
  910. if (result === 'Success') {
  911. logStatus.success();
  912. return true;
  913. }
  914. logStatus.error(`${result}:${statusText}(${status})`);
  915. return false;
  916. });
  917. } catch (error) {
  918. throwError(error, 'visitLink');
  919. return false;
  920. }
  921. };
  922. const getUrlQuery = url => {
  923. try {
  924. const query = {};
  925. if (url) {
  926. if (url.includes('?')) {
  927. url.split('?')[1].replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  928. query[key] = value;
  929. return str;
  930. });
  931. }
  932. } else {
  933. window.location.search.replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  934. query[key] = value;
  935. return str;
  936. });
  937. }
  938. return query;
  939. } catch (error) {
  940. throwError(error, 'getUrlQuery');
  941. return {};
  942. }
  943. };
  944. const getUuid = () => {
  945. const uuidUrl = URL.createObjectURL(new Blob()).toString();
  946. return uuidUrl.slice(uuidUrl.lastIndexOf('/') + 1);
  947. };
  948. const stringToColour = str => {
  949. try {
  950. let hash = 0;
  951. for (let i = 0; i < str.length; i++) {
  952. hash = str.charCodeAt(i) + ((hash << 5) - hash);
  953. }
  954. let colour = '#';
  955. for (let i = 0; i < 3; i++) {
  956. const value = hash >> i * 8 & 255;
  957. colour += `00${value.toString(16)}`.slice(-2);
  958. }
  959. return colour;
  960. } catch (error) {
  961. throwError(error, 'stringToColour');
  962. return '#fff';
  963. }
  964. };
  965. const defaultGlobalOptions = {
  966. doTask: {
  967. discord: {
  968. servers: true
  969. },
  970. instagram: {
  971. users: true
  972. },
  973. twitch: {
  974. channels: true
  975. },
  976. twitter: {
  977. users: true,
  978. retweets: true
  979. },
  980. vk: {
  981. names: true
  982. },
  983. youtube: {
  984. channels: true,
  985. likes: true
  986. },
  987. reddit: {
  988. reddits: true
  989. },
  990. steam: {
  991. groups: true,
  992. officialGroups: true,
  993. wishlists: true,
  994. follows: true,
  995. forums: true,
  996. workshops: true,
  997. curators: true,
  998. workshopVotes: true,
  999. announcements: true,
  1000. licenses: true,
  1001. playtests: true
  1002. }
  1003. },
  1004. undoTask: {
  1005. discord: {
  1006. servers: true
  1007. },
  1008. instagram: {
  1009. users: true
  1010. },
  1011. twitch: {
  1012. channels: true
  1013. },
  1014. twitter: {
  1015. users: true,
  1016. retweets: true
  1017. },
  1018. vk: {
  1019. names: true
  1020. },
  1021. youtube: {
  1022. channels: true,
  1023. likes: true
  1024. },
  1025. reddit: {
  1026. reddits: true
  1027. },
  1028. steam: {
  1029. groups: true,
  1030. officialGroups: true,
  1031. wishlists: true,
  1032. follows: true,
  1033. forums: true,
  1034. workshops: true,
  1035. curators: true
  1036. }
  1037. },
  1038. ASF: {
  1039. AsfEnabled: false,
  1040. AsfIpcUrl: '',
  1041. AsfIpcPassword: '',
  1042. AsfBotname: 'asf'
  1043. },
  1044. position: {
  1045. buttonSideX: 'right',
  1046. buttonSideY: 'top',
  1047. buttonDistance: '15,30',
  1048. showButtonSideX: 'right',
  1049. showButtonSideY: 'top',
  1050. showButtonDistance: '15,30',
  1051. logSideX: 'right',
  1052. logSideY: 'bottom',
  1053. logDistance: '10,10'
  1054. },
  1055. hotKey: {
  1056. doTaskKey: 'alt + d',
  1057. undoTaskKey: 'alt + u',
  1058. toggleLogKey: 'alt + l'
  1059. },
  1060. other: {
  1061. twitterVerifyId: '783214',
  1062. youtubeVerifyChannel: 'UCrXUsMBcfTVqwAS7DKg9C0Q',
  1063. autoUpdateSource: 'jsdelivr',
  1064. language: 'zh',
  1065. checkLogin: true,
  1066. checkLeftKey: true,
  1067. defaultShowButton: true,
  1068. defaultShowLog: true,
  1069. debug: false,
  1070. receivePreview: true
  1071. }
  1072. };
  1073. const userDefinedGlobalOptions = GM_getValue('globalOptions') || {};
  1074. const assignObject = (obj1, obj2) => {
  1075. try {
  1076. const newObj = {};
  1077. for (const [ key, value ] of Object.entries(obj1)) {
  1078. if (Object.prototype.toString.call(value) === '[object Object]' && Object.prototype.toString.call(obj2[key]) === '[object Object]') {
  1079. newObj[key] = assignObject(value, obj2[key]);
  1080. } else {
  1081. newObj[key] = obj2[key] ?? value;
  1082. }
  1083. }
  1084. return newObj;
  1085. } catch (error) {
  1086. throwError(error, 'assignObject');
  1087. return defaultGlobalOptions;
  1088. }
  1089. };
  1090. const globalOptions = assignObject(defaultGlobalOptions, userDefinedGlobalOptions);
  1091. const saveData = () => {
  1092. try {
  1093. const data = {};
  1094. $('#globalOptionsForm').serializeArray().map(value => {
  1095. data[value.name] = value.value;
  1096. return value;
  1097. });
  1098. $.makeArray($('#globalOptionsForm input')).map(element => {
  1099. const name = $(element).attr('name');
  1100. const keys = name.split('.');
  1101. if (keys.length === 3) {
  1102. globalOptions[keys[0]][keys[1]][keys[2]] = data[name] ? data[name] === 'on' ? true : data[name] : false;
  1103. } else if (keys.length === 2) {
  1104. globalOptions[keys[0]][keys[1]] = data[name] ? data[name] === 'on' ? true : data[name] : false;
  1105. }
  1106. return element;
  1107. });
  1108. GM_setValue('globalOptions', globalOptions);
  1109. external_Swal_default().fire({
  1110. title: i18n('changeGlobalOptionsSuccess'),
  1111. icon: 'success'
  1112. });
  1113. } catch (error) {
  1114. throwError(error, 'saveData');
  1115. }
  1116. };
  1117. const changeGlobalOptions = showType => {
  1118. try {
  1119. let globalOptionsForm = `<form id="globalOptionsForm" class="auto-task-form">
  1120. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  1121. for (const [ type, data1 ] of Object.entries(globalOptions)) {
  1122. for (const [ option, data2 ] of Object.entries(data1)) {
  1123. if ([ 'other', 'position', 'hotKey', 'ASF' ].includes(type)) {
  1124. if (typeof data2 === 'boolean') {
  1125. 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>`;
  1126. } else {
  1127. 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>`;
  1128. }
  1129. } else {
  1130. for (const [ socialType, data3 ] of Object.entries(data2)) {
  1131. 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>`;
  1132. }
  1133. }
  1134. }
  1135. }
  1136. globalOptionsForm += '</tbody></table></form>';
  1137. if (showType === 'swal') {
  1138. external_Swal_default().fire({
  1139. title: i18n('globalOptions'),
  1140. html: globalOptionsForm,
  1141. showConfirmButton: true,
  1142. confirmButtonText: i18n('save'),
  1143. showCancelButton: true,
  1144. cancelButtonText: i18n('close')
  1145. }).then(({
  1146. isConfirmed
  1147. }) => {
  1148. if (isConfirmed) {
  1149. saveData();
  1150. }
  1151. });
  1152. } else {
  1153. $('body').append(`<h2>${i18n('globalOptions')}</h2>${globalOptionsForm}`);
  1154. }
  1155. } catch (error) {
  1156. throwError(error, 'changeGlobalOptions');
  1157. }
  1158. };
  1159. const data = {
  1160. website: '网站',
  1161. type: '类型',
  1162. edit: '编辑',
  1163. whiteList: '白名单',
  1164. skipTask: '跳过撤销任务',
  1165. whiteListOptions: '白名单设置',
  1166. changeWhiteListOption: '设置白名单(%0)',
  1167. whiteListNotFound: '找不到此项白名单: %0',
  1168. changeWhiteListSuccess: '白名单修改成功,刷新生效!',
  1169. changeWebsiteOptions: '网站设置',
  1170. changeGlobalOptions: '全局设置',
  1171. ok: '是',
  1172. save: '保存',
  1173. close: '关闭',
  1174. return: '返回',
  1175. option: '选项',
  1176. value: '值',
  1177. websiteOptions: '当前网站设置',
  1178. changeWebsiteOptionsSuccess: '更改当前网站设置成功,刷新生效!',
  1179. changeGlobalOptionsSuccess: '更改全局设置成功,刷新生效!',
  1180. needLogin: '请先登录!',
  1181. getTasksInfo: '正在获取并处理任务信息...',
  1182. gettingKey: '正在获取Key...',
  1183. verifyingTask: '正在验证任务',
  1184. notice: '自动任务脚本提醒',
  1185. noKeysLeft: '此页面已经没有剩余key了,是否关闭?',
  1186. giveawayEnded: '此活动已结束,是否关闭?',
  1187. giveawayNotWork: '此活动因某些原因(已结束/暂停/未开始...)不可用(如果是脚本误判请及时反馈),是否关闭?',
  1188. confirm: '确定',
  1189. cancel: '取消',
  1190. unKnown: '未知',
  1191. unKnownTaskType: '未识别的任务',
  1192. doing: '正在做任务',
  1193. allTasksComplete: '所有任务已完成!',
  1194. getTaskIdFailed: '获取任务Id失败!',
  1195. initSuccess: '%0 初始化成功!',
  1196. initFailed: '%0 初始化失败!',
  1197. errorLink: '链接错误: %0',
  1198. needInit: '请先初始化',
  1199. verifyingAuth: '正在验证%0凭证...',
  1200. updatingAuth: '正在更新%0凭证...',
  1201. refreshingToken: '正在刷新%0凭证...',
  1202. settingToken: '正在设置%0凭证...',
  1203. steamStoreTab: 'Steam商店(弹窗)',
  1204. steamCommunityTab: 'Steam社区(弹窗)',
  1205. initing: '正在初始化...',
  1206. getFailed: '获取%0失败!',
  1207. checkLoginFailed: '检测登录状态失败!',
  1208. checkLeftKeyFailed: '检测剩余Key失败!',
  1209. userId: '用户Id',
  1210. joiningGiveaway: '正在加入赠Key',
  1211. needJoinGiveaway: '需要先加入赠Key',
  1212. cannotUndo: '此网站不支持取消任务',
  1213. verifyAuth: '正在验证 %0 凭证...',
  1214. closePageNotice: '如果此页面没有自动关闭,请自行关闭本页面。',
  1215. errorReport: '检测到脚本报错,是否前往反馈BUG?',
  1216. visitingLink: '正在访问链接: ',
  1217. doTask: '做任务',
  1218. undoTask: '撤销任务',
  1219. verifyTask: '验证任务',
  1220. getKey: '获取Key',
  1221. selectAll: '全选',
  1222. selectNone: '全不选',
  1223. invertSelect: '反选',
  1224. doFreeTask: '加入免费赠品',
  1225. doPointTask: '加入点数赠品',
  1226. skipTaskOption: '设置中已配置跳过任务',
  1227. other: '其他',
  1228. globalOptions: '全局设置',
  1229. checkLogin: '登录检测</br>需要登录的网站自动登录,部分网站支持',
  1230. checkLeftKey: '剩余Key检测</br>赠Key活动结束提示是否关闭,部分网站支持',
  1231. twitterVerifyId: '通过尝试关注该账号验证Twitter凭证</br>默认为Twitter官方帐号 783214</br>不想关注官方账号可以改为自己的帐号',
  1232. youtubeVerifyChannel: '通过尝试订阅该频道验证YouTube凭证</br>默认为YouTube官方频道 UCrXUsMBcfTVqwAS7DKg9C0Q</br>不想关注官方频道可以改为自己的频道',
  1233. autoUpdateSource: '更新源</br>github: 需代理,实时更新</br>jsdelivr: 可不用代理,更新有延迟</br>standby: 备用</br>auto: 依次使用github, jsdelivr, standby源进行尝试更新',
  1234. saveGlobalOptions: '保存设置',
  1235. settingPage: '设置页面',
  1236. name: '名称',
  1237. version: '版本',
  1238. scriptManager: '脚本管理器',
  1239. script: '脚本',
  1240. environment: '环境',
  1241. os: '系统',
  1242. browser: '浏览器',
  1243. getId: '获取 %0 id',
  1244. getTwitterUserId: '获取Twitter用户id(获取id功能仅在设置页面可用)',
  1245. getYoutubeChannelId: '获取Youtube频道id(获取id功能仅在设置页面可用)',
  1246. showButton: '显示按钮',
  1247. hideButton: '隐藏按钮',
  1248. showLog: '显示日志',
  1249. hideLog: '隐藏日志',
  1250. defaultShowButton: '默认显示按钮',
  1251. defaultShowLog: '默认显示日志',
  1252. debug: '输出调试日志,不要开启此选项!',
  1253. receivePreview: '接收预览版更新',
  1254. position: '组件位置',
  1255. buttonSideX: '按钮区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1256. buttonSideY: '按钮区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1257. buttonDistance: '按钮区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1258. showButtonSideX: '显示按钮水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1259. showButtonSideY: '显示按钮垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1260. showButtonDistance: '显示按钮距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1261. logSideX: '日志区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1262. logSideY: '日志区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1263. logDistance: '日志区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1264. hotKey: '快捷键',
  1265. doTaskKey: '做任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1266. undoTaskKey: '撤销任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1267. toggleLogKey: '显示/隐藏日志快捷键</br>(实时预览功能仅在设置页面可用)',
  1268. tasksHistory: '任务历史',
  1269. clearHistory: '清空历史',
  1270. clearHistoryFinished: '已清空任务历史!',
  1271. deleteTask: '删除任务',
  1272. lastChangeTime: '最后一次修改时间',
  1273. clearTaskFinished: '删除以下任务完成!',
  1274. clearTaskFailed: '删除任务失败,没有找到任务名!',
  1275. syncData: '数据同步',
  1276. settingData: '正在上传数据...',
  1277. gettingData: '正在获取数据...',
  1278. help: '帮助',
  1279. fileName: '文件名',
  1280. upload2gist: '同步到Gist',
  1281. downloadFromGist: '从Gist同步',
  1282. saveAndTest: '保存配置并测试',
  1283. testSuccess: '测试成功!',
  1284. testFailed: '测试失败!',
  1285. saveAndTestNotice: '请先保存配置并测试!',
  1286. processingData: '正在处理数据...',
  1287. updatingData: '正在上传数据...',
  1288. syncDataSuccess: '同步数据成功!',
  1289. syncDataFailed: '同步数据失败,请在控制台查看错误信息!',
  1290. downloadingData: '正在下载数据...',
  1291. checkedNoData: '没有检测到远程数据,请确认配置是否正确!',
  1292. savingData: '正在保存数据...',
  1293. syncHistory: '同步任务历史',
  1294. checkUpdateFailed: '检测更新失败',
  1295. newVersionNotice: '检测到新版本V%0, <a class="high-light" href="%1" target="_blank">点此更新</a>',
  1296. language: '语言</br>目前仅支持zh: 中文, en: 英文',
  1297. gistOptions: 'Gist 设置',
  1298. swalNotice: '检测到您第一次安装V4版本脚本,请前往阅读用前必读内容!',
  1299. echoNotice: '检测到您第一次安装V4版本脚本,请<a class="high-light" href="%0" target="_blank">点此前往</a>阅读用前必读内容!',
  1300. noticeLink: 'https://auto-task-doc.js.org/guide/#用前必读',
  1301. toGithub: '前往Github反馈',
  1302. toKeylol: '前往其乐论坛反馈',
  1303. copySuccess: '错误信息已复制到剪切板,是否前往其乐论坛反馈?',
  1304. copyFailed: '请复制下方错误信息后前往Keylol论坛反馈!',
  1305. updateText: '%0 版本更新内容:',
  1306. Active: '进行中',
  1307. Ended: '已结束',
  1308. Banned: '已封禁',
  1309. Paused: '已暂停',
  1310. notStart: '未开始',
  1311. noRemoteData: '检测到远程无数据',
  1312. errorRemoteDataFormat: '远程数据格式错误',
  1313. updateHistory: '历史更新记录<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">点此查看</a>',
  1314. AsfEnabled: '使用ASF做Steam相关任务(需<a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a>插件)',
  1315. AsfIpcUrl: 'ASF IPC 地址',
  1316. AsfIpcPassword: 'ASF IPC 密码',
  1317. versionNotMatched: '脚本管理器版本过低,需TamperMonkey >= 5.2.0或TamperMonkey Beta >= 5.2.6196',
  1318. groups: '组',
  1319. officialGroups: '官方组',
  1320. wishlists: '愿望单',
  1321. follows: '游戏关注',
  1322. forums: '论坛',
  1323. workshops: '创意工坊收藏',
  1324. curators: '鉴赏家',
  1325. workshopVotes: '创意工坊点赞',
  1326. announcements: '社区通知',
  1327. steamCommunity: 'Steam社区',
  1328. steamStore: 'Steam商店',
  1329. licenses: '入库免费游戏',
  1330. playtests: '请求访问权限',
  1331. needLoginSteamStore: '请先<a href="https://store.steampowered.com/login/" target="_blank">登录Steam商店</a>',
  1332. needLoginSteamCommunity: '请先<a href="https://steamcommunity.com/login/home/" target="_blank">登录Steam社区</a>',
  1333. joiningSteamGroup: '正在加入Steam组',
  1334. leavingSteamGroup: '正在退出Steam组',
  1335. gettingSteamGroupId: '正在获取Steam组Id',
  1336. joiningSteamOfficialGroup: '正在加入Steam官方组',
  1337. leavingSteamOfficialGroup: '正在退出Steam官方组',
  1338. gettingSteamOfficialGroupId: '正在获取Steam官方组Id',
  1339. subscribingForum: '正在订阅Steam论坛',
  1340. unsubscribingForum: '正在取消订阅Steam论坛',
  1341. gettingForumId: '正在获取Steam论坛Id',
  1342. followingCurator: '正在关注Steam鉴赏家',
  1343. unfollowingCurator: '正在取关Steam鉴赏家',
  1344. gettingCuratorId: '正在获取Steam鉴赏家Id',
  1345. addingToWishlist: '正在添加游戏到Steam愿望单',
  1346. removingFromWishlist: '正在从Steam愿望单移除游戏',
  1347. followingGame: '正在关注Steam游戏',
  1348. unfollowingGame: '正在取关Steam游戏',
  1349. favoritingWorkshop: '正在收藏Steam创意工坊物品',
  1350. unfavoritingWorkshop: '正在取消收藏Steam创意工坊物品',
  1351. gettingWorkshopAppId: '正在获取Steam创意工坊物品Id',
  1352. votingUpWorkshop: '正在点赞Steam创意工坊物品',
  1353. gettingAnnouncementParams: '正在获取Steam通知信息',
  1354. likingAnnouncement: '正在点赞Steam通知',
  1355. changingArea: '正在更换Steam地区: %0...',
  1356. notNeededChangeArea: '当前地区不需要更换',
  1357. noAnotherArea: '请检测是否开启正确开启代理',
  1358. gettingAreaInfo: '正在获取Steam地区信息...',
  1359. changeAreaNotice: '疑似锁区游戏,尝试换区执行',
  1360. steamFinishNotice: 'Steam任务完成,尝试将购物车地区换回',
  1361. gettingSubid: '正在获取游戏subid',
  1362. addingFreeLicense: '正在入库',
  1363. missParams: '缺少参数',
  1364. gettingLicenses: '正在获取Licenses...',
  1365. requestingPlayTestAccess: '正在请求访问权限',
  1366. tryChangeAreaNotice: '此功能无法检测游戏是否限区,因此会尝试换区后再入库,换区失败也不影响后续入库',
  1367. gettingUserLink: '正在获取Steam用户社区链接...',
  1368. retry: '重试',
  1369. owned: '已拥有',
  1370. redirect: '重定向',
  1371. noSubid: '无法获取,跳过',
  1372. initingASF: '正在初始化ASF...',
  1373. servers: '服务器',
  1374. joiningDiscordServer: '正在加入Discord服务器',
  1375. leavingDiscordServer: '正在退出Discord服务器',
  1376. gettingDiscordGuild: '正在获取Discord服务器Id',
  1377. getDiscordAuthFailed: '获取Discord凭证失败,请检测Discord帐号是否已登录',
  1378. discordImportantNotice: '重要提醒!!!',
  1379. discordImportantNoticeText: '由于Discord网站后台更新,目前使用此脚本加组后可能会导致Discord帐号被强制退出,且需要两步验证才能正常登录,请谨慎使用!!!',
  1380. continue: '继续',
  1381. skipDiscordTask: '跳过Discord任务',
  1382. continueAndDontRemindAgain: '继续且不再提醒',
  1383. users: '用户',
  1384. loginIns: '请先<a href="https://www.instagram.com/accounts/login/" target="_blank">登录Instagram</a>',
  1385. insBanned: '您的Instagram账户已被封禁',
  1386. verifyingInsAuth: '正在验证Instagram凭证...',
  1387. gettingInsUserId: '正在获取Instagram用户Id',
  1388. followingIns: '正在关注Instagram用户',
  1389. unfollowingIns: '正在取关Instagram用户',
  1390. reddits: '社区/用户',
  1391. loginReddit: '请先<a href="https://www.reddit.com/login/" target="_blank">登录Reddit</a>',
  1392. changingRedditVersion: '正在切换Reddit为新版页面...',
  1393. joiningReddit: '正在加入Reddit社区',
  1394. leavingReddit: '正在退出Reddit社区',
  1395. followingRedditUser: '正在关注Reddit用户',
  1396. unfollowingRedditUser: '正在取关Reddit用户',
  1397. channels: '频道',
  1398. followingTwitchChannel: '正在关注Twitch频道',
  1399. unfollowingTwitchChannel: '正在取关Twitch频道',
  1400. gettingTwitchChannelId: '正在获取Twitch频道Id',
  1401. checkingTwitchIntegrity: '正在检查Twitch完整性...',
  1402. twitterUser: '推特用户',
  1403. retweets: '转推',
  1404. gettingTwitterUserId: '正在获取推特用户Id',
  1405. followingTwitterUser: '正在关注推特用户',
  1406. unfollowingTwitterUser: '正在取关推特用户',
  1407. retweetting: '正在转推',
  1408. unretweetting: '正在撤销转推',
  1409. names: '组/社区/动态',
  1410. loginVk: '请先<a href="https://vk.com/login/" target="_blank">登录Vk</a>',
  1411. gettingVkId: '正在获取Vk任务Id',
  1412. joiningVkGroup: '正在加入Vk组',
  1413. leavingVkGroup: '正在退出Vk组',
  1414. joiningVkPublic: '正在加入Vk社区',
  1415. leavingVkPublic: '正在退出Vk社区',
  1416. sendingVkWall: '正在转发Vk动态',
  1417. deletingVkWall: '正在撤销转发Vk动态',
  1418. youtubeChannel: 'YouTube频道',
  1419. likes: '点赞',
  1420. loginYtb: '请先<a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">登录YouTube</a>',
  1421. tryUpdateYtbAuth: '请尝试<a href="https://www.youtube.com/#auth" target="_blank">更新YouTube凭证</a>',
  1422. gettingYtbToken: '正在获取YouTube Token...',
  1423. followingYtbChannel: '正在订阅YouTube频道',
  1424. unfollowingYtbChannel: '正在退订YouTube频道',
  1425. likingYtbVideo: '正在点赞YouTube视频',
  1426. unlikingYtbVideo: '正在取消点赞YouTube视频',
  1427. giveKeyNoticeBefore: '每次验证间隔15s',
  1428. giveKeyNoticeAfter: '如果没有key, 请在<a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>查看',
  1429. noPoints: '点数不够,跳过抽奖',
  1430. getNeedPointsFailed: '获取所需点数失败,跳过抽奖',
  1431. joiningLottery: '正在加入抽奖',
  1432. doingGleamTask: '正在做Gleam任务...',
  1433. gettingGleamLink: '正在获取Gleam任务链接...',
  1434. gleamTaskNotice: '如果此页面长时间未关闭,请完成任一任务后自行关闭!',
  1435. verifiedGleamTasks: '已尝试验证所有任务,验证失败的任务请尝试手动验证或完成!',
  1436. campaign: '检测到人机验证,请完成验证后重新验证任务!',
  1437. gsNotice: '为避免得到"0000-0000-0000"key, 已自动屏蔽"Grab Key"按钮,获取key时请关闭脚本!',
  1438. giveeClubVerifyNotice: '正在验证任务...',
  1439. giveeClubVerifyFinished: '请等待验证完成后自行加入赠Key',
  1440. doingKeyhubTask: '正在做Keyhub任务...',
  1441. SweepWidgetNotice: '正在处理并验证任务,每次验证任务有1~3s间隔防止触发验证过快警告...',
  1442. tasksNotCompleted: '任务未完成',
  1443. confirmingTask: '正在跳过警告页面...'
  1444. };
  1445. const zh_CN = data;
  1446. const en_US_data = {
  1447. website: 'Website',
  1448. type: 'Type',
  1449. edit: 'Edit',
  1450. whiteList: 'Whitelist',
  1451. skipTask: 'Skip undo task',
  1452. whiteListOptions: 'Whitelist options',
  1453. changeWhiteListOption: 'Whitelist option(%0)',
  1454. whiteListNotFound: 'Cannot find this whitelist: %0',
  1455. changeWhiteListSuccess: 'The whitelist is successfully modified, and the page refresh will take effect!',
  1456. changeWebsiteOptions: 'Website options',
  1457. changeGlobalOptions: 'Global options',
  1458. ok: 'OK',
  1459. save: 'Save',
  1460. close: 'Close',
  1461. return: 'Return',
  1462. option: 'Option',
  1463. value: 'Value',
  1464. websiteOptions: 'Current website settings',
  1465. changeWebsiteOptionsSuccess: 'The current website setting is changed successfully, and the page refresh will take effect!',
  1466. changeGlobalOptionsSuccess: 'The global setting is changed successfully, and the refresh will take effect!',
  1467. needLogin: 'Please log in first!',
  1468. getTasksInfo: 'Obtaining and processing task information...',
  1469. gettingKey: 'Getting Key...',
  1470. verifyingTask: 'Verifying task',
  1471. notice: 'Automatic task script notice',
  1472. noKeysLeft: 'There are no more keys left on this page. Do you want to close it?',
  1473. giveawayEnded: 'This event has ended, do you want to close it?',
  1474. 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?',
  1475. confirm: 'Confirm',
  1476. cancel: 'Cancel',
  1477. unKnown: 'Unknown',
  1478. unKnownTaskType: 'Unrecognized task',
  1479. doing: 'Doing a task',
  1480. allTasksComplete: 'All tasks have been completed!',
  1481. getTaskIdFailed: 'Failed to obtain task Id!',
  1482. initSuccess: '%0 was initialized successfully!',
  1483. initFailed: '%0 initialization failed!',
  1484. errorLink: 'Link error: %0',
  1485. needInit: 'Please initialize first',
  1486. verifyingAuth: 'Verifying %0 token...',
  1487. updatingAuth: 'Update %0 token...',
  1488. refreshingToken: 'Refreshing %0 token...',
  1489. settingToken: 'Setting %0 token...',
  1490. steamStoreTab: 'Steam store (new tab)',
  1491. steamCommunityTab: 'Steam community(new tab)',
  1492. initing: 'Initializing...',
  1493. getFailed: 'Failed to get %0!',
  1494. checkLoginFailed: 'Failed to detect login status!',
  1495. checkLeftKeyFailed: 'Failed to detect the remaining keys!',
  1496. userId: 'User Id',
  1497. joiningGiveaway: 'Joining giveaway',
  1498. needJoinGiveaway: 'Need to join the giveaway first',
  1499. cannotUndo: 'This website does not support canceling tasks',
  1500. verifyAuth: 'Verifying %0 token...',
  1501. closePageNotice: 'f this page does not close automatically, please close this page yourself.',
  1502. errorReport: 'A script error is detected, do you want to report the BUG?',
  1503. visitingLink: 'Visiting link: ',
  1504. doTask: 'DoTask',
  1505. undoTask: 'UndoTask',
  1506. verifyTask: 'Verify',
  1507. getKey: 'GetKey',
  1508. selectAll: 'SelectAll',
  1509. selectNone: 'SelectNone',
  1510. invertSelect: 'InvertSelect',
  1511. doFreeTask: 'FreeTask',
  1512. doPointTask: 'PointTask',
  1513. skipTaskOption: 'Skip task has been configured in the settings',
  1514. other: 'Other',
  1515. globalOptions: 'Global Options',
  1516. checkLogin: 'Login detection</br>Need to log in to the website automatically log in, part of this website supports.',
  1517. checkLeftKey: 'Key remaining detection</br>The end of the giveaway event prompts whether to close or not, part of this website supports.',
  1518. 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.',
  1519. 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.',
  1520. 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.',
  1521. saveGlobalOptions: 'SaveSettings',
  1522. settingPage: 'Setting Page',
  1523. name: 'Name',
  1524. version: 'Version',
  1525. scriptManager: 'Script Manager',
  1526. script: 'Script',
  1527. environment: 'Environment',
  1528. os: 'OS',
  1529. browser: 'Browser',
  1530. getId: 'Get %0 id',
  1531. getTwitterUserId: 'Get Twitter user id (Get id function is only available on the settings page).',
  1532. getYoutubeChannelId: 'Get Youtube channel id (Get id function is only available on the settings page).',
  1533. showButton: 'ShowButton',
  1534. hideButton: 'HideButton',
  1535. showLog: 'ShowLog',
  1536. hideLog: 'HideLog',
  1537. defaultShowButton: 'Default display button',
  1538. defaultShowLog: 'Display log by default',
  1539. debug: 'Output debug log, do not enable this option!',
  1540. receivePreview: 'Receive preview updates',
  1541. position: 'Component position',
  1542. buttonSideX: 'Horizontal positioning of the button area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1543. 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',
  1544. 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',
  1545. showButtonSideX: 'ShowButton horizontal positioning (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1546. showButtonSideY: 'ShowButton vertical positioning (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  1547. 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',
  1548. logSideX: 'Horizontal positioning of the log area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1549. logSideY: 'Vertical positioning of the log area (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  1550. 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',
  1551. hotKey: 'Shortcut key',
  1552. doTaskKey: 'DoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  1553. undoTaskKey: 'UndoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  1554. toggleLogKey: 'ShowLog/HideLog shortcut keys</br> (real-time preview function is only available on the settings page).',
  1555. tasksHistory: 'TasksHistory',
  1556. clearHistory: 'Clear history',
  1557. clearHistoryFinished: 'The mission history has been cleared!',
  1558. deleteTask: 'Delete task',
  1559. lastChangeTime: 'Last Change Time',
  1560. clearTaskFinished: 'Delete the following tasks completed!',
  1561. clearTaskFailed: 'Failed to delete the task, the task name was not found!',
  1562. syncData: 'DataSync',
  1563. settingData: 'Uploading data...',
  1564. gettingData: 'Getting data...',
  1565. help: 'Help',
  1566. fileName: 'Filename',
  1567. upload2gist: 'Sync to Gist',
  1568. downloadFromGist: 'Sync from Gist',
  1569. saveAndTest: 'Save configuration and test',
  1570. testSuccess: 'Test success!',
  1571. testFailed: 'Test failed!',
  1572. saveAndTestNotice: 'Please save the configuration and test first!',
  1573. processingData: 'Processing data...',
  1574. updatingData: 'Uploading data...',
  1575. syncDataSuccess: 'Synchronized data successfully!',
  1576. syncDataFailed: 'Failed to synchronize data, please check the error message on the console!',
  1577. downloadingData: 'Downloading data...',
  1578. checkedNoData: 'No remote data is detected, please confirm whether the configuration is correct!',
  1579. savingData: 'Saving data...',
  1580. syncHistory: 'Synchronize tasks history',
  1581. checkUpdateFailed: 'Check update failed',
  1582. newVersionNotice: 'Checked a new version V%0, <a class="high-light" href="%1" target="_blank">click to update</a>',
  1583. language: 'Language</br> Currently only supports zh: Chinese, en: English',
  1584. gistOptions: 'Gist Settings',
  1585. 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!',
  1586. 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!',
  1587. noticeLink: 'https://auto-task-doc.js.org/en/guide/#read-me-first',
  1588. toGithub: 'Feedback(Github)',
  1589. toKeylol: 'Feedback(Keylol)',
  1590. copySuccess: 'The error message has been copied to the clipboard. Do you want to go to the Keylol forum to give feedback?',
  1591. copyFailed: 'Please copy the error information below and report back to the Keylol forum!',
  1592. updateText: 'Updates in version %0:',
  1593. Active: 'Active',
  1594. Ended: 'Ended',
  1595. Banned: 'Banned',
  1596. Paused: 'Paused',
  1597. notStart: 'notStart',
  1598. noRemoteData: 'No data remotely',
  1599. errorRemoteDataFormat: 'Remote data has wrong format',
  1600. updateHistory: '<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">Click here</a>' + ' to view the historical update record.',
  1601. AsfEnabled: 'Use ASF to do Steam related tasks (requires <a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a> plugin)',
  1602. AsfIpcUrl: 'ASF IPC URL',
  1603. AsfIpcPassword: 'ASF IPC Password',
  1604. groups: 'Group',
  1605. officialGroups: 'Official Group',
  1606. wishlists: 'Wishlist',
  1607. follows: 'Follow Game',
  1608. forums: 'Forum',
  1609. workshops: 'Favorite Workshop',
  1610. curators: 'Curator',
  1611. workshopVotes: 'Voteup Workshop',
  1612. announcements: 'Announcement',
  1613. steamCommunity: 'Steam Community',
  1614. steamStore: 'Steam Store',
  1615. licenses: 'Add License',
  1616. playtests: 'Playtest Access',
  1617. needLoginSteamStore: 'Please <a href="https://store.steampowered.com/login/" target="_blank">log in to the Steam Store</a>',
  1618. needLoginSteamCommunity: 'Please <a href="https://steamcommunity.com/login/home/" target="_blank">log in to the Steam Community</a>',
  1619. joiningSteamGroup: 'Joining Steam Group',
  1620. leavingSteamGroup: 'Leaving Steam Group',
  1621. gettingSteamGroupId: 'Getting Steam Group Id',
  1622. joiningSteamOfficialGroup: 'Joining Steam Official Group',
  1623. leavingSteamOfficialGroup: 'Leaving Steam Official Group',
  1624. gettingSteamOfficialGroupId: 'Getting Steam Official Group Id',
  1625. subscribingForum: 'Subscribing the Steam Forum',
  1626. unsubscribingForum: 'Unsubscribing the Steam Forum',
  1627. gettingForumId: 'Getting Steam Forum Id',
  1628. followingCurator: 'Following Steam Curator',
  1629. unfollowingCurator: 'Unfollowing Steam Curator',
  1630. gettingCuratorId: 'Getting Steam Curator Id',
  1631. addingToWishlist: 'Adding the game to the Steam wishlist',
  1632. removingFromWishlist: 'Removing the game from the Steam wishlist',
  1633. followingGame: 'Following Steam games',
  1634. unfollowingGame: 'Unfollowing Steam games',
  1635. favoritingWorkshop: 'Favouring Steam Workshop Items',
  1636. unfavoritingWorkshop: 'Unfavoriting Steam Workshop Items',
  1637. gettingWorkshopAppId: 'Getting Steam Workshop Item Id',
  1638. votingUpWorkshop: 'Liking Steam workshop items',
  1639. gettingAnnouncementParams: 'Getting Steam announcement information',
  1640. likingAnnouncement: 'Liking Steam announcement',
  1641. changingArea: 'Changing Steam area: %0...',
  1642. notNeededChangeArea: 'The current area does not need to be changed',
  1643. noAnotherArea: 'Please check whether the proxy is turned on correctly',
  1644. gettingAreaInfo: 'Getting Steam area information...',
  1645. changeAreaNotice: 'Suspected of a locked zone game, try to change the zone to execute',
  1646. steamFinishNotice: 'Steam task completed, try to change the shopping cart area back to ',
  1647. gettingSubid: 'Getting subid',
  1648. addingFreeLicense: 'Adding free license',
  1649. missParams: 'Missing parameters',
  1650. gettingLicenses: 'Getting licenses...',
  1651. requestingPlayTestAccess: 'Requesting play test access',
  1652. 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.',
  1653. versionNotMatched: 'The script manager version is too low, requiring TamperMonkey >= 5.2.0 or TamperMonkey Beta >= 5.2.6196',
  1654. gettingUserLink: 'Getting steam user community link...',
  1655. retry: 'Retry',
  1656. owned: 'Owned',
  1657. redirect: 'Redirect',
  1658. noSubid: 'skip due to unrecognized',
  1659. initingASF: 'Initing ASF...',
  1660. servers: 'Server',
  1661. joiningDiscordServer: 'Joining Discord Server',
  1662. leavingDiscordServer: 'Leaving Discord Server',
  1663. gettingDiscordGuild: 'Getting Discord server Id',
  1664. getDiscordAuthFailed: 'Failed to get Discord token, please check whether the Discord account is logged in',
  1665. discordImportantNotice: 'Important Reminder! ! !',
  1666. 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! ! !',
  1667. continue: 'Continue',
  1668. skipDiscordTask: 'Skip',
  1669. continueAndDontRemindAgain: 'Continue without Reminders',
  1670. users: 'User',
  1671. loginIns: 'Please <a href="https://www.instagram.com/accounts/login/" target="_blank">log in to Instagram</a>',
  1672. insBanned: 'Your Instagram account has been banned',
  1673. verifyingInsAuth: 'Verifying Instagram token...',
  1674. gettingInsUserId: 'Getting Instagram user Id',
  1675. followingIns: 'Following Instagram user',
  1676. unfollowingIns: 'Unfollowing Instagram user',
  1677. reddits: 'Reddit/User',
  1678. loginReddit: 'Please <a href="https://www.reddit.com/login/" target="_blank">log in to Reddit</a>',
  1679. changingRedditVersion: 'Switching Reddit to a new version page...',
  1680. joiningReddit: 'Joining the Reddit',
  1681. leavingReddit: 'Leaving the Reddit',
  1682. followingRedditUser: 'Following Reddit User',
  1683. unfollowingRedditUser: 'Unfollowing Reddit User',
  1684. channels: 'Channel',
  1685. followingTwitchChannel: 'Following Twitch Channel',
  1686. unfollowingTwitchChannel: 'Unfollowing Twitch Channel',
  1687. gettingTwitchChannelId: 'Getting Twitch Channel Id',
  1688. checkingTwitchIntegrity: 'Checking Twitch integrity...',
  1689. twitterUser: 'Twitter User',
  1690. retweets: 'Retweet',
  1691. gettingTwitterUserId: 'Getting Twitter User Id',
  1692. followingTwitterUser: 'Following Twitter User',
  1693. unfollowingTwitterUser: 'Unfollowing Twitter User',
  1694. retweetting: 'Retweetting',
  1695. unretweetting: 'Unretweetting',
  1696. names: 'Group/Public/Wall',
  1697. loginVk: 'Please <a href="https://vk.com/login/" target="_blank">log in to Vk</a>',
  1698. gettingVkId: 'Getting Vk task Id',
  1699. joiningVkGroup: 'Joining Vk Group',
  1700. leavingVkGroup: 'Leaving Vk Group',
  1701. joiningVkPublic: 'Joining Vk Public',
  1702. leavingVkPublic: 'Leaving Vk Public',
  1703. sendingVkWall: 'Sending Vk Wall',
  1704. deletingVkWall: 'Deleting Vk Wall',
  1705. youtubeChannel: 'YouTube Channel',
  1706. likes: 'Like',
  1707. loginYtb: 'Please <a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">log in to YouTube</a>',
  1708. tryUpdateYtbAuth: 'Please try to <a href="https://www.youtube.com/#auth" target="_blank">update YouTube token</a>',
  1709. gettingYtbToken: 'Getting YouTube Token...',
  1710. followingYtbChannel: 'Subscribing to YouTube channel',
  1711. unfollowingYtbChannel: 'Unsubscribing to YouTube channel',
  1712. likingYtbVideo: 'Liking YouTube video',
  1713. unlikingYtbVideo: 'Unliking YouTube video',
  1714. giveKeyNoticeBefore: 'Each verification interval is 15s',
  1715. giveKeyNoticeAfter: 'If there is no key, please check at <a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>',
  1716. noPoints: 'Not enough points, skip the lottery',
  1717. getNeedPointsFailed: 'ailed to obtain the required points, skip the lottery',
  1718. joiningLottery: 'Joining the lottery',
  1719. doingGleamTask: 'Doing Gleam Task...',
  1720. gettingGleamLink: 'Getting Gleam task link...',
  1721. gleamTaskNotice: 'If this page has not been closed for a long time, please close it yourself after completing any task!',
  1722. verifiedGleamTasks: 'Attempted to verify all tasks. If the verification fails, please try to verify manually or complete it!',
  1723. campaign: 'ReCAPTCHA detected, please complete it and re-verify the tasks!',
  1724. 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!',
  1725. giveeClubVerifyNotice: 'Verifying task...',
  1726. giveeClubVerifyFinished: 'Wait for the verification to complete and join it by yourself',
  1727. doingKeyhubTask: 'Doing Keyhub Task...',
  1728. 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...',
  1729. tasksNotCompleted: 'Tasks Not Completed',
  1730. confirmingTask: 'Confirming task...'
  1731. };
  1732. const en_US = en_US_data;
  1733. const languages = {
  1734. zh: zh_CN,
  1735. en: en_US
  1736. };
  1737. const language = [ 'zh', 'en' ].includes(globalOptions.other.language) ? globalOptions.other.language : 'en';
  1738. const I18n = (key, ...argvs) => {
  1739. if (!languages[language]?.[key]) {
  1740. return key;
  1741. }
  1742. return languages[language][key].replace(/%([\d]+)/g, (match, index) => argvs[parseInt(index, 10)]);
  1743. };
  1744. const i18n = I18n;
  1745. function throwError(error, name) {
  1746. if (window.TRACE) {
  1747. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  1748. }
  1749. external_Swal_default().fire({
  1750. title: i18n('errorReport'),
  1751. icon: 'error',
  1752. showCancelButton: true,
  1753. confirmButtonText: i18n('toGithub'),
  1754. showDenyButton: true,
  1755. denyButtonText: i18n('toKeylol'),
  1756. cancelButtonText: i18n('close')
  1757. }).then(({
  1758. isDenied,
  1759. isConfirmed
  1760. }) => {
  1761. if (isConfirmed) {
  1762. 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,
  1763. 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'))}`, {
  1764. active: true
  1765. });
  1766. } else if (isDenied) {
  1767. const text = `错误链接: [url=${window.location.href}]${window.location.href}[/url]
  1768.  
  1769. 环境:
  1770.  
  1771. [code]${JSON.stringify((0, javascript_utils_umd_min.ua)(), null, 4)}[/code]
  1772.  
  1773. 脚本管理器: ${GM_info.scriptHandler} ${GM_info.version}
  1774. 脚本版本: ${GM_info.script.version}
  1775.  
  1776. 报错信息:
  1777. [code]${error.stack}[/code]
  1778.  
  1779. 执行日志:
  1780. [code]${$.makeArray($('#auto-task-info>li')).map(element => element.innerText).join('\n')}[/code]`;
  1781. GM_setClipboard(text);
  1782. external_Swal_default().fire({
  1783. title: i18n('copySuccess'),
  1784. icon: 'success',
  1785. confirmButtonText: i18n('ok')
  1786. }).then(() => {
  1787. GM_openInTab('https://keylol.com/forum.php?mod=post&action=reply&fid=319&tid=777450', {
  1788. active: true
  1789. });
  1790. });
  1791. }
  1792. });
  1793. console.log('%c%s', 'color:white;background:red', `Auto-Task[Error]: ${name}\n${error.stack}`);
  1794. }
  1795. class Social {
  1796. tasks;
  1797. getRealParams(name, links, doTask, link2param) {
  1798. try {
  1799. let realParams = [];
  1800. if (links.length > 0) {
  1801. realParams = [ ...realParams, ...links.map(link => link2param(link)).filter(link => link) ];
  1802. }
  1803. if (!doTask && this.tasks[name].length > 0) {
  1804. realParams = [ ...realParams, ...this.tasks[name] ];
  1805. }
  1806. return unique(realParams);
  1807. } catch (error) {
  1808. throwError(error, 'Social.getRealParams');
  1809. return [];
  1810. }
  1811. }
  1812. }
  1813. const social_Social = Social;
  1814. class Discord extends social_Social {
  1815. tasks;
  1816. whiteList;
  1817. #auth = GM_getValue('discordAuth') || {};
  1818. #cache = GM_getValue('discordCache') || {};
  1819. #initialized = false;
  1820. constructor() {
  1821. super();
  1822. const defaultTasksTemplate = {
  1823. servers: []
  1824. };
  1825. this.tasks = defaultTasksTemplate;
  1826. this.whiteList = {
  1827. ...defaultTasksTemplate,
  1828. ...GM_getValue('whiteList')?.discord || {}
  1829. };
  1830. }
  1831. async init(action) {
  1832. try {
  1833. if (!GM_getValue('dontRemindDiscordAgain')) {
  1834. const result = await external_Swal_default().fire({
  1835. title: i18n('discordImportantNotice'),
  1836. text: i18n('discordImportantNoticeText'),
  1837. showCancelButton: true,
  1838. showDenyButton: true,
  1839. confirmButtonText: i18n('continue'),
  1840. cancelButtonText: i18n('skipDiscordTask'),
  1841. denyButtonText: i18n('continueAndDontRemindAgain')
  1842. }).then(({
  1843. isConfirmed,
  1844. isDenied
  1845. }) => {
  1846. if (isConfirmed) {
  1847. return true;
  1848. }
  1849. if (isDenied) {
  1850. GM_setValue('dontRemindDiscordAgain', true);
  1851. return true;
  1852. }
  1853. return false;
  1854. });
  1855. if (!result) {
  1856. this.#initialized = false;
  1857. return 'skip';
  1858. }
  1859. }
  1860. if (GM_getValue('dontRemindDiscordAgain') || action === 'do' && !globalOptions.doTask.discord.servers || action === 'undo' && !globalOptions.undoTask.discord.servers) {
  1861. this.#initialized = false;
  1862. return 'skip';
  1863. }
  1864. if (this.#initialized) {
  1865. return true;
  1866. }
  1867. if (!this.#auth.auth) {
  1868. if (await this.#updateAuth()) {
  1869. this.#initialized = true;
  1870. return true;
  1871. }
  1872. return false;
  1873. }
  1874. const isVerified = await this.#verifyAuth();
  1875. if (isVerified) {
  1876. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  1877. this.#initialized = true;
  1878. return true;
  1879. }
  1880. GM_setValue('discordAuth', {
  1881. auth: null
  1882. });
  1883. if (await this.#updateAuth()) {
  1884. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  1885. this.#initialized = true;
  1886. return true;
  1887. }
  1888. scripts_echoLog({}).error(i18n('initFailed', 'Discord'));
  1889. return false;
  1890. } catch (error) {
  1891. throwError(error, 'Discord.init');
  1892. return false;
  1893. }
  1894. }
  1895. async #verifyAuth() {
  1896. try {
  1897. const logStatus = scripts_echoLog({
  1898. text: i18n('verifyingAuth', 'Discord')
  1899. });
  1900. const {
  1901. result,
  1902. statusText,
  1903. status,
  1904. data
  1905. } = await tools_httpRequest({
  1906. url: 'https://discord.com/api/v6/users/@me',
  1907. method: 'HEAD',
  1908. headers: {
  1909. authorization: this.#auth.auth
  1910. }
  1911. });
  1912. if (result === 'Success') {
  1913. if (data?.status === 200) {
  1914. logStatus.success();
  1915. return true;
  1916. }
  1917. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  1918. return false;
  1919. }
  1920. logStatus.error(`${result}:${statusText}(${status})`);
  1921. return false;
  1922. } catch (error) {
  1923. throwError(error, 'Discord.verifyAuth');
  1924. return false;
  1925. }
  1926. }
  1927. async #updateAuth() {
  1928. try {
  1929. const logStatus = scripts_echoLog({
  1930. text: i18n('updatingAuth', 'Discord')
  1931. });
  1932. return await new Promise(resolve => {
  1933. const newTab = GM_openInTab('https://discord.com/channels/@me', {
  1934. active: true,
  1935. insert: true,
  1936. setParent: true
  1937. });
  1938. newTab.name = 'ATv4_discordAuth';
  1939. newTab.onclose = async () => {
  1940. const auth = GM_getValue('discordAuth')?.auth;
  1941. if (auth) {
  1942. this.#auth = {
  1943. auth: auth
  1944. };
  1945. logStatus.success();
  1946. resolve(await this.#verifyAuth());
  1947. } else {
  1948. logStatus.error('Error: Update discord auth failed!');
  1949. resolve(false);
  1950. }
  1951. };
  1952. });
  1953. } catch (error) {
  1954. throwError(error, 'Discord.updateAuth');
  1955. return false;
  1956. }
  1957. }
  1958. async #joinServer(inviteId) {
  1959. try {
  1960. const logStatus = scripts_echoLog({
  1961. type: 'joiningDiscordServer',
  1962. text: inviteId
  1963. });
  1964. const {
  1965. result,
  1966. statusText,
  1967. status,
  1968. data
  1969. } = await tools_httpRequest({
  1970. url: `https://discord.com/api/v9/invites/${inviteId}`,
  1971. method: 'POST',
  1972. dataType: 'json',
  1973. headers: {
  1974. authorization: this.#auth.auth,
  1975. origin: 'https://discord.com',
  1976. referer: `https://discord.com/invite/${inviteId}`
  1977. }
  1978. });
  1979. if (result === 'Success' && data?.status === 200) {
  1980. logStatus.success();
  1981. const guild = String(data.response?.guild?.id);
  1982. if (guild) {
  1983. this.#setCache(inviteId, guild);
  1984. this.tasks.servers = unique([ ...this.tasks.servers, inviteId ]);
  1985. }
  1986. return true;
  1987. }
  1988. logStatus.error(`${result}:${statusText}(${status})`);
  1989. return false;
  1990. } catch (error) {
  1991. throwError(error, 'Discord.joinServer');
  1992. return false;
  1993. }
  1994. }
  1995. async #leaveServer(inviteId) {
  1996. try {
  1997. if (this.whiteList.servers.includes(inviteId)) {
  1998. scripts_echoLog({
  1999. type: 'whiteList',
  2000. text: 'Discord.leaveServer',
  2001. id: inviteId
  2002. });
  2003. return true;
  2004. }
  2005. const guild = await this.#getGuild(inviteId);
  2006. if (!guild) {
  2007. return false;
  2008. }
  2009. const logStatus = scripts_echoLog({
  2010. type: 'leavingDiscordServer',
  2011. text: guild
  2012. });
  2013. const {
  2014. result,
  2015. statusText,
  2016. status,
  2017. data
  2018. } = await tools_httpRequest({
  2019. url: `https://discord.com/api/v9/users/@me/guilds/${guild}`,
  2020. method: 'DELETE',
  2021. headers: {
  2022. authorization: this.#auth.auth
  2023. }
  2024. });
  2025. if (result === 'Success' && data?.status === 204) {
  2026. logStatus.success();
  2027. return true;
  2028. }
  2029. logStatus.error(`${result}:${statusText}(${status})`);
  2030. return false;
  2031. } catch (error) {
  2032. throwError(error, 'Discord.leaveServer');
  2033. return false;
  2034. }
  2035. }
  2036. async #getGuild(inviteId) {
  2037. try {
  2038. const logStatus = scripts_echoLog({
  2039. type: 'gettingDiscordGuild',
  2040. text: inviteId
  2041. });
  2042. const guild = this.#cache[inviteId];
  2043. if (guild) {
  2044. logStatus.success();
  2045. return guild;
  2046. }
  2047. const {
  2048. result,
  2049. statusText,
  2050. status,
  2051. data
  2052. } = await tools_httpRequest({
  2053. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2054. responseType: 'json',
  2055. method: 'GET'
  2056. });
  2057. if (result === 'Success' && data?.status === 200) {
  2058. const guild = data.response?.guild?.id;
  2059. if (guild) {
  2060. logStatus.success();
  2061. this.#setCache(inviteId, guild);
  2062. return guild;
  2063. }
  2064. logStatus.error(`${result}:${statusText}(${status})`);
  2065. return false;
  2066. }
  2067. logStatus.error(`${result}:${statusText}(${status})`);
  2068. return false;
  2069. } catch (error) {
  2070. throwError(error, 'Discord.getGuild');
  2071. return false;
  2072. }
  2073. }
  2074. async toggle({
  2075. doTask = true,
  2076. serverLinks = []
  2077. }) {
  2078. try {
  2079. if (!this.#initialized) {
  2080. scripts_echoLog({
  2081. text: i18n('needInit')
  2082. });
  2083. return false;
  2084. }
  2085. const prom = [];
  2086. if (doTask && !globalOptions.doTask.discord.servers || !doTask && !globalOptions.undoTask.discord.servers) {
  2087. scripts_echoLog({
  2088. type: 'globalOptionsSkip',
  2089. text: 'discord.servers'
  2090. });
  2091. } else {
  2092. const realServers = this.getRealParams('servers', serverLinks, doTask, link => link.match(/invite\/(.+)/)?.[1]);
  2093. if (realServers.length > 0) {
  2094. for (const server of realServers) {
  2095. if (doTask) {
  2096. prom.push(this.#joinServer(server));
  2097. } else {
  2098. prom.push(this.#leaveServer(server));
  2099. }
  2100. await delay(1e3);
  2101. }
  2102. }
  2103. }
  2104. return await Promise.all(prom).then(() => true);
  2105. } catch (error) {
  2106. throwError(error, 'Discord.toggleServers');
  2107. return false;
  2108. }
  2109. }
  2110. #setCache(inviteId, guild) {
  2111. try {
  2112. this.#cache[inviteId] = guild;
  2113. GM_setValue('discordCache', this.#cache);
  2114. } catch (error) {
  2115. throwError(error, 'Discord.setCache');
  2116. }
  2117. }
  2118. }
  2119. const social_Discord = Discord;
  2120. class Instagram extends social_Social {
  2121. tasks;
  2122. whiteList;
  2123. #cache = GM_getValue('instagramCache') || {};
  2124. #auth = {};
  2125. #initialized = false;
  2126. constructor() {
  2127. super();
  2128. const defaultTasksTemplate = {
  2129. users: []
  2130. };
  2131. this.tasks = defaultTasksTemplate;
  2132. this.whiteList = {
  2133. ...defaultTasksTemplate,
  2134. ...GM_getValue('whiteList')?.instagram || {}
  2135. };
  2136. }
  2137. async init() {
  2138. try {
  2139. if (this.#initialized) {
  2140. return true;
  2141. }
  2142. const isVerified = await this.#getUserInfo();
  2143. if (isVerified) {
  2144. scripts_echoLog({}).success(i18n('initSuccess', 'Instagram'));
  2145. this.#initialized = true;
  2146. return true;
  2147. }
  2148. scripts_echoLog({}).error(i18n('initFailed', 'Instagram'));
  2149. return false;
  2150. } catch (error) {
  2151. throwError(error, 'Instagram.init');
  2152. return false;
  2153. }
  2154. }
  2155. async #getUserInfo(name = 'instagram') {
  2156. try {
  2157. const logStatus = scripts_echoLog({
  2158. type: name === 'instagram' ? 'verifyingInsAuth' : 'gettingInsUserId',
  2159. text: name
  2160. });
  2161. const userId = this.#cache[name];
  2162. if (userId && name !== 'instagram') {
  2163. logStatus.success();
  2164. return userId;
  2165. }
  2166. const {
  2167. result,
  2168. statusText,
  2169. status,
  2170. data
  2171. } = await tools_httpRequest({
  2172. url: `https://www.instagram.com/${name}/`,
  2173. method: 'GET'
  2174. });
  2175. if (result === 'Success') {
  2176. if (data?.finalUrl.includes('accounts/login')) {
  2177. logStatus.error(`Error:${i18n('loginIns')}`, true);
  2178. return false;
  2179. } else if (data?.finalUrl.includes('www.instagram.com/challenge')) {
  2180. logStatus.error(`Error:${i18n('insBanned')}`);
  2181. return false;
  2182. }
  2183. if (data?.status === 200) {
  2184. const csrftoken = data.responseText.match(/"csrf_token":"(.+?)"/)?.[1];
  2185. const hash = data.responseText.match(/"rollout_hash":"(.+?)"/)?.[1];
  2186. if (name === 'instagram') {
  2187. if (csrftoken && hash) {
  2188. this.#auth = {
  2189. csrftoken: csrftoken,
  2190. hash: hash
  2191. };
  2192. return true;
  2193. }
  2194. return false;
  2195. }
  2196. const id = data.responseText.match(/"profilePage_([\d]+?)"/)?.[1];
  2197. if (id) {
  2198. this.#setCache(name, id);
  2199. logStatus.success();
  2200. return id;
  2201. }
  2202. logStatus.error('Error: Get ins data error!');
  2203. return false;
  2204. }
  2205. logStatus.error(`${result}:${statusText}(${status})`);
  2206. return false;
  2207. }
  2208. return false;
  2209. } catch (error) {
  2210. throwError(error, 'Instagram.getUserInfo');
  2211. return false;
  2212. }
  2213. }
  2214. async #followUser(name) {
  2215. try {
  2216. const id = await this.#getUserInfo(name);
  2217. if (!id) {
  2218. return false;
  2219. }
  2220. const logStatus = scripts_echoLog({
  2221. type: 'followingIns',
  2222. text: name
  2223. });
  2224. const {
  2225. result,
  2226. statusText,
  2227. status,
  2228. data
  2229. } = await tools_httpRequest({
  2230. url: `https://www.instagram.com/web/friendships/${id}/follow/`,
  2231. method: 'POST',
  2232. dataType: 'json',
  2233. headers: {
  2234. 'x-csrftoken': this.#auth.csrftoken,
  2235. origin: 'https://www.instagram.com',
  2236. referer: `https://www.instagram.com/${name}/`,
  2237. 'content-type': 'application/x-www-form-urlencoded',
  2238. 'sec-fetch-site': 'same-origin',
  2239. 'x-instagram-ajax': this.#auth.hash
  2240. }
  2241. });
  2242. if (result === 'Success') {
  2243. if (data?.status === 200 && data.response?.result === 'following') {
  2244. logStatus.success();
  2245. this.tasks.users = unique([ ...this.tasks.users, name ]);
  2246. return true;
  2247. }
  2248. logStatus.error(`Error:${data?.response?.feedback_message || `${data?.statusText}(${data?.status})`}`);
  2249. return false;
  2250. }
  2251. logStatus.error(`${result}:${statusText}(${status})`);
  2252. return false;
  2253. } catch (error) {
  2254. throwError(error, 'Instagram.followUser');
  2255. return false;
  2256. }
  2257. }
  2258. async #unfollowUser(name) {
  2259. try {
  2260. if (this.whiteList.users.includes(name)) {
  2261. scripts_echoLog({
  2262. type: 'whiteList',
  2263. text: 'Instagram.unfollowUser',
  2264. id: name
  2265. });
  2266. return true;
  2267. }
  2268. const id = await this.#getUserInfo(name);
  2269. if (!id) {
  2270. return false;
  2271. }
  2272. const logStatus = scripts_echoLog({
  2273. type: 'unfollowingIns',
  2274. text: name
  2275. });
  2276. const {
  2277. result,
  2278. statusText,
  2279. status,
  2280. data
  2281. } = await tools_httpRequest({
  2282. url: `https://www.instagram.com/web/friendships/${id}/unfollow/`,
  2283. method: 'POST',
  2284. dataType: 'json',
  2285. headers: {
  2286. 'x-csrftoken': this.#auth.csrftoken,
  2287. origin: 'https://www.instagram.com',
  2288. referer: `https://www.instagram.com/${name}/`,
  2289. 'content-type': 'application/x-www-form-urlencoded',
  2290. 'sec-fetch-site': 'same-origin',
  2291. 'x-instagram-ajax': this.#auth.hash
  2292. }
  2293. });
  2294. if (result === 'Success') {
  2295. if (data?.status === 200 && data.response?.status === 'ok') {
  2296. logStatus.success();
  2297. return true;
  2298. }
  2299. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2300. return false;
  2301. }
  2302. logStatus.error(`${result}:${statusText}(${status})`);
  2303. return false;
  2304. } catch (error) {
  2305. throwError(error, 'Instagram.unfollowUser');
  2306. return false;
  2307. }
  2308. }
  2309. async toggle({
  2310. doTask = true,
  2311. userLinks = []
  2312. }) {
  2313. try {
  2314. if (!this.#initialized) {
  2315. scripts_echoLog({
  2316. text: i18n('needInit')
  2317. });
  2318. return false;
  2319. }
  2320. const prom = [];
  2321. if (doTask && !globalOptions.doTask.instagram.users || !doTask && !globalOptions.undoTask.instagram.users) {
  2322. scripts_echoLog({
  2323. type: 'globalOptionsSkip',
  2324. text: 'instagram.users'
  2325. });
  2326. } else {
  2327. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1]);
  2328. if (realUsers.length > 0) {
  2329. for (const username of realUsers) {
  2330. if (doTask) {
  2331. prom.push(this.#followUser(username));
  2332. } else {
  2333. prom.push(this.#unfollowUser(username));
  2334. }
  2335. await delay(1e3);
  2336. }
  2337. }
  2338. }
  2339. return await Promise.all(prom).then(() => true);
  2340. } catch (error) {
  2341. throwError(error, 'Instagram.toggleUsers');
  2342. return false;
  2343. }
  2344. }
  2345. #setCache(name, id) {
  2346. try {
  2347. this.#cache[name] = id;
  2348. GM_setValue('instagramCache', this.#cache);
  2349. } catch (error) {
  2350. throwError(error, 'Instagram.setCache');
  2351. }
  2352. }
  2353. }
  2354. const social_Instagram = Instagram;
  2355. class Reddit extends social_Social {
  2356. tasks;
  2357. whiteList;
  2358. #auth;
  2359. #initialized = false;
  2360. constructor() {
  2361. super();
  2362. const defaultTasksTemplate = {
  2363. reddits: []
  2364. };
  2365. this.tasks = defaultTasksTemplate;
  2366. this.whiteList = {
  2367. ...defaultTasksTemplate,
  2368. ...GM_getValue('whiteList')?.reddit || {}
  2369. };
  2370. }
  2371. async init() {
  2372. try {
  2373. if (this.#initialized) {
  2374. return true;
  2375. }
  2376. const isVerified = await this.#updateAuth();
  2377. if (isVerified) {
  2378. scripts_echoLog({}).success(i18n('initSuccess', 'Reddit'));
  2379. this.#initialized = true;
  2380. return true;
  2381. }
  2382. scripts_echoLog({}).error(i18n('initFailed', 'Reddit'));
  2383. return false;
  2384. } catch (error) {
  2385. throwError(error, 'Reddit.init');
  2386. return false;
  2387. }
  2388. }
  2389. async #useBeta() {
  2390. try {
  2391. const logStatus = scripts_echoLog({
  2392. text: i18n('changingRedditVersion')
  2393. });
  2394. return await new Promise(resolve => {
  2395. const newTab = GM_openInTab('https://www.reddit.com/', {
  2396. active: true,
  2397. insert: true,
  2398. setParent: true
  2399. });
  2400. newTab.name = 'ATv4_redditAuth';
  2401. newTab.onclose = async () => {
  2402. logStatus.success();
  2403. resolve(await this.#updateAuth(true));
  2404. };
  2405. });
  2406. } catch (error) {
  2407. throwError(error, 'Reddit.useBeta');
  2408. return false;
  2409. }
  2410. }
  2411. async #updateAuth(beta = false) {
  2412. try {
  2413. const logStatus = scripts_echoLog({
  2414. text: i18n('updatingAuth', 'Reddit')
  2415. });
  2416. const {
  2417. result,
  2418. statusText,
  2419. status,
  2420. data
  2421. } = await tools_httpRequest({
  2422. url: 'https://www.reddit.com/',
  2423. method: 'GET',
  2424. nochche: true,
  2425. headers: {
  2426. 'Cache-Control': 'no-cache'
  2427. }
  2428. });
  2429. if (result === 'Success') {
  2430. if (data?.responseText.includes('www.reddit.com/login/')) {
  2431. logStatus.error(`Error:${i18n('loginReddit')}`, true);
  2432. return false;
  2433. }
  2434. if (data?.status === 200) {
  2435. if (data.responseText.includes('redesign-beta-optin-btn') && !beta) {
  2436. return await this.#useBeta();
  2437. }
  2438. const accessToken = data.responseText.match(/"accessToken":"(.*?)","expires":"(.*?)"/)?.[1];
  2439. if (accessToken) {
  2440. this.#auth = {
  2441. token: accessToken
  2442. };
  2443. logStatus.success();
  2444. return true;
  2445. }
  2446. logStatus.error('Error: Parameter "accessToken" not found!');
  2447. return false;
  2448. }
  2449. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2450. return false;
  2451. }
  2452. logStatus.error(`${result}:${statusText}(${status})`);
  2453. return false;
  2454. } catch (error) {
  2455. throwError(error, 'Reddit.updateAuth');
  2456. return false;
  2457. }
  2458. }
  2459. async #toggleTask({
  2460. name,
  2461. doTask = true
  2462. }) {
  2463. try {
  2464. if (!doTask && this.whiteList.reddits.includes(name)) {
  2465. scripts_echoLog({
  2466. type: 'whiteList',
  2467. text: 'Reddit.undoTask',
  2468. id: name
  2469. });
  2470. return true;
  2471. }
  2472. let type = doTask ? 'joiningReddit' : 'leavingReddit';
  2473. if (/^u_/.test(name)) {
  2474. type = doTask ? 'followingRedditUser' : 'unfollowingRedditUser';
  2475. }
  2476. const logStatus = scripts_echoLog({
  2477. type: type,
  2478. text: name
  2479. });
  2480. const {
  2481. result,
  2482. statusText,
  2483. status,
  2484. data
  2485. } = await tools_httpRequest({
  2486. url: 'https://oauth.reddit.com/api/subscribe?redditWebClient=desktop2x&app=desktop2x-client-production&raw_json=1&gilding_detail=1',
  2487. method: 'POST',
  2488. headers: {
  2489. authorization: `Bearer ${this.#auth.token}`,
  2490. 'content-type': 'application/x-www-form-urlencoded'
  2491. },
  2492. data: $.param({
  2493. action: doTask ? 'sub' : 'unsub',
  2494. sr_name: name,
  2495. api_type: 'json'
  2496. })
  2497. });
  2498. if (result === 'Success') {
  2499. if (data?.status === 200) {
  2500. logStatus.success();
  2501. if (doTask) {
  2502. this.tasks.reddits = unique([ ...this.tasks.reddits, name ]);
  2503. }
  2504. return true;
  2505. }
  2506. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2507. return false;
  2508. }
  2509. logStatus.error(`${result}:${statusText}(${status})`);
  2510. return false;
  2511. } catch (error) {
  2512. throwError(error, 'Reddit.toggleTask');
  2513. return false;
  2514. }
  2515. }
  2516. async toggle({
  2517. doTask = true,
  2518. redditLinks = []
  2519. }) {
  2520. try {
  2521. if (!this.#initialized) {
  2522. scripts_echoLog({
  2523. text: i18n('needInit')
  2524. });
  2525. return false;
  2526. }
  2527. const prom = [];
  2528. if (doTask && !globalOptions.doTask.reddit.reddits || !doTask && !globalOptions.undoTask.reddit.reddits) {
  2529. scripts_echoLog({
  2530. type: 'globalOptionsSkip',
  2531. text: 'reddit.reddits'
  2532. });
  2533. } else {
  2534. const realReddits = this.getRealParams('reddits', redditLinks, doTask, link => {
  2535. const name = link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1];
  2536. const userName = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1];
  2537. if (userName) {
  2538. return name || userName;
  2539. }
  2540. return name;
  2541. });
  2542. if (realReddits.length > 0) {
  2543. for (const name of realReddits) {
  2544. prom.push(this.#toggleTask({
  2545. name: name,
  2546. doTask: doTask
  2547. }));
  2548. await delay(1e3);
  2549. }
  2550. }
  2551. }
  2552. return await Promise.all(prom).then(() => true);
  2553. } catch (error) {
  2554. throwError(error, 'Reddit.toggle');
  2555. return false;
  2556. }
  2557. }
  2558. }
  2559. const social_Reddit = Reddit;
  2560. class Twitch extends social_Social {
  2561. tasks;
  2562. whiteList;
  2563. #auth = GM_getValue('twitchAuth') || {};
  2564. #cache = GM_getValue('twitchCache') || {};
  2565. #initialized = false;
  2566. #integrityToken;
  2567. constructor() {
  2568. super();
  2569. const defaultTasksTemplate = {
  2570. channels: []
  2571. };
  2572. this.tasks = defaultTasksTemplate;
  2573. this.whiteList = {
  2574. ...defaultTasksTemplate,
  2575. ...GM_getValue('whiteList')?.twitch || {}
  2576. };
  2577. }
  2578. async init() {
  2579. try {
  2580. if (this.#initialized) {
  2581. return true;
  2582. }
  2583. if (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId) {
  2584. if (await this.#updateAuth()) {
  2585. this.#initialized = true;
  2586. return true;
  2587. }
  2588. return false;
  2589. }
  2590. const isVerified = await this.#verifyAuth(true);
  2591. if (isVerified) {
  2592. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  2593. this.#initialized = true;
  2594. return true;
  2595. }
  2596. GM_setValue('twitchAuth', null);
  2597. if (await this.#updateAuth()) {
  2598. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  2599. this.#initialized = true;
  2600. return true;
  2601. }
  2602. scripts_echoLog({}).error(i18n('initFailed', 'Twitch'));
  2603. return false;
  2604. } catch (error) {
  2605. throwError(error, 'Twitch.init');
  2606. return false;
  2607. }
  2608. }
  2609. async #verifyAuth(isFirst) {
  2610. try {
  2611. const logStatus = scripts_echoLog({
  2612. text: i18n('verifyingAuth', 'Twitch')
  2613. });
  2614. const {
  2615. result,
  2616. statusText,
  2617. status,
  2618. data
  2619. } = await tools_httpRequest({
  2620. url: 'https://gql.twitch.tv/gql',
  2621. method: 'POST',
  2622. dataType: 'json',
  2623. headers: {
  2624. Authorization: `OAuth ${this.#auth.authToken}`,
  2625. 'Client-Id': this.#auth.clientId
  2626. },
  2627. data: '[{"operationName":"FrontPageNew_User","variables":{"limit":1},"extensions":{"persistedQuery":{"version":1,' + '"sha256Hash":"64bd07a2cbaca80699d62636d966cf6395a5d14a1f0a14282067dcb28b13eb11"}}}]'
  2628. });
  2629. if (result === 'Success') {
  2630. if (data?.status === 200 && data.response?.[0]?.data?.currentUser) {
  2631. await this.#integrity(isFirst);
  2632. logStatus.success();
  2633. return true;
  2634. }
  2635. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2636. return false;
  2637. }
  2638. logStatus.error(`${result}:${statusText}(${status})`);
  2639. return false;
  2640. } catch (error) {
  2641. throwError(error, 'Twitch.verifyAuth');
  2642. return false;
  2643. }
  2644. }
  2645. async #integrity(isFirst = true, ct = '') {
  2646. try {
  2647. const logStatus = scripts_echoLog({
  2648. text: i18n('checkingTwitchIntegrity')
  2649. });
  2650. if (isFirst && (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId)) {
  2651. return await this.#updateAuth(false);
  2652. }
  2653. const {
  2654. result,
  2655. statusText,
  2656. status,
  2657. data
  2658. } = await tools_httpRequest({
  2659. url: 'https://gql.twitch.tv/integrity',
  2660. method: 'POST',
  2661. dataType: 'json',
  2662. anonymous: true,
  2663. headers: {
  2664. Origin: 'https://www.twitch.tv',
  2665. Referer: 'https://www.twitch.tv/',
  2666. Authorization: `OAuth ${this.#auth.authToken}`,
  2667. 'Client-Id': this.#auth.clientId,
  2668. 'Client-Version': this.#auth.clientVersion,
  2669. 'X-Device-Id': this.#auth.deviceId,
  2670. 'Client-Session-Id': this.#auth.clientSessionId,
  2671. 'x-kpsdk-ct': ct
  2672. }
  2673. });
  2674. if (result === 'Success') {
  2675. if (!ct && data?.responseHeaders?.['x-kpsdk-ct']) {
  2676. return await this.#integrity(isFirst, data.responseHeaders['x-kpsdk-ct']);
  2677. }
  2678. if (data?.status === 200 && data.response?.token) {
  2679. this.#integrityToken = data.response.token;
  2680. logStatus.success();
  2681. return true;
  2682. }
  2683. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2684. return false;
  2685. }
  2686. logStatus.error(`${result}:${statusText}(${status})`);
  2687. return false;
  2688. } catch (error) {
  2689. throwError(error, 'Twitch.integrity');
  2690. return false;
  2691. }
  2692. }
  2693. async #updateAuth(isFirst = true) {
  2694. try {
  2695. const logStatus = scripts_echoLog({
  2696. text: i18n('updatingAuth', 'Twitch')
  2697. });
  2698. return await new Promise(resolve => {
  2699. const newTab = GM_openInTab('https://www.twitch.tv/', {
  2700. active: true,
  2701. insert: true,
  2702. setParent: true
  2703. });
  2704. newTab.name = 'ATv4_twitchAuth';
  2705. newTab.onclose = async () => {
  2706. const auth = GM_getValue('twitchAuth');
  2707. if (auth) {
  2708. this.#auth = auth;
  2709. logStatus.success();
  2710. resolve(await this.#verifyAuth(isFirst));
  2711. } else {
  2712. logStatus.error('Error: Update twitch auth failed!');
  2713. resolve(false);
  2714. }
  2715. };
  2716. });
  2717. } catch (error) {
  2718. throwError(error, 'Twitch.updateAuth');
  2719. return false;
  2720. }
  2721. }
  2722. async #toggleChannel({
  2723. name,
  2724. doTask = true
  2725. }) {
  2726. try {
  2727. if (!doTask && this.whiteList.channels.includes(name)) {
  2728. scripts_echoLog({
  2729. type: 'whiteList',
  2730. text: 'Twitch.unfollowChannel',
  2731. id: name
  2732. });
  2733. return true;
  2734. }
  2735. const channelId = await this.#getChannelId(name);
  2736. if (!channelId) {
  2737. return false;
  2738. }
  2739. const logStatus = scripts_echoLog({
  2740. type: `${doTask ? '' : 'un'}followingTwitchChannel`,
  2741. text: name
  2742. });
  2743. const followData = `[{"operationName":"FollowButton_FollowUser","variables":{"input":{"disableNotifications":false,"targetID":"${channelId}` + '"}},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"800e7346bdf7e5278a3c1d3f21b2b56e2639928f86815677a7126b093b2fdd08"}}}]';
  2744. const unfollowData = `[{"operationName":"FollowButton_UnfollowUser","variables":{"input":{"targetID":"${channelId}"}},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"f7dae976ebf41c755ae2d758546bfd176b4eeb856656098bb40e0a672ca0d880"}}}]';
  2745. const {
  2746. result,
  2747. statusText,
  2748. status,
  2749. data
  2750. } = await tools_httpRequest({
  2751. url: 'https://gql.twitch.tv/gql',
  2752. method: 'POST',
  2753. dataType: 'json',
  2754. anonymous: true,
  2755. headers: {
  2756. Origin: 'https://www.twitch.tv',
  2757. Referer: 'https://www.twitch.tv/',
  2758. Authorization: `OAuth ${this.#auth.authToken}`,
  2759. 'Client-Id': this.#auth.clientId,
  2760. 'Client-Version': this.#auth.clientVersion,
  2761. 'X-Device-Id': this.#auth.deviceId,
  2762. 'Client-Session-Id': this.#auth.clientSessionId,
  2763. 'Client-Integrity': this.#integrityToken
  2764. },
  2765. data: doTask ? followData : unfollowData
  2766. });
  2767. if (result === 'Success') {
  2768. if (data?.status === 200 && data.response?.[0] && !data.response[0].errors) {
  2769. logStatus.success();
  2770. if (doTask) {
  2771. this.tasks.channels = unique([ ...this.tasks.channels, name ]);
  2772. }
  2773. return true;
  2774. }
  2775. logStatus.error(`Error:${data?.response?.[0].errors?.[0]?.message || `${data?.statusText}(${data?.status})`}`);
  2776. return false;
  2777. }
  2778. logStatus.error(`${result}:${statusText}(${status})`);
  2779. return false;
  2780. } catch (error) {
  2781. throwError(error, 'Twitch.toggleChannel');
  2782. return false;
  2783. }
  2784. }
  2785. async #getChannelId(name) {
  2786. try {
  2787. const logStatus = scripts_echoLog({
  2788. type: 'gettingTwitchChannelId',
  2789. text: name
  2790. });
  2791. const channelId = this.#cache[name];
  2792. if (channelId) {
  2793. logStatus.success();
  2794. return channelId;
  2795. }
  2796. const {
  2797. result,
  2798. statusText,
  2799. status,
  2800. data
  2801. } = await tools_httpRequest({
  2802. url: 'https://gql.twitch.tv/gql',
  2803. method: 'POST',
  2804. headers: {
  2805. Authorization: `OAuth ${this.#auth.authToken}`,
  2806. 'Client-Id': this.#auth.clientId
  2807. },
  2808. responseType: 'json',
  2809. data: `[{"operationName":"ActiveWatchParty","variables":{"channelLogin":"${name}"},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"4a8156c97b19e3a36e081cf6d6ddb5dbf9f9b02ae60e4d2ff26ed70aebc80a30"}}}]'
  2810. });
  2811. if (result === 'Success') {
  2812. if (data?.status === 200) {
  2813. const channelId = data.response?.[0]?.data?.user?.id;
  2814. if (channelId) {
  2815. this.#setCache(name, String(channelId));
  2816. logStatus.success();
  2817. return channelId;
  2818. }
  2819. logStatus.error(`Error:${data.statusText}(${data.status})`);
  2820. return false;
  2821. }
  2822. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2823. return false;
  2824. }
  2825. logStatus.error(`${result}:${statusText}(${status})`);
  2826. return false;
  2827. } catch (error) {
  2828. throwError(error, 'Twitch.getChannelId');
  2829. return false;
  2830. }
  2831. }
  2832. async toggle({
  2833. doTask = true,
  2834. channelLinks = []
  2835. }) {
  2836. try {
  2837. if (!this.#initialized) {
  2838. scripts_echoLog({
  2839. text: i18n('needInit')
  2840. });
  2841. return false;
  2842. }
  2843. const prom = [];
  2844. if (doTask && !globalOptions.doTask.twitch.channels || !doTask && !globalOptions.undoTask.twitch.channels) {
  2845. scripts_echoLog({
  2846. type: 'globalOptionsSkip',
  2847. text: 'twitch.channels'
  2848. });
  2849. } else {
  2850. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2]);
  2851. if (realChannels.length > 0) {
  2852. for (const channel of realChannels) {
  2853. prom.push(this.#toggleChannel({
  2854. name: channel,
  2855. doTask: doTask
  2856. }));
  2857. await delay(1e3);
  2858. }
  2859. }
  2860. }
  2861. return Promise.all(prom).then(() => true);
  2862. } catch (error) {
  2863. throwError(error, 'Twitch.toggle');
  2864. return false;
  2865. }
  2866. }
  2867. #setCache(name, id) {
  2868. try {
  2869. this.#cache[name] = id;
  2870. GM_setValue('twitchCache', this.#cache);
  2871. } catch (error) {
  2872. throwError(error, 'Twitch.setCache');
  2873. }
  2874. }
  2875. }
  2876. const social_Twitch = Twitch;
  2877. class Twitter extends social_Social {
  2878. tasks;
  2879. whiteList;
  2880. #verifyId = globalOptions.other.twitterVerifyId;
  2881. #auth = GM_getValue('twitterAuth') || {};
  2882. #cache = GM_getValue('twitterCache') || {};
  2883. #initialized = false;
  2884. constructor() {
  2885. super();
  2886. const defaultTasksTemplate = {
  2887. users: [],
  2888. retweets: [],
  2889. likes: []
  2890. };
  2891. this.tasks = defaultTasksTemplate;
  2892. this.whiteList = {
  2893. ...defaultTasksTemplate,
  2894. ...GM_getValue('whiteList')?.twitter || {}
  2895. };
  2896. }
  2897. async init() {
  2898. try {
  2899. if (this.#initialized) {
  2900. return true;
  2901. }
  2902. if (!this.#auth.ct0) {
  2903. if (await this.#updateAuth()) {
  2904. this.#initialized = true;
  2905. return true;
  2906. }
  2907. return false;
  2908. }
  2909. const isVerified = await this.#verifyAuth();
  2910. if (isVerified) {
  2911. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  2912. this.#initialized = true;
  2913. return true;
  2914. }
  2915. GM_setValue('twitterAuth', null);
  2916. if (await this.#updateAuth()) {
  2917. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  2918. this.#initialized = true;
  2919. return true;
  2920. }
  2921. scripts_echoLog({}).error(i18n('initFailed', 'Twitter'));
  2922. return false;
  2923. } catch (error) {
  2924. throwError(error, 'Twitter.init');
  2925. return false;
  2926. }
  2927. }
  2928. async #verifyAuth() {
  2929. try {
  2930. return await this.#toggleUser({
  2931. name: 'verify',
  2932. doTask: true,
  2933. verify: true
  2934. });
  2935. } catch (error) {
  2936. throwError(error, 'Twitter.verifyAuth');
  2937. return false;
  2938. }
  2939. }
  2940. async #updateAuth() {
  2941. try {
  2942. const logStatus = scripts_echoLog({
  2943. text: i18n('updatingAuth', 'Twitter')
  2944. });
  2945. return await new Promise(resolve => {
  2946. GM_cookie.list({
  2947. url: 'https://x.com/settings/account'
  2948. }, async (cookies, error) => {
  2949. if (!error) {
  2950. const [ ct0, isLogin ] = cookies.map(cookie => [ 'ct0', 'twid' ].includes(cookie.name) ? cookie.value : null).filter(cookie => cookie);
  2951. if (isLogin && ct0) {
  2952. GM_setValue('twitterAuth', {
  2953. ct0: ct0
  2954. });
  2955. this.#auth = {
  2956. ct0: ct0
  2957. };
  2958. logStatus.success();
  2959. resolve(await this.#verifyAuth());
  2960. } else {
  2961. logStatus.error(i18n('needLogin'));
  2962. resolve(false);
  2963. }
  2964. } else {
  2965. logStatus.error('Error: Update twitter auth failed!');
  2966. resolve(false);
  2967. }
  2968. });
  2969. });
  2970. } catch (error) {
  2971. throwError(error, 'Twitter.updateToken');
  2972. return false;
  2973. }
  2974. }
  2975. async #toggleUser({
  2976. name,
  2977. doTask = true,
  2978. verify = false
  2979. }) {
  2980. try {
  2981. if (!doTask && !verify && this.whiteList.users.includes(name)) {
  2982. scripts_echoLog({
  2983. type: 'whiteList',
  2984. text: 'Twitter.unfollowUser',
  2985. id: name
  2986. });
  2987. return true;
  2988. }
  2989. const userId = verify ? this.#verifyId : await this.userName2id(name);
  2990. if (!userId) {
  2991. return false;
  2992. }
  2993. const logStatus = verify ? scripts_echoLog({
  2994. text: i18n('verifyingAuth', 'Twitter')
  2995. }) : scripts_echoLog({
  2996. type: `${doTask ? '' : 'un'}followingTwitterUser`,
  2997. text: name
  2998. });
  2999. const {
  3000. result,
  3001. statusText,
  3002. status,
  3003. data
  3004. } = await tools_httpRequest({
  3005. url: `https://x.com/i/api/1.1/friendships/${doTask ? 'create' : 'destroy'}.json`,
  3006. method: 'POST',
  3007. headers: {
  3008. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3009. 'Content-Type': 'application/x-www-form-urlencoded',
  3010. 'x-csrf-token': this.#auth.ct0
  3011. },
  3012. responseType: 'json',
  3013. data: $.param({
  3014. include_profile_interstitial_type: 1,
  3015. include_blocking: 1,
  3016. include_blocked_by: 1,
  3017. include_followed_by: 1,
  3018. include_want_retweets: 1,
  3019. include_mute_edge: 1,
  3020. include_can_dm: 1,
  3021. include_can_media_tag: 1,
  3022. skip_status: 1,
  3023. id: userId
  3024. })
  3025. });
  3026. if (result === 'Success') {
  3027. if (data?.status === 200) {
  3028. logStatus.success();
  3029. if (doTask && !verify) {
  3030. this.tasks.users = unique([ ...this.tasks.users, name ]);
  3031. }
  3032. return true;
  3033. }
  3034. if (verify && data?.status === 403 && data.response?.errors?.[0]?.code === 158) {
  3035. logStatus.success();
  3036. return true;
  3037. }
  3038. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3039. return false;
  3040. }
  3041. logStatus.error(`${result}:${statusText}(${status})`);
  3042. return false;
  3043. } catch (error) {
  3044. throwError(error, 'Twitter.toggleUser');
  3045. return false;
  3046. }
  3047. }
  3048. async userName2id(name) {
  3049. try {
  3050. const logStatus = scripts_echoLog({
  3051. type: 'gettingTwitterUserId',
  3052. text: name
  3053. });
  3054. const userId = this.#cache[name];
  3055. if (userId) {
  3056. logStatus.success();
  3057. return userId;
  3058. }
  3059. const {
  3060. result,
  3061. statusText,
  3062. status,
  3063. data
  3064. } = await tools_httpRequest({
  3065. 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`,
  3066. method: 'GET',
  3067. headers: {
  3068. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3069. 'content-type': 'application/json',
  3070. referer: `https://x.com/${name}`,
  3071. 'x-csrf-token': this.#auth.ct0
  3072. },
  3073. responseType: 'json'
  3074. });
  3075. if (result === 'Success') {
  3076. if (data?.status === 200) {
  3077. let response = data.response || (typeof data.responseText === 'object' ? data.responseText : null);
  3078. if (!response) {
  3079. try {
  3080. response = JSON.parse(data.responseText);
  3081. } catch (error) {
  3082. response = null;
  3083. }
  3084. }
  3085. const userId = String(response?.data?.user?.result?.rest_id);
  3086. if (userId) {
  3087. this.#setCache(name, userId);
  3088. logStatus.success();
  3089. return userId;
  3090. }
  3091. logStatus.error(`Error:${data.statusText}(${data.status})`);
  3092. return false;
  3093. }
  3094. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3095. return false;
  3096. }
  3097. logStatus.error(`${result}:${statusText}(${status})`);
  3098. return false;
  3099. } catch (error) {
  3100. throwError(error, 'Twitter.getUserId');
  3101. return false;
  3102. }
  3103. }
  3104. async #toggleRetweet({
  3105. retweetId,
  3106. doTask = true
  3107. }) {
  3108. try {
  3109. if (!doTask && this.whiteList.retweets.includes(retweetId)) {
  3110. scripts_echoLog({
  3111. type: 'whiteList',
  3112. text: 'Twitter.unretweet',
  3113. id: retweetId
  3114. });
  3115. return true;
  3116. }
  3117. const logStatus = scripts_echoLog({
  3118. type: `${doTask ? '' : 'un'}retweetting`,
  3119. text: retweetId
  3120. });
  3121. const {
  3122. result,
  3123. statusText,
  3124. status,
  3125. data
  3126. } = await tools_httpRequest({
  3127. url: `https://x.com/i/api/graphql/${doTask ? 'ojPdsZsimiJrUGLR1sjUtA/CreateRetweet' : 'iQtK4dl5hBmXewYZuEOKVw/DeleteRetweet'}`,
  3128. method: 'POST',
  3129. headers: {
  3130. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3131. 'Content-Type': 'application/json',
  3132. 'x-csrf-token': this.#auth.ct0
  3133. },
  3134. data: `{"variables":{"tweet_id":"${retweetId}","dark_request":false},"queryId":"${doTask ? 'ojPdsZsimiJrUGLR1sjUtA' : 'iQtK4dl5hBmXewYZuEOKVw'}"}`,
  3135. responseType: 'json'
  3136. });
  3137. if (result === 'Success') {
  3138. if (data?.status === 200 || data?.status === 403 && data.response?.errors?.[0]?.code === 327) {
  3139. logStatus.success();
  3140. if (doTask) {
  3141. this.tasks.retweets = unique([ ...this.tasks.retweets, retweetId ]);
  3142. }
  3143. return true;
  3144. }
  3145. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3146. return false;
  3147. }
  3148. logStatus.error(`${result}:${statusText}(${status})`);
  3149. return false;
  3150. } catch (error) {
  3151. throwError(error, 'Twitter.toggleRetweet');
  3152. return false;
  3153. }
  3154. }
  3155. async toggle({
  3156. doTask = true,
  3157. userLinks = [],
  3158. retweetLinks = []
  3159. }) {
  3160. try {
  3161. if (!this.#initialized) {
  3162. scripts_echoLog({
  3163. text: i18n('needInit')
  3164. });
  3165. return false;
  3166. }
  3167. const prom = [];
  3168. if (doTask && !globalOptions.doTask.twitter.users || !doTask && !globalOptions.undoTask.twitter.users) {
  3169. scripts_echoLog({
  3170. type: 'globalOptionsSkip',
  3171. text: 'twitter.users'
  3172. });
  3173. } else {
  3174. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/x\.com\/(.+)/)?.[1] || link.match(/https:\/\/twitter\.com\/(.+)/)?.[1]);
  3175. if (realUsers.length > 0) {
  3176. for (const user of realUsers) {
  3177. prom.push(this.#toggleUser({
  3178. name: user,
  3179. doTask: doTask
  3180. }));
  3181. await delay(1e3);
  3182. }
  3183. }
  3184. }
  3185. if (doTask && !globalOptions.doTask.twitter.retweets || !doTask && !globalOptions.undoTask.twitter.retweets) {
  3186. scripts_echoLog({
  3187. type: 'globalOptionsSkip',
  3188. text: 'twitter.retweets'
  3189. });
  3190. } else {
  3191. const realRetweets = this.getRealParams('retweets', retweetLinks, doTask, link => link.match(/https:\/\/x\.com\/.*?\/status\/([\d]+)/)?.[1] || link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1]);
  3192. if (realRetweets.length > 0) {
  3193. for (const retweet of realRetweets) {
  3194. prom.push(this.#toggleRetweet({
  3195. retweetId: retweet,
  3196. doTask: doTask
  3197. }));
  3198. await delay(1e3);
  3199. }
  3200. }
  3201. }
  3202. return Promise.all(prom).then(() => true);
  3203. } catch (error) {
  3204. throwError(error, 'Twitter.toggle');
  3205. return false;
  3206. }
  3207. }
  3208. #setCache(name, id) {
  3209. try {
  3210. this.#cache[name] = id;
  3211. GM_setValue('twitterCache', this.#cache);
  3212. } catch (error) {
  3213. throwError(error, 'Twitter.setCache');
  3214. }
  3215. }
  3216. }
  3217. const social_Twitter = Twitter;
  3218. class Vk extends social_Social {
  3219. tasks;
  3220. whiteList;
  3221. #username = '';
  3222. #cache = GM_getValue('vkCache') || {};
  3223. #initialized = false;
  3224. constructor() {
  3225. super();
  3226. const defaultTasksTemplate = {
  3227. names: []
  3228. };
  3229. this.tasks = defaultTasksTemplate;
  3230. this.whiteList = {
  3231. ...defaultTasksTemplate,
  3232. ...GM_getValue('whiteList')?.vk || {}
  3233. };
  3234. }
  3235. async init() {
  3236. try {
  3237. if (this.#initialized) {
  3238. return true;
  3239. }
  3240. const isVerified = await this.#verifyAuth();
  3241. if (isVerified) {
  3242. scripts_echoLog({}).success(i18n('initSuccess', 'Vk'));
  3243. this.#initialized = true;
  3244. return true;
  3245. }
  3246. scripts_echoLog({}).error(i18n('initFailed', 'Vk'));
  3247. return false;
  3248. } catch (error) {
  3249. throwError(error, 'Vk.init');
  3250. return false;
  3251. }
  3252. }
  3253. async #verifyAuth() {
  3254. try {
  3255. const logStatus = scripts_echoLog({
  3256. text: i18n('verifyAuth', 'Vk')
  3257. });
  3258. const {
  3259. result,
  3260. statusText,
  3261. status,
  3262. data
  3263. } = await tools_httpRequest({
  3264. url: 'https://vk.com/im',
  3265. method: 'GET'
  3266. });
  3267. if (result === 'Success') {
  3268. if (data?.finalUrl.includes('vk.com/login')) {
  3269. logStatus.error(`Error:${i18n('loginVk')}`, true);
  3270. return false;
  3271. }
  3272. if (data?.status === 200) {
  3273. this.#username = data.responseText.match(/TopNavBtn__profileLink" href="\/(.*?)"/)?.[1] || '';
  3274. logStatus.success();
  3275. return true;
  3276. }
  3277. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3278. return false;
  3279. }
  3280. logStatus.error(`${result}:${statusText}(${status})`);
  3281. return false;
  3282. } catch (error) {
  3283. throwError(error, 'Vk.verifyAuth');
  3284. return false;
  3285. }
  3286. }
  3287. async #toggleGroup(name, dataParam, doTask = true) {
  3288. try {
  3289. const logStatus = scripts_echoLog({
  3290. type: doTask ? 'joiningVkGroup' : 'leavingVkGroup',
  3291. text: name
  3292. });
  3293. if (dataParam.groupAct === 'enter' && !doTask || dataParam.groupAct === 'leave' && doTask) {
  3294. logStatus.success();
  3295. return true;
  3296. }
  3297. const reqData = {
  3298. act: doTask ? 'enter' : 'leave',
  3299. al: 1,
  3300. gid: dataParam.groupId,
  3301. hash: dataParam.groupHash
  3302. };
  3303. if (doTask) {
  3304. reqData.context = '_';
  3305. }
  3306. const {
  3307. result,
  3308. statusText,
  3309. status,
  3310. data
  3311. } = await tools_httpRequest({
  3312. url: 'https://vk.com/al_groups.php',
  3313. method: 'POST',
  3314. headers: {
  3315. origin: 'https://vk.com',
  3316. referer: `https://vk.com/${name}`,
  3317. 'content-type': 'application/x-www-form-urlencoded'
  3318. },
  3319. data: $.param(reqData)
  3320. });
  3321. if (result === 'Success') {
  3322. if (data?.status === 200) {
  3323. logStatus.success();
  3324. if (doTask) {
  3325. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3326. }
  3327. return true;
  3328. }
  3329. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3330. return false;
  3331. }
  3332. logStatus.error(`${result}:${statusText}(${status})`);
  3333. return false;
  3334. } catch (error) {
  3335. throwError(error, 'Vk.toggleGroup');
  3336. return false;
  3337. }
  3338. }
  3339. async #togglePublic(name, dataParam, doTask = true) {
  3340. try {
  3341. const logStatus = scripts_echoLog({
  3342. type: doTask ? 'joiningVkPublic' : 'leavingVkPublic',
  3343. text: name
  3344. });
  3345. if (dataParam.publicJoined && doTask || !dataParam.publicJoined && !doTask) {
  3346. logStatus.success();
  3347. return true;
  3348. }
  3349. const {
  3350. result,
  3351. statusText,
  3352. status,
  3353. data
  3354. } = await tools_httpRequest({
  3355. url: 'https://vk.com/al_public.php',
  3356. method: 'POST',
  3357. headers: {
  3358. origin: 'https://vk.com',
  3359. referer: `https://vk.com/${name}`,
  3360. 'content-type': 'application/x-www-form-urlencoded'
  3361. },
  3362. data: $.param({
  3363. act: doTask ? 'a_enter' : 'a_leave',
  3364. al: 1,
  3365. pid: dataParam.publicPid,
  3366. hash: dataParam.publicHash
  3367. })
  3368. });
  3369. if (result === 'Success') {
  3370. if (data?.status === 200) {
  3371. logStatus.success();
  3372. if (doTask) {
  3373. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3374. }
  3375. return true;
  3376. }
  3377. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3378. return false;
  3379. }
  3380. logStatus.error(`${result}:${statusText}(${status})`);
  3381. return false;
  3382. } catch (error) {
  3383. throwError(error, 'Vk.togglePublic');
  3384. return false;
  3385. }
  3386. }
  3387. async #sendWall(name) {
  3388. try {
  3389. const logStatus = scripts_echoLog({
  3390. type: 'sendingVkWall',
  3391. text: name
  3392. });
  3393. const {
  3394. result,
  3395. statusText,
  3396. status,
  3397. data
  3398. } = await tools_httpRequest({
  3399. url: 'https://vk.com/like.php',
  3400. method: 'POST',
  3401. headers: {
  3402. origin: 'https://vk.com',
  3403. referer: `https://vk.com/${name}`,
  3404. 'content-type': 'application/x-www-form-urlencoded'
  3405. },
  3406. data: $.param({
  3407. act: 'publish_box',
  3408. al: 1,
  3409. object: name
  3410. })
  3411. });
  3412. if (result === 'Success') {
  3413. if (data?.status === 200) {
  3414. const hash = data.responseText.match(/shHash:[\s]*'(.*?)'/)?.[1];
  3415. if (hash) {
  3416. const {
  3417. result: resultR,
  3418. statusText: statusTextR,
  3419. status: statusR,
  3420. data: dataR
  3421. } = await tools_httpRequest({
  3422. url: 'https://vk.com/like.php',
  3423. method: 'POST',
  3424. headers: {
  3425. origin: 'https://vk.com',
  3426. referer: `https://vk.com/${name}`,
  3427. 'content-type': 'application/x-www-form-urlencoded'
  3428. },
  3429. data: $.param({
  3430. Message: '',
  3431. act: 'a_do_publish',
  3432. al: 1,
  3433. close_comments: 0,
  3434. friends_only: 0,
  3435. from: 'box',
  3436. hash: hash,
  3437. list: '',
  3438. mark_as_ads: 0,
  3439. mute_notifications: 0,
  3440. object: name,
  3441. ret_data: 1,
  3442. to: 0
  3443. })
  3444. });
  3445. if (resultR === 'Success') {
  3446. if (dataR?.status === 200) {
  3447. const jsonData = JSON.parse(dataR.responseText?.replace('\x3c!--', '') || '{}');
  3448. if (jsonData?.payload?.[1]?.[1]?.share_my === true) {
  3449. logStatus.success();
  3450. const postId = String(jsonData?.payload?.[1]?.[1]?.post_id);
  3451. const ownerId = String(jsonData?.payload?.[1]?.[1]?.owner_id);
  3452. if (postId && ownerId) {
  3453. this.#setCache(name, `${ownerId}_${postId}`);
  3454. }
  3455. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3456. return true;
  3457. }
  3458. }
  3459. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  3460. return false;
  3461. }
  3462. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  3463. return false;
  3464. }
  3465. logStatus.error('Error: Get "hash" failed');
  3466. return false;
  3467. }
  3468. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3469. return false;
  3470. }
  3471. logStatus.error(`${result}:${statusText}(${status})`);
  3472. return false;
  3473. } catch (error) {
  3474. throwError(error, 'Vk.sendWall');
  3475. return false;
  3476. }
  3477. }
  3478. async #deleteWall(name, dataParams) {
  3479. try {
  3480. const logStatus = scripts_echoLog({
  3481. type: 'deletingVkWall',
  3482. text: name
  3483. });
  3484. const {
  3485. result,
  3486. statusText,
  3487. status,
  3488. data
  3489. } = await tools_httpRequest({
  3490. url: 'https://vk.com/al_wall.php?act=delete',
  3491. method: 'POST',
  3492. headers: {
  3493. origin: 'https://vk.com',
  3494. referer: `https://vk.com/${this.#username}?w=wall${this.#cache[name]}%2Fall`,
  3495. 'content-type': 'application/x-www-form-urlencoded'
  3496. },
  3497. data: $.param({
  3498. act: 'delete',
  3499. al: 1,
  3500. confirm: 0,
  3501. from: 'wkview',
  3502. hash: dataParams.wallHash,
  3503. post: this.#cache[name]
  3504. })
  3505. });
  3506. if (result === 'Success') {
  3507. if (data?.status === 200) {
  3508. const jsonData = JSON.parse(data.responseText?.replace('\x3c!--', '') || '{}');
  3509. if (jsonData?.payload?.[1]?.[1]) {
  3510. logStatus.success();
  3511. return true;
  3512. }
  3513. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3514. return false;
  3515. }
  3516. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3517. return false;
  3518. }
  3519. logStatus.error(`${result}:${statusText}(${status})`);
  3520. return false;
  3521. } catch (error) {
  3522. throwError(error, 'Vk.deleteWall');
  3523. return false;
  3524. }
  3525. }
  3526. async #getId(name, doTask) {
  3527. try {
  3528. let url = `https://vk.com/${name}`;
  3529. if (/^wall-/.test(name)) {
  3530. if (doTask) {
  3531. return {
  3532. type: 'sendWall'
  3533. };
  3534. }
  3535. if (!this.#cache[name]) {
  3536. return {
  3537. type: 'unSupport'
  3538. };
  3539. }
  3540. url = `https://vk.com/${this.#username}?w=wall${this.#cache[name]}`;
  3541. }
  3542. const logStatus = scripts_echoLog({
  3543. type: 'gettingVkId',
  3544. text: name
  3545. });
  3546. const {
  3547. result,
  3548. statusText,
  3549. status,
  3550. data
  3551. } = await tools_httpRequest({
  3552. url: url,
  3553. method: 'GET'
  3554. });
  3555. if (result === 'Success') {
  3556. if (data?.status === 200) {
  3557. const [ , groupAct, groupId, , groupHash ] = data.responseText.match(/Groups.(enter|leave)\(.*?,.*?([\d]+?), (&#39;|')(.*?)(&#39;|')/) || [];
  3558. const publicHash = data.responseText.match(/"enterHash":"(.*?)"/)?.[1];
  3559. const publicPid = data.responseText.match(/"public_id":([\d]+?),/)?.[1];
  3560. const publicJoined = !data.responseText.includes('Public.subscribe');
  3561. if (groupAct && groupId && groupHash) {
  3562. logStatus.success();
  3563. return {
  3564. groupAct: groupAct,
  3565. groupId: groupId,
  3566. groupHash: groupHash,
  3567. type: 'group'
  3568. };
  3569. } else if (publicHash && publicPid) {
  3570. logStatus.success();
  3571. return {
  3572. publicHash: publicHash,
  3573. publicPid: publicPid,
  3574. publicJoined: publicJoined,
  3575. type: 'public'
  3576. };
  3577. } else if (data.responseText.includes('wall.deletePost') && !doTask) {
  3578. const wallHash = data.responseText.match(/wall\.deletePost\(this, '.*?', '(.*?)'\)/)?.[1];
  3579. if (wallHash) {
  3580. logStatus.success();
  3581. return {
  3582. type: 'deleteWall',
  3583. wallHash: wallHash
  3584. };
  3585. }
  3586. } else if (name.includes('wall') && doTask) {
  3587. logStatus.success();
  3588. return {
  3589. type: 'sendWall'
  3590. };
  3591. }
  3592. logStatus.error('Error: Parameters not found!');
  3593. return false;
  3594. }
  3595. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3596. return false;
  3597. }
  3598. logStatus.error(`${result}:${statusText}(${status})`);
  3599. return false;
  3600. } catch (error) {
  3601. throwError(error, 'Vk.getId');
  3602. return false;
  3603. }
  3604. }
  3605. async #toggleVk({
  3606. name,
  3607. doTask = true
  3608. }) {
  3609. try {
  3610. if (!doTask && this.whiteList.names.includes(name)) {
  3611. scripts_echoLog({
  3612. type: 'whiteList',
  3613. text: 'Vk.undoTask',
  3614. id: name
  3615. });
  3616. return true;
  3617. }
  3618. const formatName = name.replace(/\/$/, '');
  3619. const data = await this.#getId(formatName, doTask);
  3620. if (!data) {
  3621. return false;
  3622. }
  3623. switch (data.type) {
  3624. case 'group':
  3625. return await this.#toggleGroup(formatName, data, doTask);
  3626.  
  3627. case 'public':
  3628. return await this.#togglePublic(formatName, data, doTask);
  3629.  
  3630. case 'sendWall':
  3631. return doTask ? await this.#sendWall(formatName) : true;
  3632.  
  3633. case 'deleteWall':
  3634. return doTask ? true : await this.#deleteWall(formatName, data);
  3635.  
  3636. default:
  3637. return false;
  3638. }
  3639. } catch (error) {
  3640. throwError(error, 'Vk.toggleVk');
  3641. return false;
  3642. }
  3643. }
  3644. async toggle({
  3645. doTask = true,
  3646. nameLinks = []
  3647. }) {
  3648. try {
  3649. if (!this.#initialized) {
  3650. scripts_echoLog({
  3651. text: i18n('needInit')
  3652. });
  3653. return false;
  3654. }
  3655. const prom = [];
  3656. if (doTask && !globalOptions.doTask.vk.names || !doTask && !globalOptions.undoTask.vk.names) {
  3657. scripts_echoLog({
  3658. type: 'globalOptionsSkip',
  3659. text: 'vk.names'
  3660. });
  3661. } else {
  3662. const realNames = this.getRealParams('names', nameLinks, doTask, link => link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1]);
  3663. if (realNames.length > 0) {
  3664. for (const name of realNames) {
  3665. prom.push(this.#toggleVk({
  3666. name: name,
  3667. doTask: doTask
  3668. }));
  3669. await delay(1e3);
  3670. }
  3671. }
  3672. }
  3673. return Promise.all(prom).then(() => true);
  3674. } catch (error) {
  3675. throwError(error, 'Vk.toggle');
  3676. return false;
  3677. }
  3678. }
  3679. #setCache(name, postId) {
  3680. try {
  3681. this.#cache[name] = postId;
  3682. GM_setValue('vkCache', this.#cache);
  3683. } catch (error) {
  3684. throwError(error, 'Vk.setCache');
  3685. }
  3686. }
  3687. }
  3688. const social_Vk = Vk;
  3689. const getInfo = async function(link, type) {
  3690. try {
  3691. const logStatus = scripts_echoLog({
  3692. text: i18n('gettingYtbToken')
  3693. });
  3694. const {
  3695. result,
  3696. statusText,
  3697. status,
  3698. data
  3699. } = await tools_httpRequest({
  3700. url: link,
  3701. method: 'GET'
  3702. });
  3703. if (result === 'Success') {
  3704. if (data?.status === 200) {
  3705. if (data.responseText.includes('accounts.google.com/ServiceLogin?service=youtube')) {
  3706. logStatus.error(`Error:${i18n('loginYtb')}`, true);
  3707. return {
  3708. needLogin: true
  3709. };
  3710. }
  3711. const apiKey = data.responseText.match(/"INNERTUBE_API_KEY":"(.*?)"/)?.[1];
  3712. const context = (data.responseText.match(/\(\{"INNERTUBE_CONTEXT":([\w\W]*?)\}\)/) || data.responseText.match(/"INNERTUBE_CONTEXT":([\w\W]*?\}),"INNERTUBE/))?.[1] || '{}';
  3713. const {
  3714. client,
  3715. request
  3716. } = JSON.parse(context);
  3717. if (apiKey && client && request) {
  3718. client.hl = 'en';
  3719. if (type === 'channel') {
  3720. const channelId = data.responseText.match(/"channelId":"(.+?)"/)?.[1];
  3721. if (channelId) {
  3722. logStatus.success();
  3723. return {
  3724. params: {
  3725. apiKey: apiKey,
  3726. client: client,
  3727. request: request,
  3728. channelId: channelId
  3729. }
  3730. };
  3731. }
  3732. logStatus.error('Error: Get "channelId" failed!');
  3733. return {};
  3734. } else if (type === 'likeVideo') {
  3735. const videoId = data.responseText.match(/<link rel="shortlinkUrl" href="https:\/\/youtu\.be\/(.*?)">/)?.[1];
  3736. const likeParams = data.responseText.match(/"likeParams":"(.*?)"/)?.[1];
  3737. if (videoId) {
  3738. logStatus.success();
  3739. return {
  3740. params: {
  3741. apiKey: apiKey,
  3742. client: client,
  3743. request: request,
  3744. videoId: videoId,
  3745. likeParams: likeParams
  3746. }
  3747. };
  3748. }
  3749. logStatus.error('Error: Get "videoId" failed!');
  3750. return {};
  3751. }
  3752. logStatus.error('Error: Unknown type');
  3753. return {};
  3754. }
  3755. logStatus.error('Error: Parameter "apiKey" not found!');
  3756. return {};
  3757. }
  3758. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3759. return {};
  3760. }
  3761. logStatus.error(`${result}:${statusText}(${status})`);
  3762. return {};
  3763. } catch (error) {
  3764. throwError(error, 'Youtube.getInfo');
  3765. return {};
  3766. }
  3767. };
  3768. class Youtube extends social_Social {
  3769. tasks;
  3770. whiteList;
  3771. #auth = GM_getValue('youtubeAuth') || {};
  3772. #initialized = false;
  3773. #verifyChannel = `https://www.youtube.com/channel/${globalOptions.other.youtubeVerifyChannel}`;
  3774. constructor() {
  3775. super();
  3776. const defaultTasksTemplate = {
  3777. channels: [],
  3778. likes: []
  3779. };
  3780. this.tasks = defaultTasksTemplate;
  3781. this.whiteList = {
  3782. ...defaultTasksTemplate,
  3783. ...GM_getValue('whiteList')?.youtube || {}
  3784. };
  3785. }
  3786. async init() {
  3787. try {
  3788. if (this.#initialized) {
  3789. return true;
  3790. }
  3791. if (!this.#auth.PAPISID) {
  3792. if (await this.#updateAuth()) {
  3793. this.#initialized = true;
  3794. return true;
  3795. }
  3796. return false;
  3797. }
  3798. const isVerified = await this.#verifyAuth();
  3799. if (isVerified) {
  3800. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  3801. this.#initialized = true;
  3802. return true;
  3803. }
  3804. GM_setValue('youtubeAuth', null);
  3805. if (await this.#updateAuth()) {
  3806. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  3807. this.#initialized = true;
  3808. return true;
  3809. }
  3810. scripts_echoLog({}).error(i18n('initFailed', 'Youtube'));
  3811. return false;
  3812. } catch (error) {
  3813. throwError(error, 'Youtube.init');
  3814. return false;
  3815. }
  3816. }
  3817. async #verifyAuth() {
  3818. try {
  3819. return await this.#toggleChannel({
  3820. link: this.#verifyChannel,
  3821. doTask: true,
  3822. verify: true
  3823. });
  3824. } catch (error) {
  3825. throwError(error, 'Youtube.verifyAuth');
  3826. return false;
  3827. }
  3828. }
  3829. async #updateAuth() {
  3830. try {
  3831. const logStatus = scripts_echoLog({
  3832. text: i18n('updatingAuth', 'Youtube')
  3833. });
  3834. return await new Promise(resolve => {
  3835. GM_cookie.list({
  3836. url: 'https://www.youtube.com/@YouTube'
  3837. }, async (cookies, error) => {
  3838. if (!error) {
  3839. const PAPISID = cookies.find(cookie => cookie.name === '__Secure-3PAPISID')?.value;
  3840. if (PAPISID) {
  3841. GM_setValue('youtubeAuth', {
  3842. PAPISID: PAPISID
  3843. });
  3844. this.#auth = {
  3845. PAPISID: PAPISID
  3846. };
  3847. logStatus.success();
  3848. resolve(await this.#verifyAuth());
  3849. } else {
  3850. logStatus.error(i18n('needLogin'));
  3851. resolve(false);
  3852. }
  3853. } else {
  3854. logStatus.error('Error: Update youtube auth failed!');
  3855. resolve(false);
  3856. }
  3857. });
  3858. });
  3859. } catch (error) {
  3860. throwError(error, 'Youtube.updateAuth');
  3861. return false;
  3862. }
  3863. }
  3864. #getInfo(link, type) {
  3865. return getInfo(link, type);
  3866. }
  3867. async #toggleChannel({
  3868. link,
  3869. doTask = true,
  3870. verify = false
  3871. }) {
  3872. try {
  3873. const {
  3874. params,
  3875. needLogin
  3876. } = await this.#getInfo(link, 'channel');
  3877. const {
  3878. apiKey,
  3879. client,
  3880. request,
  3881. channelId
  3882. } = params || {};
  3883. if (needLogin) {
  3884. scripts_echoLog({
  3885. html: i18n('loginYtb')
  3886. });
  3887. return false;
  3888. }
  3889. if (!(apiKey && client && request && channelId)) {
  3890. scripts_echoLog({
  3891. text: '"getYtbToken" failed'
  3892. });
  3893. return false;
  3894. }
  3895. if (!doTask && !verify && this.whiteList.channels.includes(channelId)) {
  3896. scripts_echoLog({
  3897. type: 'whiteList',
  3898. text: 'Youtube.unfollowChannel',
  3899. id: channelId
  3900. });
  3901. return true;
  3902. }
  3903. const logStatus = verify ? scripts_echoLog({
  3904. text: i18n('verifyingAuth', 'Youtube')
  3905. }) : scripts_echoLog({
  3906. type: doTask ? 'followingYtbChannel' : 'unfollowingYtbChannel',
  3907. text: channelId
  3908. });
  3909. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  3910. const {
  3911. result,
  3912. statusText,
  3913. status,
  3914. data
  3915. } = await tools_httpRequest({
  3916. url: `https://www.youtube.com/youtubei/v1/subscription/${doTask ? '' : 'un'}subscribe?key=${apiKey}&prettyPrint=false`,
  3917. method: 'POST',
  3918. headers: {
  3919. origin: 'https://www.youtube.com',
  3920. referer: `https://www.youtube.com/channel/${channelId}`,
  3921. 'content-type': 'application/json',
  3922. 'x-goog-authuser': '0',
  3923. 'x-goog-visitor-id': client?.visitorData,
  3924. 'x-origin': 'https://www.youtube.com',
  3925. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  3926. },
  3927. data: JSON.stringify({
  3928. context: {
  3929. client: client,
  3930. request: {
  3931. sessionId: request?.sessionId,
  3932. internalExperimentFlags: [],
  3933. consistencyTokenJars: []
  3934. },
  3935. user: {}
  3936. },
  3937. channelIds: [ channelId ],
  3938. params: doTask ? 'EgIIAhgA' : 'CgIIAhgA'
  3939. })
  3940. });
  3941. if (result === 'Success') {
  3942. if (data?.status === 200) {
  3943. if (doTask && (/"subscribed":true/.test(data.responseText) || data.responseText.includes('The subscription already exists')) || !doTask && /"subscribed":false/.test(data.responseText)) {
  3944. logStatus.success();
  3945. if (doTask && !verify) {
  3946. this.tasks.channels = unique([ ...this.tasks.channels, link ]);
  3947. }
  3948. return true;
  3949. }
  3950. if (verify && data.responseText.includes('You may not subscribe to yourself')) {
  3951. logStatus.success();
  3952. return true;
  3953. }
  3954. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  3955. return false;
  3956. }
  3957. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3958. return false;
  3959. }
  3960. logStatus.error(`${result}:${statusText}(${status})`);
  3961. return false;
  3962. } catch (error) {
  3963. throwError(error, 'Youtube.toggleChannel');
  3964. return false;
  3965. }
  3966. }
  3967. async #toggleLikeVideo({
  3968. link,
  3969. doTask = true
  3970. }) {
  3971. try {
  3972. const {
  3973. params,
  3974. needLogin
  3975. } = await this.#getInfo(link, 'likeVideo');
  3976. const {
  3977. apiKey,
  3978. client,
  3979. request,
  3980. videoId,
  3981. likeParams
  3982. } = params || {};
  3983. if (needLogin) {
  3984. scripts_echoLog({
  3985. html: `${i18n('loginYtb')}`
  3986. });
  3987. return false;
  3988. }
  3989. if (!(apiKey && client && request && videoId && likeParams)) {
  3990. scripts_echoLog({
  3991. text: '"getYtbToken" failed'
  3992. });
  3993. return false;
  3994. }
  3995. if (!doTask && this.whiteList.likes.includes(videoId)) {
  3996. scripts_echoLog({
  3997. type: 'whiteList',
  3998. text: 'Youtube.unlikeVideo',
  3999. id: videoId
  4000. });
  4001. return true;
  4002. }
  4003. const logStatus = scripts_echoLog({
  4004. type: doTask ? 'likingYtbVideo' : 'unlikingYtbVideo',
  4005. text: videoId
  4006. });
  4007. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  4008. const likeVideoData = {
  4009. context: {
  4010. client: client,
  4011. request: {
  4012. sessionId: request.sessionId,
  4013. internalExperimentFlags: [],
  4014. consistencyTokenJars: []
  4015. },
  4016. user: {}
  4017. },
  4018. target: {
  4019. videoId: videoId
  4020. }
  4021. };
  4022. if (doTask) {
  4023. if (likeParams) {
  4024. likeVideoData.params = likeParams;
  4025. } else {
  4026. logStatus.error('Empty likeParams');
  4027. return false;
  4028. }
  4029. }
  4030. const {
  4031. result,
  4032. statusText,
  4033. status,
  4034. data
  4035. } = await tools_httpRequest({
  4036. url: `https://www.youtube.com/youtubei/v1/like/${doTask ? '' : 'remove'}like?key=${apiKey}`,
  4037. method: 'POST',
  4038. headers: {
  4039. origin: 'https://www.youtube.com',
  4040. referer: `https://www.youtube.com/watch?v=${videoId}`,
  4041. 'content-type': 'application/json',
  4042. 'x-goog-authuser': '0',
  4043. 'x-goog-visitor-id': client.visitorData,
  4044. 'x-origin': 'https://www.youtube.com',
  4045. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  4046. },
  4047. data: JSON.stringify(likeVideoData)
  4048. });
  4049. if (result === 'Success') {
  4050. if (data?.status === 200) {
  4051. if (doTask && data.responseText.includes('Added to Liked videos') || !doTask && (data.responseText.includes('Removed from Liked videos') || data.responseText.includes('Dislike removed'))) {
  4052. logStatus.success();
  4053. if (doTask) {
  4054. this.tasks.likes = unique([ ...this.tasks.likes, link ]);
  4055. }
  4056. return true;
  4057. }
  4058. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4059. return false;
  4060. }
  4061. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4062. return false;
  4063. }
  4064. logStatus.error(`${result}:${statusText}(${status})`);
  4065. return false;
  4066. } catch (error) {
  4067. throwError(error, 'Youtube.toggleLikeVideo');
  4068. return false;
  4069. }
  4070. }
  4071. async toggle({
  4072. doTask = true,
  4073. channelLinks = [],
  4074. videoLinks = []
  4075. }) {
  4076. try {
  4077. if (!this.#initialized) {
  4078. scripts_echoLog({
  4079. text: i18n('needInit')
  4080. });
  4081. return false;
  4082. }
  4083. const prom = [];
  4084. if (doTask && !globalOptions.doTask.youtube.channels || !doTask && !globalOptions.undoTask.youtube.channels) {
  4085. scripts_echoLog({
  4086. type: 'globalOptionsSkip',
  4087. text: 'youtube.channels'
  4088. });
  4089. } else {
  4090. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => {
  4091. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4092. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4093. }
  4094. return link;
  4095. });
  4096. if (realChannels.length > 0) {
  4097. for (const channel of realChannels) {
  4098. prom.push(this.#toggleChannel({
  4099. link: channel,
  4100. doTask: doTask
  4101. }));
  4102. await delay(1e3);
  4103. }
  4104. }
  4105. }
  4106. if (doTask && !globalOptions.doTask.youtube.likes || !doTask && !globalOptions.undoTask.youtube.likes) {
  4107. scripts_echoLog({
  4108. type: 'globalOptionsSkip',
  4109. text: 'youtube.likes'
  4110. });
  4111. } else {
  4112. const realLikes = this.getRealParams('likes', videoLinks, doTask, link => {
  4113. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4114. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4115. }
  4116. return link;
  4117. });
  4118. if (realLikes.length > 0) {
  4119. for (const video of realLikes) {
  4120. prom.push(this.#toggleLikeVideo({
  4121. link: video,
  4122. doTask: doTask
  4123. }));
  4124. await delay(1e3);
  4125. }
  4126. }
  4127. }
  4128. return Promise.all(prom).then(() => true);
  4129. } catch (error) {
  4130. throwError(error, 'Youtube.toggle');
  4131. return false;
  4132. }
  4133. }
  4134. }
  4135. class SteamASF {
  4136. #asfOptions;
  4137. #botName = 'asf';
  4138. #groupInfo;
  4139. async init() {
  4140. try {
  4141. const asfCommandsUrl = new URL('/Api/Command/', globalOptions.ASF.AsfIpcUrl);
  4142. this.#asfOptions = {
  4143. url: asfCommandsUrl.href,
  4144. method: 'POST',
  4145. responseType: 'json',
  4146. headers: {
  4147. accept: 'application/json',
  4148. 'Content-Type': 'application/json',
  4149. Host: asfCommandsUrl.host,
  4150. Origin: asfCommandsUrl.origin,
  4151. Referer: asfCommandsUrl.href,
  4152. Authentication: globalOptions.ASF.AsfIpcPassword
  4153. }
  4154. };
  4155. if (globalOptions.ASF.AsfBotname) {
  4156. this.#botName = globalOptions.ASF.AsfBotname;
  4157. }
  4158. const logStatus = scripts_echoLog({
  4159. text: i18n('initingASF')
  4160. });
  4161. const {
  4162. result,
  4163. statusText,
  4164. status,
  4165. data
  4166. } = await tools_httpRequest({
  4167. ...this.#asfOptions,
  4168. data: '{"Command":"!stats"}'
  4169. });
  4170. if (result === 'Success') {
  4171. if (data?.response?.Success === true && data.response.Message === 'OK' && data.response.Result) {
  4172. logStatus.success();
  4173. return true;
  4174. }
  4175. if (data?.response?.Result || data?.response?.Message) {
  4176. logStatus.error(data?.response?.Result || data.response.Message);
  4177. return false;
  4178. }
  4179. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4180. return false;
  4181. }
  4182. logStatus.error(`${result}:${statusText}(${status})`);
  4183. return false;
  4184. } catch (error) {
  4185. throwError(error, 'SteamASF.init');
  4186. return false;
  4187. }
  4188. }
  4189. async joinGroup(groupName) {
  4190. try {
  4191. const logStatus = scripts_echoLog({
  4192. type: 'joiningSteamGroup',
  4193. text: groupName
  4194. });
  4195. const {
  4196. result,
  4197. statusText,
  4198. status,
  4199. data
  4200. } = await tools_httpRequest({
  4201. ...this.#asfOptions,
  4202. data: JSON.stringify({
  4203. Command: `!JOINGROUP ${this.#botName} ${groupName}`
  4204. })
  4205. });
  4206. if (result === 'Success') {
  4207. if (data?.status === 200 && [ '已加入', '已申请', 'Joined', 'Applied', 'Присоединился', 'costs' ].find(text => data.response?.Result?.includes(text))) {
  4208. logStatus.success();
  4209. return true;
  4210. }
  4211. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4212. return false;
  4213. }
  4214. logStatus.error(`${result}:${statusText}(${status})`);
  4215. return false;
  4216. } catch (error) {
  4217. throwError(error, 'SteamASF.joinGroup');
  4218. return false;
  4219. }
  4220. }
  4221. async leaveGroup(groupName) {
  4222. try {
  4223. if (!this.#groupInfo) {
  4224. if (!await this.#getGroupId()) {
  4225. return false;
  4226. }
  4227. }
  4228. const groupId = await this.#groupInfo[groupName];
  4229. if (!groupId) {
  4230. return false;
  4231. }
  4232. const logStatus = scripts_echoLog({
  4233. type: 'leavingSteamGroup',
  4234. text: groupName
  4235. });
  4236. const {
  4237. result,
  4238. statusText,
  4239. status,
  4240. data
  4241. } = await tools_httpRequest({
  4242. ...this.#asfOptions,
  4243. data: JSON.stringify({
  4244. Command: `!LEAVEGROUP ${this.#botName} ${groupId}`
  4245. })
  4246. });
  4247. if (result === 'Success') {
  4248. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4249. logStatus.success();
  4250. return true;
  4251. }
  4252. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4253. return false;
  4254. }
  4255. logStatus.error(`${result}:${statusText}(${status})`);
  4256. return false;
  4257. } catch (error) {
  4258. throwError(error, 'SteamASF.leaveGroup');
  4259. return false;
  4260. }
  4261. }
  4262. async #getGroupId() {
  4263. try {
  4264. const logStatus = scripts_echoLog({
  4265. type: 'gettingSteamGroupId',
  4266. text: 'All'
  4267. });
  4268. const {
  4269. result,
  4270. statusText,
  4271. status,
  4272. data
  4273. } = await tools_httpRequest({
  4274. ...this.#asfOptions,
  4275. data: JSON.stringify({
  4276. Command: `!GROUPLIST ${this.#botName}`
  4277. })
  4278. });
  4279. if (result === 'Success') {
  4280. if (data?.status === 200 && data.response?.Result?.includes('|')) {
  4281. this.#groupInfo = Object.fromEntries(data.response.Result.split('\n').map(line => {
  4282. const [ , name, id ] = line.trim().split('|');
  4283. if (name && id) {
  4284. return [ name, id ];
  4285. }
  4286. return null;
  4287. }).filter(ele => ele));
  4288. logStatus.success();
  4289. return true;
  4290. }
  4291. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4292. return false;
  4293. }
  4294. logStatus.error(`${result}:${statusText}(${status})`);
  4295. return false;
  4296. } catch (error) {
  4297. throwError(error, 'SteamASF.getGroupID');
  4298. return false;
  4299. }
  4300. }
  4301. async addToWishlist(gameId) {
  4302. try {
  4303. const logStatus = scripts_echoLog({
  4304. type: 'addingToWishlist',
  4305. text: gameId
  4306. });
  4307. if ((await this.#checkGame(gameId)).wishlist === true) {
  4308. logStatus.success();
  4309. return true;
  4310. }
  4311. const {
  4312. result,
  4313. statusText,
  4314. status,
  4315. data
  4316. } = await tools_httpRequest({
  4317. ...this.#asfOptions,
  4318. data: JSON.stringify({
  4319. Command: `!ADDWISHLIST ${this.#botName} ${gameId}`
  4320. })
  4321. });
  4322. if (result === 'Success') {
  4323. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4324. logStatus.success();
  4325. return true;
  4326. }
  4327. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4328. return false;
  4329. }
  4330. logStatus.error(`${result}:${statusText}(${status})`);
  4331. return false;
  4332. } catch (error) {
  4333. throwError(error, 'SteamASF.addToWishlist');
  4334. return false;
  4335. }
  4336. }
  4337. async removeFromWishlist(gameId) {
  4338. try {
  4339. const logStatus = scripts_echoLog({
  4340. type: 'removingFromWishlist',
  4341. text: gameId
  4342. });
  4343. if ((await this.#checkGame(gameId)).wishlist === false) {
  4344. logStatus.success();
  4345. return true;
  4346. }
  4347. const {
  4348. result,
  4349. statusText,
  4350. status,
  4351. data
  4352. } = await tools_httpRequest({
  4353. ...this.#asfOptions,
  4354. data: JSON.stringify({
  4355. Command: `!REMOVEWISHLIST ${this.#botName} ${gameId}`
  4356. })
  4357. });
  4358. if (result === 'Success') {
  4359. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4360. logStatus.success();
  4361. return true;
  4362. }
  4363. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4364. return false;
  4365. }
  4366. logStatus.error(`${result}:${statusText}(${status})`);
  4367. return false;
  4368. } catch (error) {
  4369. throwError(error, 'SteamASF.removeFromWishlist');
  4370. return false;
  4371. }
  4372. }
  4373. async toggleFollowGame(gameId, doTask) {
  4374. try {
  4375. const logStatus = scripts_echoLog({
  4376. type: `${doTask ? '' : 'un'}followingGame`,
  4377. text: gameId
  4378. });
  4379. if (doTask && (await this.#checkGame(gameId)).followed === true || !doTask && (await this.#checkGame(gameId)).followed === false) {
  4380. logStatus.success();
  4381. return true;
  4382. }
  4383. const {
  4384. result,
  4385. statusText,
  4386. status,
  4387. data
  4388. } = await tools_httpRequest({
  4389. ...this.#asfOptions,
  4390. data: JSON.stringify({
  4391. Command: `!${doTask ? '' : 'UN'}FOLLOWGAME ${this.#botName} ${gameId}`
  4392. })
  4393. });
  4394. if (result === 'Success') {
  4395. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4396. logStatus.success();
  4397. return true;
  4398. }
  4399. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4400. return false;
  4401. }
  4402. logStatus.error(`${result}:${statusText}(${status})`);
  4403. return false;
  4404. } catch (error) {
  4405. throwError(error, 'SteamASF.toggleFollowGame');
  4406. return false;
  4407. }
  4408. }
  4409. async #checkGame(gameId) {
  4410. try {
  4411. const {
  4412. result,
  4413. data
  4414. } = await tools_httpRequest({
  4415. ...this.#asfOptions,
  4416. data: JSON.stringify({
  4417. Command: `!CHECK ${this.#botName} ${gameId}`
  4418. })
  4419. });
  4420. if (result === 'Success') {
  4421. if (data?.status === 200 && data.response?.Result?.includes(gameId)) {
  4422. const matchedResult = data.response.Result.split('\n').find(result => result.includes(gameId))?.split('|');
  4423. if (matchedResult?.length > 3) {
  4424. return {
  4425. wishlist: matchedResult.at(-3).trim() === '√' || matchedResult.at(-2).trim() === '√',
  4426. followed: matchedResult.at(-1).trim() === '√'
  4427. };
  4428. }
  4429. return {};
  4430. }
  4431. return {};
  4432. }
  4433. return {};
  4434. } catch (error) {
  4435. throwError(error, 'SteamASF.checkGame');
  4436. return {};
  4437. }
  4438. }
  4439. async toggleCurator(curatorId, doTask = true) {
  4440. try {
  4441. const logStatus = scripts_echoLog({
  4442. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  4443. text: curatorId
  4444. });
  4445. const {
  4446. result,
  4447. statusText,
  4448. status,
  4449. data
  4450. } = await tools_httpRequest({
  4451. ...this.#asfOptions,
  4452. data: JSON.stringify({
  4453. Command: `!${doTask ? '' : 'UN'}FOLLOWCURATOR ${this.#botName} ${curatorId}`
  4454. })
  4455. });
  4456. if (result === 'Success') {
  4457. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4458. logStatus.success();
  4459. return true;
  4460. }
  4461. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4462. return false;
  4463. }
  4464. logStatus.error(`${result}:${statusText}(${status})`);
  4465. return false;
  4466. } catch (error) {
  4467. throwError(error, 'Steam.toggleCurator');
  4468. return false;
  4469. }
  4470. }
  4471. async addLicense(id) {
  4472. try {
  4473. const [ type, ids ] = id.split('-');
  4474. if (type === 'appid') {
  4475. const logStatus = scripts_echoLog({
  4476. type: 'addingFreeLicense',
  4477. text: ids
  4478. });
  4479. const {
  4480. result,
  4481. statusText,
  4482. status,
  4483. data
  4484. } = await tools_httpRequest({
  4485. ...this.#asfOptions,
  4486. data: JSON.stringify({
  4487. Command: `!addlicense ${this.#botName} app/${ids}`
  4488. })
  4489. });
  4490. if (result === 'Success') {
  4491. if (data?.status === 200 && [ 'AlreadyPurchased', 'OK' ].find(text => data.response?.Result?.includes(text))) {
  4492. logStatus.success();
  4493. return true;
  4494. }
  4495. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4496. return false;
  4497. }
  4498. logStatus.error(`${result}:${statusText}(${status})`);
  4499. return false;
  4500. } else if (type === 'subid') {
  4501. const idsArr = ids.split(',');
  4502. const logStatus = scripts_echoLog({
  4503. type: 'addingFreeLicenseSubid',
  4504. text: ids
  4505. });
  4506. const {
  4507. result,
  4508. statusText,
  4509. status,
  4510. data
  4511. } = await tools_httpRequest({
  4512. ...this.#asfOptions,
  4513. data: JSON.stringify({
  4514. Command: `!addlicense ${this.#botName} ${idsArr.map(id => `sub/${id}`).join(',')}`
  4515. })
  4516. });
  4517. if (result === 'Success') {
  4518. if (data?.status === 200 && data.response?.Result) {
  4519. const resultLines = data.response.Result.split('\n');
  4520. idsArr.forEach(subid => {
  4521. const targetLine = resultLines.find(text => text.includes(subid));
  4522. if (targetLine && [ '成功', 'Success', 'Успех' ].find(text => targetLine.includes(text))) {
  4523. scripts_echoLog({}).success(targetLine);
  4524. } else {
  4525. scripts_echoLog({}).error(targetLine);
  4526. }
  4527. });
  4528. return true;
  4529. }
  4530. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4531. return false;
  4532. }
  4533. logStatus.error(`${result}:${statusText}(${status})`);
  4534. return false;
  4535. }
  4536. return false;
  4537. } catch (error) {
  4538. throwError(error, 'SteamASF.addLicense');
  4539. return false;
  4540. }
  4541. }
  4542. async requestPlayTestAccess(id) {
  4543. try {
  4544. const logStatus = scripts_echoLog({
  4545. type: 'requestingPlayTestAccess',
  4546. text: id
  4547. });
  4548. const {
  4549. result,
  4550. statusText,
  4551. status,
  4552. data
  4553. } = await tools_httpRequest({
  4554. ...this.#asfOptions,
  4555. data: JSON.stringify({
  4556. Command: `!REQUESTACCESS ${this.#botName} ${id}`
  4557. })
  4558. });
  4559. if (result === 'Success') {
  4560. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4561. logStatus.success();
  4562. return true;
  4563. }
  4564. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4565. return false;
  4566. }
  4567. logStatus.error(`${result}:${statusText}(${status})`);
  4568. return false;
  4569. } catch (error) {
  4570. throwError(error, 'Steam.requestPlayTestAccess');
  4571. return false;
  4572. }
  4573. }
  4574. }
  4575. const social_SteamASF = SteamASF;
  4576. class Steam extends social_Social {
  4577. tasks;
  4578. whiteList;
  4579. #cache = {
  4580. ...{
  4581. group: {},
  4582. officialGroup: {},
  4583. forum: {},
  4584. workshop: {},
  4585. curator: {}
  4586. },
  4587. ...GM_getValue('steamCache')
  4588. };
  4589. #auth = {};
  4590. #storeInitialized = false;
  4591. #communityInitialized = false;
  4592. #area = 'CN';
  4593. #oldArea;
  4594. #areaStatus = 'end';
  4595. #ASF;
  4596. constructor() {
  4597. super();
  4598. const defaultTasksTemplate = {
  4599. groups: [],
  4600. officialGroups: [],
  4601. wishlists: [],
  4602. follows: [],
  4603. forums: [],
  4604. workshops: [],
  4605. workshopVotes: [],
  4606. curators: [],
  4607. curatorLikes: [],
  4608. announcements: [],
  4609. licenses: [],
  4610. playtests: []
  4611. };
  4612. this.tasks = defaultTasksTemplate;
  4613. this.whiteList = {
  4614. ...defaultTasksTemplate,
  4615. ...GM_getValue('whiteList')?.steam || {}
  4616. };
  4617. }
  4618. async init(type = 'all') {
  4619. try {
  4620. if (globalOptions.ASF.AsfEnabled && globalOptions.ASF.AsfIpcUrl && globalOptions.ASF.AsfIpcPassword) {
  4621. this.#ASF = new social_SteamASF();
  4622. if (await this.#ASF.init()) {
  4623. this.#storeInitialized = true;
  4624. this.#communityInitialized = true;
  4625. return true;
  4626. }
  4627. return false;
  4628. }
  4629. if (type === 'store') {
  4630. if (this.#storeInitialized) {
  4631. return true;
  4632. }
  4633. let storeInitialized = await this.#updateStoreAuth();
  4634. if (!storeInitialized) {
  4635. storeInitialized = await this.#updateStoreAuthTab();
  4636. }
  4637. this.#storeInitialized = storeInitialized;
  4638. if (!this.#storeInitialized) {
  4639. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4640. return false;
  4641. }
  4642. scripts_echoLog({}).success(i18n('initSuccess', 'SteamStore'));
  4643. return true;
  4644. }
  4645. if (type === 'community') {
  4646. if (this.#communityInitialized) {
  4647. return true;
  4648. }
  4649. let communityInitialized = await this.#updateCommunityAuth();
  4650. if (!communityInitialized) {
  4651. communityInitialized = await this.#updateCommunityAuthTab();
  4652. GM_setValue('steamCommunityAuth', null);
  4653. }
  4654. this.#communityInitialized = communityInitialized;
  4655. if (!this.#communityInitialized) {
  4656. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4657. return false;
  4658. }
  4659. scripts_echoLog({}).success(i18n('initSuccess', 'SteamCommunity'));
  4660. return true;
  4661. }
  4662. if (this.#storeInitialized && this.#communityInitialized) {
  4663. scripts_echoLog({}).success(i18n('initSuccess', 'Steam'));
  4664. return true;
  4665. }
  4666. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4667. return false;
  4668. } catch (error) {
  4669. throwError(error, 'Steam.init');
  4670. return false;
  4671. }
  4672. }
  4673. async #refreshToken(type = 'steamStore') {
  4674. try {
  4675. const host = {
  4676. steamStore: 'store.steampowered.com',
  4677. steamCommunity: 'steamcommunity.com'
  4678. };
  4679. const logStatus = scripts_echoLog({
  4680. text: i18n('refreshingToken', i18n(type))
  4681. });
  4682. const formData = new FormData();
  4683. formData.append('redir', `https://${host[type]}/`);
  4684. const {
  4685. result,
  4686. statusText,
  4687. status,
  4688. data
  4689. } = await tools_httpRequest({
  4690. url: 'https://login.steampowered.com/jwt/ajaxrefresh',
  4691. method: 'POST',
  4692. responseType: 'json',
  4693. headers: {
  4694. Host: 'login.steampowered.com',
  4695. Origin: `https://${host[type]}`,
  4696. Referer: `https://${host[type]}/`
  4697. },
  4698. data: formData
  4699. });
  4700. if (result === 'Success') {
  4701. if (data?.response?.success) {
  4702. if (await this.#setStoreToken(data.response, type)) {
  4703. logStatus.success();
  4704. return true;
  4705. }
  4706. logStatus.error('Error');
  4707. return false;
  4708. }
  4709. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4710. return false;
  4711. }
  4712. logStatus.error(`${result}:${statusText}(${status})`);
  4713. return false;
  4714. } catch (error) {
  4715. throwError(error, 'Steam.refreshToken');
  4716. return false;
  4717. }
  4718. }
  4719. async #setStoreToken(param, type) {
  4720. try {
  4721. const host = {
  4722. steamStore: 'store.steampowered.com',
  4723. steamCommunity: 'steamcommunity.com'
  4724. };
  4725. const logStatus = scripts_echoLog({
  4726. text: i18n('settingToken', i18n(type))
  4727. });
  4728. const formData = new FormData();
  4729. formData.append('steamID', param.steamID);
  4730. formData.append('nonce', param.nonce);
  4731. formData.append('redir', param.redir);
  4732. formData.append('auth', param.auth);
  4733. const {
  4734. result,
  4735. statusText,
  4736. status,
  4737. data
  4738. } = await tools_httpRequest({
  4739. url: `https://${host[type]}/login/settoken`,
  4740. method: 'POST',
  4741. headers: {
  4742. Accept: 'application/json, text/plain, */*',
  4743. Host: host[type],
  4744. Origin: `https://${host[type]}`
  4745. },
  4746. data: formData
  4747. });
  4748. if (result === 'Success') {
  4749. if (data?.status === 200) {
  4750. logStatus.success();
  4751. return true;
  4752. }
  4753. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4754. return false;
  4755. }
  4756. logStatus.error(`${result}:${statusText}(${status})`);
  4757. return false;
  4758. } catch (error) {
  4759. throwError(error, 'Steam.setStoreToken');
  4760. return false;
  4761. }
  4762. }
  4763. async #updateStoreAuth(retry = false) {
  4764. try {
  4765. const logStatus = scripts_echoLog({
  4766. text: i18n('updatingAuth', i18n('steamStore'))
  4767. });
  4768. const {
  4769. result,
  4770. statusText,
  4771. status,
  4772. data
  4773. } = await tools_httpRequest({
  4774. url: 'https://store.steampowered.com/',
  4775. method: 'GET',
  4776. headers: {
  4777. 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',
  4778. 'Sec-Fetch-Dest': 'document',
  4779. 'Sec-Fetch-Mode': 'navigate',
  4780. 'Upgrade-Insecure-Requests': '1'
  4781. },
  4782. fetch: false,
  4783. redirect: 'manual'
  4784. });
  4785. if (data?.status === 200) {
  4786. if (!data.responseText.includes('data-miniprofile=')) {
  4787. if (await this.#refreshToken('steamStore')) {
  4788. logStatus.warning(i18n('retry'));
  4789. if (retry) {
  4790. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4791. return false;
  4792. }
  4793. return this.#updateStoreAuth(true);
  4794. }
  4795. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4796. return false;
  4797. }
  4798. const storeSessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  4799. if (storeSessionID) {
  4800. this.#auth.storeSessionID = storeSessionID;
  4801. logStatus.success();
  4802. return true;
  4803. }
  4804. logStatus.error('Error: Get "sessionID" failed');
  4805. return false;
  4806. }
  4807. if ([ 301, 302 ].includes(data?.status)) {
  4808. if (await this.#refreshToken('steamStore')) {
  4809. logStatus.warning(i18n('retry'));
  4810. if (retry) {
  4811. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4812. return false;
  4813. }
  4814. return this.#updateStoreAuth(true);
  4815. }
  4816. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4817. return false;
  4818. }
  4819. logStatus.error(`${result}:${statusText}(${status})`);
  4820. return false;
  4821. } catch (error) {
  4822. throwError(error, 'Steam.updateStoreAuth');
  4823. return false;
  4824. }
  4825. }
  4826. async #updateStoreAuthTab() {
  4827. try {
  4828. const logStatus = scripts_echoLog({
  4829. text: i18n('updatingAuth', i18n('steamStoreTab'))
  4830. });
  4831. return await new Promise(resolve => {
  4832. GM_deleteValue('steamStoreAuth');
  4833. GM_setValue('ATv4_updateStoreAuth', true);
  4834. const newTab = GM_openInTab('https://store.steampowered.com/', {
  4835. active: true,
  4836. setParent: true
  4837. });
  4838. newTab.name = 'ATv4_updateStoreAuth';
  4839. const listenerId = GM_addValueChangeListener('steamStoreAuth', (key, oldValue, newValue) => {
  4840. GM_removeValueChangeListener(listenerId);
  4841. GM_deleteValue('ATv4_updateStoreAuth');
  4842. newTab?.close();
  4843. window.focus();
  4844. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  4845. this.#auth.storeSessionID = newValue.storeSessionID;
  4846. logStatus.success();
  4847. resolve(true);
  4848. return;
  4849. }
  4850. logStatus.error('Failed');
  4851. resolve(false);
  4852. });
  4853. newTab.onclose = () => {
  4854. GM_deleteValue('ATv4_updateStoreAuth');
  4855. };
  4856. });
  4857. } catch (error) {
  4858. throwError(error, 'Steam.updateStoreAuthTab');
  4859. return false;
  4860. }
  4861. }
  4862. async #updateCommunityAuthTab() {
  4863. try {
  4864. const logStatus = scripts_echoLog({
  4865. text: i18n('updatingAuth', i18n('steamCommunityTab'))
  4866. });
  4867. return await new Promise(resolve => {
  4868. GM_deleteValue('steamCommunityAuth');
  4869. GM_setValue('ATv4_updateCommunityAuth', true);
  4870. const newTab = GM_openInTab('https://steamcommunity.com/my', {
  4871. active: true,
  4872. setParent: true
  4873. });
  4874. newTab.name = 'ATv4_updateCommunityAuth';
  4875. const listenerId = GM_addValueChangeListener('steamCommunityAuth', (key, oldValue, newValue) => {
  4876. GM_removeValueChangeListener(listenerId);
  4877. GM_deleteValue('ATv4_updateCommunityAuth');
  4878. newTab?.close();
  4879. window.focus();
  4880. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  4881. this.#auth.steam64Id = newValue.steam64Id;
  4882. this.#auth.communitySessionID = newValue.communitySessionID;
  4883. logStatus.success();
  4884. resolve(true);
  4885. return;
  4886. }
  4887. logStatus.error('Failed');
  4888. resolve(false);
  4889. });
  4890. newTab.onclose = () => {
  4891. GM_deleteValue('ATv4_updateCommunityAuth');
  4892. };
  4893. });
  4894. } catch (error) {
  4895. throwError(error, 'Steam.updateCommunityAuthTab');
  4896. return false;
  4897. }
  4898. }
  4899. async #updateCommunityAuth() {
  4900. try {
  4901. const logStatus = scripts_echoLog({
  4902. text: i18n('gettingUserLink')
  4903. });
  4904. const {
  4905. result,
  4906. statusText,
  4907. status,
  4908. data
  4909. } = await tools_httpRequest({
  4910. url: 'https://steamcommunity.com/my',
  4911. method: 'GET',
  4912. headers: {
  4913. 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',
  4914. Host: 'steamcommunity.com',
  4915. 'Sec-Fetch-Dest': 'document',
  4916. 'Sec-Fetch-Mode': 'navigate'
  4917. },
  4918. fetch: false
  4919. });
  4920. if (data?.status === 200) {
  4921. if (data.finalUrl.includes('https://steamcommunity.com/login/home')) {
  4922. logStatus.error(`Error:${i18n('needLoginSteamCommunity')}`, true);
  4923. return false;
  4924. }
  4925. const steam64Id = data.responseText.match(/g_steamID = "(.+?)";/)?.[1];
  4926. const communitySessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  4927. if (steam64Id && communitySessionID) {
  4928. this.#auth.steam64Id = steam64Id;
  4929. this.#auth.communitySessionID = communitySessionID;
  4930. logStatus.success();
  4931. return true;
  4932. }
  4933. logStatus.error('Error: Get "sessionID" failed');
  4934. return false;
  4935. }
  4936. logStatus.error(`${result}:${statusText}(${status})`);
  4937. return false;
  4938. } catch (error) {
  4939. throwError(error, 'Steam.updateCommunityAuth');
  4940. return false;
  4941. }
  4942. }
  4943. async #getAreaInfo() {
  4944. try {
  4945. const logStatus = scripts_echoLog({
  4946. text: i18n('gettingAreaInfo')
  4947. });
  4948. const {
  4949. result,
  4950. statusText,
  4951. status,
  4952. data
  4953. } = await tools_httpRequest({
  4954. url: 'https://store.steampowered.com/cart/',
  4955. method: 'GET'
  4956. });
  4957. if (result === 'Success') {
  4958. if (data?.status === 200) {
  4959. const cartConfigRaw = data.responseText.match(/data-cart_config="(.*?)"/)?.[1];
  4960. const temp = document.createElement('div');
  4961. temp.innerHTML = cartConfigRaw || '{}';
  4962. const cartConfigStr = temp.textContent || temp.innerText;
  4963. let cartConfig;
  4964. try {
  4965. cartConfig = JSON.parse(cartConfigStr);
  4966. } catch (error) {
  4967. logStatus.error('Error: get country info filed');
  4968. console.error(error);
  4969. return {};
  4970. }
  4971. if (!cartConfig.rgUserCountryOptions) {
  4972. logStatus.warning('Warning: Area cannot be changed');
  4973. return {};
  4974. }
  4975. const userInfoRaw = data.responseText.match(/data-userinfo="(.*?)"/)?.[1];
  4976. const temp1 = document.createElement('div');
  4977. temp1.innerHTML = userInfoRaw || '{}';
  4978. const userInfoStr = temp1.textContent || temp1.innerText;
  4979. let userInfo;
  4980. try {
  4981. userInfo = JSON.parse(userInfoStr);
  4982. } catch (error) {
  4983. logStatus.error('Error: get country info filed');
  4984. console.error(error);
  4985. return {};
  4986. }
  4987. const currentArea = userInfo.country_code;
  4988. const areas = Object.keys(cartConfig.rgUserCountryOptions).filter(area => area !== 'help');
  4989. if (currentArea && areas.length > 0) {
  4990. this.#area = currentArea;
  4991. logStatus.success();
  4992. return {
  4993. currentArea: currentArea,
  4994. areas: areas
  4995. };
  4996. }
  4997. logStatus.error('Error: get country info filed');
  4998. return {};
  4999. }
  5000. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5001. return {};
  5002. }
  5003. logStatus.error(`${result}:${statusText}(${status})`);
  5004. return {};
  5005. } catch (error) {
  5006. throwError(error, 'Steam.getAreaInfo');
  5007. return {};
  5008. }
  5009. }
  5010. async #changeArea(area) {
  5011. try {
  5012. if (this.#areaStatus === 'waiting') {
  5013. await new Promise(resolve => {
  5014. const checker = setInterval(() => {
  5015. if (this.#areaStatus !== 'waiting') {
  5016. clearInterval(checker);
  5017. resolve(true);
  5018. }
  5019. });
  5020. });
  5021. }
  5022. if (this.#area === area || !area && this.#area !== 'CN') {
  5023. return true;
  5024. }
  5025. this.#areaStatus = 'waiting';
  5026. let aimedArea = area;
  5027. if (!aimedArea) {
  5028. const {
  5029. currentArea,
  5030. areas
  5031. } = await this.#getAreaInfo();
  5032. if (!currentArea || !areas) {
  5033. this.#areaStatus = 'error';
  5034. return false;
  5035. }
  5036. if (currentArea !== 'CN') {
  5037. this.#areaStatus = 'skip';
  5038. scripts_echoLog({
  5039. text: 'notNeededChangeArea'
  5040. });
  5041. return 'skip';
  5042. }
  5043. const anotherArea = areas.filter(area => area && area !== 'CN');
  5044. if (!anotherArea || anotherArea.length === 0) {
  5045. this.#areaStatus = 'noAnotherArea';
  5046. scripts_echoLog({
  5047. text: 'noAnotherArea'
  5048. });
  5049. return false;
  5050. }
  5051. [ aimedArea ] = anotherArea;
  5052. }
  5053. const logStatus = scripts_echoLog({
  5054. text: i18n('changingArea', aimedArea)
  5055. });
  5056. const {
  5057. result,
  5058. statusText,
  5059. status,
  5060. data
  5061. } = await tools_httpRequest({
  5062. url: 'https://store.steampowered.com/country/setcountry',
  5063. method: 'POST',
  5064. headers: {
  5065. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5066. },
  5067. data: $.param({
  5068. cc: aimedArea,
  5069. sessionid: this.#auth.storeSessionID
  5070. })
  5071. });
  5072. if (result === 'Success') {
  5073. if (data?.status === 200 && data.responseText === 'true') {
  5074. const {
  5075. currentArea
  5076. } = await this.#getAreaInfo();
  5077. if (currentArea) {
  5078. this.#area = currentArea;
  5079. if (!this.#oldArea) {
  5080. this.#oldArea = currentArea;
  5081. }
  5082. }
  5083. if (currentArea === aimedArea) {
  5084. this.#areaStatus = 'success';
  5085. logStatus.success();
  5086. return currentArea;
  5087. }
  5088. this.#areaStatus = 'error';
  5089. logStatus.error('Error: change country filed');
  5090. return 'CN';
  5091. }
  5092. this.#areaStatus = 'error';
  5093. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5094. return 'CN';
  5095. }
  5096. this.#areaStatus = 'error';
  5097. logStatus.error(`${result}:${statusText}(${status})`);
  5098. return 'CN';
  5099. } catch (error) {
  5100. this.#areaStatus = 'error';
  5101. throwError(error, 'Steam.changeArea');
  5102. return false;
  5103. }
  5104. }
  5105. async #joinGroup(groupName) {
  5106. try {
  5107. if (this.#ASF) {
  5108. if (await this.#ASF.joinGroup(groupName)) {
  5109. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5110. return true;
  5111. }
  5112. return false;
  5113. }
  5114. const logStatus = scripts_echoLog({
  5115. type: 'joiningSteamGroup',
  5116. text: groupName
  5117. });
  5118. const {
  5119. result,
  5120. statusText,
  5121. status,
  5122. data
  5123. } = await tools_httpRequest({
  5124. url: `https://steamcommunity.com/groups/${groupName}`,
  5125. method: 'POST',
  5126. headers: {
  5127. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5128. },
  5129. data: $.param({
  5130. action: 'join',
  5131. sessionID: this.#auth.communitySessionID
  5132. })
  5133. });
  5134. if (result === 'Success') {
  5135. if (data?.status === 200 && !data.responseText.includes('grouppage_join_area')) {
  5136. logStatus.success();
  5137. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5138. return true;
  5139. }
  5140. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5141. return false;
  5142. }
  5143. logStatus.error(`${result}:${statusText}(${status})`);
  5144. return false;
  5145. } catch (error) {
  5146. throwError(error, 'Steam.joinGroup');
  5147. return false;
  5148. }
  5149. }
  5150. async #leaveGroup(groupName) {
  5151. try {
  5152. if (this.whiteList.groups.includes(groupName)) {
  5153. scripts_echoLog({
  5154. type: 'whiteList',
  5155. text: 'Steam.leaveGroup',
  5156. id: groupName
  5157. });
  5158. return true;
  5159. }
  5160. if (this.#ASF) {
  5161. return await this.#ASF.leaveGroup(groupName);
  5162. }
  5163. const groupId = await this.#getGroupId(groupName);
  5164. if (!groupId) {
  5165. return false;
  5166. }
  5167. const logStatus = scripts_echoLog({
  5168. type: 'leavingSteamGroup',
  5169. text: groupName
  5170. });
  5171. const {
  5172. result,
  5173. statusText,
  5174. status,
  5175. data
  5176. } = await tools_httpRequest({
  5177. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5178. method: 'POST',
  5179. headers: {
  5180. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5181. },
  5182. data: $.param({
  5183. sessionID: this.#auth.communitySessionID,
  5184. action: 'leaveGroup',
  5185. groupId: groupId
  5186. })
  5187. });
  5188. if (result === 'Success') {
  5189. 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) {
  5190. logStatus.success();
  5191. return true;
  5192. }
  5193. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5194. return false;
  5195. }
  5196. logStatus.error(`${result}:${statusText}(${status})`);
  5197. return false;
  5198. } catch (error) {
  5199. throwError(error, 'Steam.leaveGroup');
  5200. return false;
  5201. }
  5202. }
  5203. async #getGroupId(groupName) {
  5204. try {
  5205. const logStatus = scripts_echoLog({
  5206. type: 'gettingSteamGroupId',
  5207. text: groupName
  5208. });
  5209. const groupId = this.#cache.group[groupName];
  5210. if (groupId) {
  5211. logStatus.success();
  5212. return groupId;
  5213. }
  5214. const {
  5215. result,
  5216. statusText,
  5217. status,
  5218. data
  5219. } = await tools_httpRequest({
  5220. url: `https://steamcommunity.com/groups/${groupName}`,
  5221. method: 'GET',
  5222. headers: {
  5223. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5224. }
  5225. });
  5226. if (result === 'Success') {
  5227. if (data?.status === 200) {
  5228. const groupId = data.responseText.match(/OpenGroupChat\( '([0-9]+)'/)?.[1];
  5229. if (groupId) {
  5230. this.#setCache('group', groupName, groupId);
  5231. logStatus.success();
  5232. return groupId;
  5233. }
  5234. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5235. return false;
  5236. }
  5237. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5238. return false;
  5239. }
  5240. logStatus.error(`${result}:${statusText}(${status})`);
  5241. return false;
  5242. } catch (error) {
  5243. throwError(error, 'Steam.getGroupID');
  5244. return false;
  5245. }
  5246. }
  5247. async #joinOfficialGroup(gameId) {
  5248. try {
  5249. if (this.#ASF) {
  5250. if (await this.#ASF.joinGroup(gameId)) {
  5251. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5252. return true;
  5253. }
  5254. return false;
  5255. }
  5256. const logStatus = scripts_echoLog({
  5257. type: 'joiningSteamOfficialGroup',
  5258. text: gameId
  5259. });
  5260. const {
  5261. result,
  5262. statusText,
  5263. status,
  5264. data
  5265. } = await tools_httpRequest({
  5266. url: `https://steamcommunity.com/games/${gameId}?action=join&sessionID=${this.#auth.communitySessionID}`,
  5267. method: 'GET',
  5268. headers: {
  5269. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5270. }
  5271. });
  5272. if (result === 'Success') {
  5273. if (data?.status === 200 && !data.responseText.includes('id="publicGroupJoin"')) {
  5274. logStatus.success();
  5275. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5276. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5277. if (groupId) {
  5278. this.#setCache('officialGroup', gameId, groupId);
  5279. }
  5280. return true;
  5281. }
  5282. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5283. return false;
  5284. }
  5285. logStatus.error(`${result}:${statusText}(${status})`);
  5286. return false;
  5287. } catch (error) {
  5288. throwError(error, 'Steam.joinOfficialGroup');
  5289. return false;
  5290. }
  5291. }
  5292. async #leaveOfficialGroup(gameId) {
  5293. try {
  5294. if (this.whiteList.officialGroups.includes(gameId)) {
  5295. scripts_echoLog({
  5296. type: 'whiteList',
  5297. text: 'Steam.leaveOfficialGroup',
  5298. id: gameId
  5299. });
  5300. return true;
  5301. }
  5302. if (this.#ASF) {
  5303. return await this.#ASF.leaveGroup(gameId);
  5304. }
  5305. const groupId = await this.#getOfficialGroupId(gameId);
  5306. if (!groupId) {
  5307. return false;
  5308. }
  5309. const logStatus = scripts_echoLog({
  5310. type: 'leavingSteamOfficialGroup',
  5311. text: gameId
  5312. });
  5313. const {
  5314. result,
  5315. statusText,
  5316. status,
  5317. data
  5318. } = await tools_httpRequest({
  5319. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5320. method: 'POST',
  5321. headers: {
  5322. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5323. },
  5324. data: $.param({
  5325. sessionID: this.#auth.communitySessionID,
  5326. action: 'leaveGroup',
  5327. groupId: groupId
  5328. })
  5329. });
  5330. if (result === 'Success') {
  5331. if (data?.status === 200) {
  5332. const {
  5333. result: resultR,
  5334. statusText: statusTextR,
  5335. status: statusR,
  5336. data: dataR
  5337. } = await tools_httpRequest({
  5338. url: `https://steamcommunity.com/games/${gameId}`,
  5339. method: 'GET',
  5340. headers: {
  5341. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5342. }
  5343. });
  5344. if (resultR === 'Success') {
  5345. if (dataR?.status === 200 && dataR.responseText.includes('id="publicGroupJoin"')) {
  5346. logStatus.success();
  5347. return true;
  5348. }
  5349. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5350. return false;
  5351. }
  5352. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5353. return false;
  5354. }
  5355. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5356. return false;
  5357. }
  5358. logStatus.error(`${result}:${statusText}(${status})`);
  5359. return false;
  5360. } catch (error) {
  5361. throwError(error, 'Steam.leaveOfficialGroup');
  5362. return false;
  5363. }
  5364. }
  5365. async #getOfficialGroupId(gameId) {
  5366. try {
  5367. const logStatus = scripts_echoLog({
  5368. type: 'gettingSteamOfficialGroupId',
  5369. text: gameId
  5370. });
  5371. const groupId = this.#cache.officialGroup[gameId];
  5372. if (groupId) {
  5373. logStatus.success();
  5374. return groupId;
  5375. }
  5376. const {
  5377. result,
  5378. statusText,
  5379. status,
  5380. data
  5381. } = await tools_httpRequest({
  5382. url: `https://steamcommunity.com/games/${gameId}`,
  5383. method: 'GET',
  5384. headers: {
  5385. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5386. }
  5387. });
  5388. if (result === 'Success') {
  5389. if (data?.status === 200) {
  5390. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5391. if (groupId) {
  5392. this.#setCache('officialGroup', gameId, groupId);
  5393. logStatus.success();
  5394. return groupId;
  5395. }
  5396. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5397. return false;
  5398. }
  5399. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5400. return false;
  5401. }
  5402. logStatus.error(`${result}:${statusText}(${status})`);
  5403. return false;
  5404. } catch (error) {
  5405. throwError(error, 'Steam.getGroupID');
  5406. return false;
  5407. }
  5408. }
  5409. async #addToWishlist(gameId) {
  5410. try {
  5411. if (this.#ASF) {
  5412. if (await this.#ASF.addToWishlist(gameId)) {
  5413. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5414. return true;
  5415. }
  5416. return false;
  5417. }
  5418. const logStatus = scripts_echoLog({
  5419. type: 'addingToWishlist',
  5420. text: gameId
  5421. });
  5422. const {
  5423. result,
  5424. data
  5425. } = await tools_httpRequest({
  5426. url: 'https://store.steampowered.com/api/addtowishlist',
  5427. method: 'POST',
  5428. headers: {
  5429. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5430. },
  5431. data: $.param({
  5432. sessionid: this.#auth.storeSessionID,
  5433. appid: gameId
  5434. }),
  5435. dataType: 'json'
  5436. });
  5437. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  5438. logStatus.success();
  5439. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5440. return true;
  5441. }
  5442. const {
  5443. result: resultR,
  5444. statusText: statusTextR,
  5445. status: statusR,
  5446. data: dataR
  5447. } = await tools_httpRequest({
  5448. url: `https://store.steampowered.com/app/${gameId}`,
  5449. method: 'GET'
  5450. });
  5451. if (resultR === 'Success') {
  5452. if (dataR?.status === 200) {
  5453. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  5454. logStatus.warning(i18n('changeAreaNotice'));
  5455. if (!await this.#changeArea()) {
  5456. return false;
  5457. }
  5458. return await this.#addToWishlist(gameId);
  5459. }
  5460. if (dataR.responseText.includes('class="queue_actions_ctn"') && dataR.responseText.includes('class="already_in_library"')) {
  5461. logStatus.success();
  5462. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5463. return true;
  5464. } 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"')) {
  5465. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  5466. return false;
  5467. }
  5468. logStatus.success();
  5469. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5470. return true;
  5471. }
  5472. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5473. return false;
  5474. }
  5475. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5476. return false;
  5477. } catch (error) {
  5478. throwError(error, 'Steam.addToWishlist');
  5479. return false;
  5480. }
  5481. }
  5482. async #removeFromWishlist(gameId) {
  5483. try {
  5484. if (this.whiteList.wishlists.includes(gameId)) {
  5485. scripts_echoLog({
  5486. type: 'whiteList',
  5487. text: 'Steam.removeFromWishlist',
  5488. id: gameId
  5489. });
  5490. return true;
  5491. }
  5492. if (this.#ASF) {
  5493. return await this.#ASF.removeFromWishlist(gameId);
  5494. }
  5495. const logStatus = scripts_echoLog({
  5496. type: 'removingFromWishlist',
  5497. text: gameId
  5498. });
  5499. const {
  5500. result,
  5501. data
  5502. } = await tools_httpRequest({
  5503. url: 'https://store.steampowered.com/api/removefromwishlist',
  5504. method: 'POST',
  5505. headers: {
  5506. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5507. },
  5508. data: $.param({
  5509. sessionid: this.#auth.storeSessionID,
  5510. appid: gameId
  5511. }),
  5512. dataType: 'json'
  5513. });
  5514. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  5515. logStatus.success();
  5516. return true;
  5517. }
  5518. const {
  5519. result: resultR,
  5520. statusText: statusTextR,
  5521. status: statusR,
  5522. data: dataR
  5523. } = await tools_httpRequest({
  5524. url: `https://store.steampowered.com/app/${gameId}`,
  5525. method: 'GET'
  5526. });
  5527. if (resultR === 'Success') {
  5528. if (dataR?.status === 200) {
  5529. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  5530. logStatus.warning(i18n('changeAreaNotice'));
  5531. const result = await this.#changeArea();
  5532. if (!result || result === 'CN' || result === 'skip') {
  5533. return false;
  5534. }
  5535. return await this.#removeFromWishlist(gameId);
  5536. }
  5537. if (dataR.responseText.includes('class="queue_actions_ctn"') && (dataR.responseText.includes('ds_owned_flag ds_flag') || dataR.responseText.includes('add_to_wishlist_area'))) {
  5538. logStatus.success();
  5539. return true;
  5540. }
  5541. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  5542. return false;
  5543. }
  5544. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5545. return false;
  5546. }
  5547. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5548. return false;
  5549. } catch (error) {
  5550. throwError(error, 'Steam.removeFromWishlist');
  5551. return false;
  5552. }
  5553. }
  5554. async #toggleFollowGame(gameId, doTask) {
  5555. try {
  5556. if (!doTask && this.whiteList.follows.includes(gameId)) {
  5557. scripts_echoLog({
  5558. type: 'whiteList',
  5559. text: 'Steam.unfollowGame',
  5560. id: gameId
  5561. });
  5562. return true;
  5563. }
  5564. if (this.#ASF) {
  5565. if (await this.#ASF.toggleFollowGame(gameId, doTask)) {
  5566. if (doTask) {
  5567. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  5568. }
  5569. return true;
  5570. }
  5571. return false;
  5572. }
  5573. const logStatus = scripts_echoLog({
  5574. type: `${doTask ? '' : 'un'}followingGame`,
  5575. text: gameId
  5576. });
  5577. const requestData = {
  5578. sessionid: this.#auth.storeSessionID,
  5579. appid: gameId
  5580. };
  5581. if (!doTask) {
  5582. requestData.unfollow = '1';
  5583. }
  5584. const {
  5585. result,
  5586. data
  5587. } = await tools_httpRequest({
  5588. url: 'https://store.steampowered.com/explore/followgame/',
  5589. method: 'POST',
  5590. headers: {
  5591. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5592. },
  5593. data: $.param(requestData)
  5594. });
  5595. if (result === 'Success' && data?.status === 200 && data.responseText === 'true') {
  5596. logStatus.success();
  5597. return true;
  5598. }
  5599. const followed = await this.#isFollowedGame(gameId);
  5600. if (this.#area === 'CN' && followed === 'areaLocked') {
  5601. logStatus.warning(i18n('changeAreaNotice'));
  5602. if (!await this.#changeArea()) {
  5603. return false;
  5604. }
  5605. return await this.#toggleFollowGame(gameId, doTask);
  5606. }
  5607. if (doTask === followed) {
  5608. logStatus.success();
  5609. if (doTask) {
  5610. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  5611. }
  5612. return true;
  5613. }
  5614. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5615. return false;
  5616. } catch (error) {
  5617. throwError(error, 'Steam.toggleFollowGame');
  5618. return false;
  5619. }
  5620. }
  5621. async #isFollowedGame(gameId) {
  5622. try {
  5623. const {
  5624. result,
  5625. data
  5626. } = await tools_httpRequest({
  5627. url: `https://store.steampowered.com/app/${gameId}`,
  5628. method: 'GET'
  5629. });
  5630. if (result === 'Success') {
  5631. if (data?.status === 200) {
  5632. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  5633. return 'areaLocked';
  5634. }
  5635. if ($(data.responseText.replace(/<img.*?>/g, '')).find('.queue_control_button.queue_btn_follow>.btnv6_blue_hoverfade.btn_medium.queue_btn_active').css('display') !== 'none') {
  5636. return true;
  5637. }
  5638. return false;
  5639. }
  5640. return false;
  5641. }
  5642. return false;
  5643. } catch (error) {
  5644. throwError(error, 'Steam.isFollowedGame');
  5645. return false;
  5646. }
  5647. }
  5648. async #toggleForum(gameId, doTask = true) {
  5649. try {
  5650. if (!doTask && this.whiteList.forums.includes(gameId)) {
  5651. scripts_echoLog({
  5652. type: 'whiteList',
  5653. text: 'Steam.unsubscribeForum',
  5654. id: gameId
  5655. });
  5656. return true;
  5657. }
  5658. const forumId = await this.#getForumId(gameId);
  5659. if (!forumId) {
  5660. return false;
  5661. }
  5662. const logStatus = scripts_echoLog({
  5663. type: `${doTask ? '' : 'un'}subscribingForum`,
  5664. text: gameId
  5665. });
  5666. const [ id, feature ] = forumId.split('_');
  5667. const {
  5668. result,
  5669. statusText,
  5670. status,
  5671. data
  5672. } = await tools_httpRequest({
  5673. url: `https://steamcommunity.com/forum/${id}/General/${doTask ? '' : 'un'}subscribe/${feature || '0'}/`,
  5674. method: 'POST',
  5675. responseType: 'json',
  5676. headers: {
  5677. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5678. },
  5679. data: $.param({
  5680. sessionid: this.#auth.communitySessionID
  5681. })
  5682. });
  5683. if (result === 'Success') {
  5684. if (data?.status === 200 && (data.response?.success === 1 || data.response?.success === 29)) {
  5685. if (doTask) {
  5686. this.tasks.forums = unique([ ...this.tasks.forums, gameId ]);
  5687. }
  5688. logStatus.success();
  5689. return true;
  5690. }
  5691. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5692. return true;
  5693. }
  5694. logStatus.error(`${result}:${statusText}(${status})`);
  5695. return true;
  5696. } catch (error) {
  5697. throwError(error, 'Steam.toggleForum');
  5698. return true;
  5699. }
  5700. }
  5701. async #getForumId(gameId) {
  5702. try {
  5703. const logStatus = scripts_echoLog({
  5704. type: 'gettingForumId',
  5705. text: gameId
  5706. });
  5707. const forumId = this.#cache.forum[gameId];
  5708. if (forumId) {
  5709. logStatus.success();
  5710. return forumId;
  5711. }
  5712. const {
  5713. result,
  5714. statusText,
  5715. status,
  5716. data
  5717. } = await tools_httpRequest({
  5718. url: `https://steamcommunity.com/app/${gameId}/discussions/`,
  5719. method: 'GET'
  5720. });
  5721. if (result === 'Success') {
  5722. if (data?.status === 200) {
  5723. const forumId = data.responseText?.match(/General_([\d]+(_[\d]+)?)/)?.[1];
  5724. if (forumId) {
  5725. this.#setCache('forum', gameId, forumId);
  5726. logStatus.success();
  5727. return forumId;
  5728. }
  5729. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5730. return false;
  5731. }
  5732. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5733. return false;
  5734. }
  5735. logStatus.error(`${result}:${statusText}(${status})`);
  5736. return false;
  5737. } catch (error) {
  5738. throwError(error, 'Steam.getForumId');
  5739. return false;
  5740. }
  5741. }
  5742. async #toggleFavoriteWorkshop(id, doTask = true) {
  5743. try {
  5744. if (!doTask && this.whiteList.workshops.includes(id)) {
  5745. scripts_echoLog({
  5746. type: 'whiteList',
  5747. text: 'Steam.unfavoriteWorkshop',
  5748. id: id
  5749. });
  5750. return true;
  5751. }
  5752. const appid = await this.#getWorkshopAppId(id);
  5753. if (!appid) {
  5754. return false;
  5755. }
  5756. const logStatus = scripts_echoLog({
  5757. type: doTask ? 'favoritingWorkshop' : 'unfavoritingWorkshop',
  5758. text: id
  5759. });
  5760. const {
  5761. result,
  5762. statusText,
  5763. status,
  5764. data
  5765. } = await tools_httpRequest({
  5766. url: `https://steamcommunity.com/sharedfiles/${doTask ? '' : 'un'}favorite`,
  5767. method: 'POST',
  5768. headers: {
  5769. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5770. },
  5771. data: $.param({
  5772. id: id,
  5773. appid: appid,
  5774. sessionid: this.#auth.communitySessionID
  5775. })
  5776. });
  5777. if (result === 'Success') {
  5778. if (data?.status === 200 && !data.responseText) {
  5779. if (doTask) {
  5780. this.tasks.workshops = unique([ ...this.tasks.workshops, id ]);
  5781. }
  5782. logStatus.success();
  5783. return true;
  5784. }
  5785. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5786. return false;
  5787. }
  5788. logStatus.error(`${result}:${statusText}(${status})`);
  5789. return false;
  5790. } catch (error) {
  5791. throwError(error, 'Steam.toggleFavoriteWorkshop');
  5792. return false;
  5793. }
  5794. }
  5795. async #getWorkshopAppId(id) {
  5796. try {
  5797. const logStatus = scripts_echoLog({
  5798. type: 'gettingWorkshopAppId',
  5799. text: id
  5800. });
  5801. const appId = this.#cache.workshop[id];
  5802. if (appId) {
  5803. logStatus.success();
  5804. return appId;
  5805. }
  5806. const {
  5807. result,
  5808. statusText,
  5809. status,
  5810. data
  5811. } = await tools_httpRequest({
  5812. url: `https://steamcommunity.com/sharedfiles/filedetails/?id=${id}`,
  5813. method: 'GET'
  5814. });
  5815. if (result === 'Success') {
  5816. if (data?.status === 200) {
  5817. const appId = data.responseText.match(/<input type="hidden" name="appid" value="([\d]+?)" \/>/)?.[1];
  5818. if (appId) {
  5819. this.#setCache('workshop', id, appId);
  5820. logStatus.success();
  5821. return appId;
  5822. }
  5823. logStatus.error('Error: getWorkshopAppId failed');
  5824. return false;
  5825. }
  5826. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5827. return false;
  5828. }
  5829. logStatus.error(`${result}:${statusText}(${status})`);
  5830. return false;
  5831. } catch (error) {
  5832. throwError(error, 'Steam.getWorkshopAppId');
  5833. return false;
  5834. }
  5835. }
  5836. async #voteUpWorkshop(id) {
  5837. try {
  5838. const logStatus = scripts_echoLog({
  5839. type: 'votingUpWorkshop',
  5840. text: id
  5841. });
  5842. const {
  5843. result,
  5844. statusText,
  5845. status,
  5846. data
  5847. } = await tools_httpRequest({
  5848. url: 'https://steamcommunity.com/sharedfiles/voteup',
  5849. method: 'POST',
  5850. responseType: 'json',
  5851. headers: {
  5852. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5853. },
  5854. data: $.param({
  5855. id: id,
  5856. sessionid: this.#auth.communitySessionID
  5857. })
  5858. });
  5859. if (result === 'Success') {
  5860. if (data?.status === 200 && data.response?.success === 1) {
  5861. logStatus.success();
  5862. return true;
  5863. }
  5864. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5865. return true;
  5866. }
  5867. logStatus.error(`${result}:${statusText}(${status})`);
  5868. return true;
  5869. } catch (error) {
  5870. throwError(error, 'Steam.voteupWorkshop');
  5871. return true;
  5872. }
  5873. }
  5874. async #toggleCurator(curatorId, doTask = true) {
  5875. try {
  5876. if (!doTask && this.whiteList.curators.includes(curatorId)) {
  5877. scripts_echoLog({
  5878. type: 'whiteList',
  5879. text: 'Steam.unfollowCurator',
  5880. id: curatorId
  5881. });
  5882. return true;
  5883. }
  5884. if (this.#ASF) {
  5885. return await this.#ASF.toggleCurator(curatorId, doTask);
  5886. }
  5887. const logStatus = scripts_echoLog({
  5888. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  5889. text: curatorId
  5890. });
  5891. const {
  5892. result,
  5893. statusText,
  5894. status,
  5895. data
  5896. } = await tools_httpRequest({
  5897. url: 'https://store.steampowered.com/curators/ajaxfollow',
  5898. method: 'POST',
  5899. headers: {
  5900. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5901. },
  5902. data: $.param({
  5903. clanid: curatorId,
  5904. sessionid: this.#auth.storeSessionID,
  5905. follow: doTask
  5906. }),
  5907. dataType: 'json'
  5908. });
  5909. if (result === 'Success') {
  5910. if (data?.status === 200 && data.response?.success?.success === 1) {
  5911. logStatus.success();
  5912. return true;
  5913. }
  5914. logStatus.error(`Error:${data?.statusText}(${data?.response?.success}` || `${data?.status})`);
  5915. return false;
  5916. }
  5917. logStatus.error(`${result}:${statusText}(${status})`);
  5918. return false;
  5919. } catch (error) {
  5920. throwError(error, 'Steam.toggleCurator');
  5921. return false;
  5922. }
  5923. }
  5924. async getCuratorId(path, name) {
  5925. try {
  5926. const logStatus = scripts_echoLog({
  5927. type: 'gettingCuratorId',
  5928. text: `${path}/${name}`
  5929. });
  5930. const curatorId = this.#cache.curator[`${path}/${name}`];
  5931. if (curatorId) {
  5932. logStatus.success();
  5933. return curatorId;
  5934. }
  5935. const {
  5936. result,
  5937. statusText,
  5938. status,
  5939. data
  5940. } = await tools_httpRequest({
  5941. url: `https://store.steampowered.com/${path}/${name}`,
  5942. method: 'GET',
  5943. headers: {
  5944. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5945. }
  5946. });
  5947. if (result === 'Success') {
  5948. if (data?.status === 200) {
  5949. const curatorId = data.responseText.match(/g_pagingData.*?"clanid":([\d]+)/)?.[1];
  5950. if (curatorId) {
  5951. this.#setCache('curator', `${path}/${name}`, curatorId);
  5952. logStatus.success();
  5953. return curatorId;
  5954. }
  5955. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5956. return false;
  5957. }
  5958. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5959. return false;
  5960. }
  5961. logStatus.error(`${result}:${statusText}(${status})`);
  5962. return false;
  5963. } catch (error) {
  5964. throwError(error, 'Steam.getCuratorID');
  5965. return false;
  5966. }
  5967. }
  5968. async #toggleCuratorLike(link, doTask = true) {
  5969. try {
  5970. const [ path, name ] = link.split('/');
  5971. if (!(path && name)) {
  5972. scripts_echoLog({
  5973. text: i18n('errorLink', link)
  5974. });
  5975. return false;
  5976. }
  5977. const curatorId = await this.getCuratorId(path, name);
  5978. if (curatorId) {
  5979. return await this.#toggleCurator(curatorId, doTask);
  5980. }
  5981. return false;
  5982. } catch (error) {
  5983. throwError(error, 'Steam.toggleCuratorLike');
  5984. return false;
  5985. }
  5986. }
  5987. async #getAnnouncementParams(appId, viewId) {
  5988. try {
  5989. const logStatus = scripts_echoLog({
  5990. type: 'gettingAnnouncementParams',
  5991. text: appId,
  5992. id: viewId
  5993. });
  5994. const {
  5995. result,
  5996. statusText,
  5997. status,
  5998. data
  5999. } = await tools_httpRequest({
  6000. 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`,
  6001. method: 'GET',
  6002. responseType: 'json',
  6003. headers: {
  6004. Host: 'store.steampowered.com',
  6005. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6006. }
  6007. });
  6008. if (result === 'Success') {
  6009. if (data?.status === 200 && data?.response?.success === 1) {
  6010. const {
  6011. clanid,
  6012. gid
  6013. } = data.response.event?.announcement_body || {};
  6014. if (clanid) {
  6015. logStatus.success();
  6016. return {
  6017. clanId: clanid,
  6018. gid: gid
  6019. };
  6020. }
  6021. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6022. return {};
  6023. }
  6024. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6025. return {};
  6026. }
  6027. logStatus.error(`${result}:${statusText}(${status})`);
  6028. return {};
  6029. } catch (error) {
  6030. throwError(error, 'Steam.likeAnnouncement');
  6031. return {};
  6032. }
  6033. }
  6034. async #likeAnnouncement(id) {
  6035. try {
  6036. const [ appId, viewId ] = id.split('/');
  6037. if (!(appId && viewId)) {
  6038. scripts_echoLog({}).error(`${i18n('missParams')}(id)`);
  6039. return false;
  6040. }
  6041. const {
  6042. clanId,
  6043. gid
  6044. } = await this.#getAnnouncementParams(appId, viewId);
  6045. if (!clanId) {
  6046. return false;
  6047. }
  6048. const logStatus = scripts_echoLog({
  6049. type: 'likingAnnouncement',
  6050. text: appId,
  6051. id: viewId
  6052. });
  6053. const {
  6054. result,
  6055. statusText,
  6056. status,
  6057. data
  6058. } = await tools_httpRequest({
  6059. url: `https://store.steampowered.com/updated/ajaxrateupdate/${gid || viewId}`,
  6060. method: 'POST',
  6061. headers: {
  6062. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6063. Host: 'store.steampowered.com',
  6064. Origin: 'https://store.steampowered.com',
  6065. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6066. },
  6067. data: $.param({
  6068. sessionid: this.#auth.storeSessionID,
  6069. voteup: 1,
  6070. clanid: clanId,
  6071. ajax: 1
  6072. }),
  6073. dataType: 'json'
  6074. });
  6075. if (result === 'Success') {
  6076. if (data?.status === 200 && data.response.success === 1) {
  6077. logStatus.success();
  6078. return true;
  6079. }
  6080. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6081. return false;
  6082. }
  6083. logStatus.error(`${result}:${statusText}(${status})`);
  6084. return false;
  6085. } catch (error) {
  6086. throwError(error, 'Steam.likeAnnouncement');
  6087. return false;
  6088. }
  6089. }
  6090. async #appid2subid(id) {
  6091. try {
  6092. const logStatus = scripts_echoLog({
  6093. type: 'gettingSubid',
  6094. text: id
  6095. });
  6096. const {
  6097. result,
  6098. statusText,
  6099. status,
  6100. data
  6101. } = await tools_httpRequest({
  6102. url: `https://store.steampowered.com/app/${id}`,
  6103. method: 'GET',
  6104. headers: {
  6105. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6106. }
  6107. });
  6108. if (result === 'Success') {
  6109. if (data?.status === 200) {
  6110. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6111. logStatus.success(i18n('owned'));
  6112. return false;
  6113. }
  6114. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6115. logStatus.warning(i18n('changeAreaNotice'));
  6116. const result = await this.#changeArea();
  6117. if (!result || result === 'CN' || result === 'skip') {
  6118. return false;
  6119. }
  6120. return await this.#appid2subid(id);
  6121. }
  6122. let subid = data.responseText.match(/name="subid" value="([\d]+?)"/)?.[1];
  6123. if (subid) {
  6124. logStatus.success();
  6125. return subid;
  6126. }
  6127. subid = data.responseText.match(/AddFreeLicense\(\s*(\d+)/)?.[1];
  6128. if (subid) {
  6129. logStatus.success();
  6130. return subid;
  6131. }
  6132. logStatus.error(`Error:${i18n('noSubid')}`);
  6133. return false;
  6134. }
  6135. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6136. return false;
  6137. }
  6138. logStatus.error(`${result}:${statusText}(${status})`);
  6139. return false;
  6140. } catch (error) {
  6141. throwError(error, 'Steam.appid2subid');
  6142. return false;
  6143. }
  6144. }
  6145. async #getLicenses() {
  6146. try {
  6147. const logStatus = scripts_echoLog({
  6148. text: i18n('gettingLicenses')
  6149. });
  6150. const {
  6151. result,
  6152. statusText,
  6153. status,
  6154. data
  6155. } = await tools_httpRequest({
  6156. url: `https://store.steampowered.com/dynamicstore/userdata/?t=${new Date().getTime()}`,
  6157. method: 'GET',
  6158. responseType: 'json'
  6159. });
  6160. if (result === 'Success') {
  6161. if (data?.status === 200) {
  6162. logStatus.success();
  6163. return data.response?.rgOwnedPackages;
  6164. }
  6165. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6166. return false;
  6167. }
  6168. logStatus.error(`${result}:${statusText}(${status})`);
  6169. return false;
  6170. } catch (error) {
  6171. throwError(error, 'Steam.getLicenses');
  6172. return false;
  6173. }
  6174. }
  6175. async #addLicense(id) {
  6176. try {
  6177. if (this.#ASF) {
  6178. return await this.#ASF.addLicense(id);
  6179. }
  6180. const [ type, ids ] = id.split('-');
  6181. if (type === 'appid') {
  6182. const subid = await this.#appid2subid(ids);
  6183. if (!subid) {
  6184. return false;
  6185. }
  6186. const logStatus = scripts_echoLog({
  6187. type: 'addingFreeLicense',
  6188. text: ids
  6189. });
  6190. if (!await this.#addFreeLicense(subid, logStatus)) {
  6191. return false;
  6192. }
  6193. const {
  6194. result,
  6195. statusText,
  6196. status,
  6197. data
  6198. } = await tools_httpRequest({
  6199. url: `https://store.steampowered.com/app/${ids}`,
  6200. method: 'GET'
  6201. });
  6202. if (result === 'Success') {
  6203. if (data?.status === 200) {
  6204. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6205. logStatus.success();
  6206. return true;
  6207. }
  6208. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6209. return false;
  6210. }
  6211. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6212. return false;
  6213. }
  6214. logStatus.error(`${result}:${statusText}(${status})`);
  6215. return false;
  6216. } else if (type === 'subid') {
  6217. if (this.#area === 'CN') {
  6218. scripts_echoLog({}).success(i18n('tryChangeAreaNotice'));
  6219. await this.#changeArea();
  6220. }
  6221. const logStatusArr = {};
  6222. const idsArr = ids.split(',');
  6223. for (const subid of idsArr) {
  6224. const logStatus = scripts_echoLog({
  6225. type: 'addingFreeLicenseSubid',
  6226. text: subid
  6227. });
  6228. if (!await this.#addFreeLicense(subid, logStatus)) {
  6229. return false;
  6230. }
  6231. logStatusArr[subid] = logStatus;
  6232. }
  6233. const licenses = await this.#getLicenses();
  6234. if (!licenses) {
  6235. return false;
  6236. }
  6237. for (const subid of idsArr) {
  6238. if (licenses.includes(parseInt(subid, 10))) {
  6239. logStatusArr[subid].success();
  6240. } else {
  6241. logStatusArr[subid].error();
  6242. }
  6243. }
  6244. return true;
  6245. }
  6246. return false;
  6247. } catch (error) {
  6248. throwError(error, 'Steam.addLicense');
  6249. return false;
  6250. }
  6251. }
  6252. async #addFreeLicense(id, logStatusPre) {
  6253. try {
  6254. const logStatus = logStatusPre || scripts_echoLog({
  6255. type: 'addingFreeLicenseSubid',
  6256. text: id
  6257. });
  6258. const {
  6259. result,
  6260. statusText,
  6261. status,
  6262. data
  6263. } = await tools_httpRequest({
  6264. url: `https://store.steampowered.com/freelicense/addfreelicense/${id}`,
  6265. method: 'POST',
  6266. headers: {
  6267. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6268. Host: 'store.steampowered.com',
  6269. Origin: 'https://store.steampowered.com',
  6270. Referer: 'https://store.steampowered.com/account/licenses/'
  6271. },
  6272. data: $.param({
  6273. ajax: true,
  6274. sessionid: this.#auth.storeSessionID
  6275. }),
  6276. dataType: 'json'
  6277. });
  6278. if (result === 'Success') {
  6279. if (data?.status === 200) {
  6280. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6281. logStatus.warning(i18n('changeAreaNotice'));
  6282. const result = await this.#changeArea();
  6283. if (!result || [ 'CN', 'skip' ].includes(result)) {
  6284. return false;
  6285. }
  6286. return await this.#addFreeLicense(id);
  6287. }
  6288. logStatus.success();
  6289. return true;
  6290. }
  6291. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6292. return false;
  6293. }
  6294. logStatus.error(`${result}:${statusText}(${status})`);
  6295. return false;
  6296. } catch (error) {
  6297. throwError(error, 'Steam.addFreeLicense');
  6298. return false;
  6299. }
  6300. }
  6301. async #requestPlayTestAccess(id) {
  6302. try {
  6303. if (this.#ASF) {
  6304. return await this.#ASF.requestPlayTestAccess(id);
  6305. }
  6306. const logStatus = scripts_echoLog({
  6307. type: 'requestingPlayTestAccess',
  6308. text: id
  6309. });
  6310. const {
  6311. result,
  6312. statusText,
  6313. status,
  6314. data
  6315. } = await tools_httpRequest({
  6316. url: `https://store.steampowered.com/ajaxrequestplaytestaccess/${id}`,
  6317. method: 'POST',
  6318. headers: {
  6319. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6320. Host: 'store.steampowered.com',
  6321. Origin: 'https://store.steampowered.com',
  6322. Referer: `https://store.steampowered.com/app/${id}`
  6323. },
  6324. data: $.param({
  6325. sessionid: this.#auth.storeSessionID
  6326. }),
  6327. dataType: 'json'
  6328. });
  6329. if (result === 'Success') {
  6330. if (data?.status === 200 && data?.response?.success === 1) {
  6331. logStatus.success();
  6332. return true;
  6333. }
  6334. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6335. return false;
  6336. }
  6337. logStatus.error(`${result}:${statusText}(${status})`);
  6338. return false;
  6339. } catch (error) {
  6340. throwError(error, 'Steam.requestPlayTestAccess');
  6341. return false;
  6342. }
  6343. }
  6344. async toggle({
  6345. doTask = true,
  6346. groupLinks = [],
  6347. officialGroupLinks = [],
  6348. wishlistLinks = [],
  6349. followLinks = [],
  6350. forumLinks = [],
  6351. workshopLinks = [],
  6352. workshopVoteLinks = [],
  6353. curatorLinks = [],
  6354. curatorLikeLinks = [],
  6355. announcementLinks = [],
  6356. licenseLinks = [],
  6357. playtestLinks = []
  6358. }) {
  6359. try {
  6360. if ([ ...groupLinks, ...officialGroupLinks, ...forumLinks, ...workshopLinks, ...workshopVoteLinks ].length > 0 && !this.#communityInitialized) {
  6361. scripts_echoLog({
  6362. text: i18n('needInit')
  6363. });
  6364. return false;
  6365. }
  6366. if ([ ...wishlistLinks, ...followLinks, ...curatorLinks, ...curatorLikeLinks, ...announcementLinks, ...licenseLinks, ...playtestLinks ].length > 0 && !this.#storeInitialized) {
  6367. scripts_echoLog({
  6368. text: i18n('needInit')
  6369. });
  6370. return false;
  6371. }
  6372. const prom = [];
  6373. if (doTask && !globalOptions.doTask.steam.groups || !doTask && !globalOptions.undoTask.steam.groups) {
  6374. scripts_echoLog({
  6375. type: 'globalOptionsSkip',
  6376. text: 'steam.groups'
  6377. });
  6378. } else {
  6379. const realGroups = this.getRealParams('groups', groupLinks, doTask, link => link.match(/groups\/(.+)\/?/)?.[1]);
  6380. if (realGroups.length > 0) {
  6381. for (const group of realGroups) {
  6382. if (doTask) {
  6383. prom.push(this.#joinGroup(group));
  6384. } else {
  6385. prom.push(this.#leaveGroup(group));
  6386. }
  6387. await delay(1e3);
  6388. }
  6389. }
  6390. }
  6391. if (doTask && !globalOptions.doTask.steam.officialGroups || !doTask && !globalOptions.undoTask.steam.officialGroups) {
  6392. scripts_echoLog({
  6393. type: 'globalOptionsSkip',
  6394. text: 'steam.officialGroups'
  6395. });
  6396. } else {
  6397. const realOfficialGroups = this.getRealParams('officialGroups', officialGroupLinks, doTask, link => link.match(/games\/(.+)\/?/)?.[1]);
  6398. if (realOfficialGroups.length > 0) {
  6399. for (const officialGroup of realOfficialGroups) {
  6400. if (doTask) {
  6401. prom.push(this.#joinOfficialGroup(officialGroup));
  6402. } else {
  6403. prom.push(this.#leaveOfficialGroup(officialGroup));
  6404. }
  6405. await delay(1e3);
  6406. }
  6407. }
  6408. }
  6409. if (doTask && !globalOptions.doTask.steam.wishlists || !doTask && !globalOptions.undoTask.steam.wishlists) {
  6410. scripts_echoLog({
  6411. type: 'globalOptionsSkip',
  6412. text: 'steam.wishlists'
  6413. });
  6414. } else {
  6415. const realWishlists = this.getRealParams('wishlists', wishlistLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6416. if (realWishlists.length > 0) {
  6417. for (const game of realWishlists) {
  6418. if (doTask) {
  6419. prom.push(this.#addToWishlist(game));
  6420. } else {
  6421. prom.push(this.#removeFromWishlist(game));
  6422. }
  6423. await delay(1e3);
  6424. }
  6425. }
  6426. }
  6427. if (doTask && !globalOptions.doTask.steam.follows || !doTask && !globalOptions.undoTask.steam.follows) {
  6428. scripts_echoLog({
  6429. type: 'globalOptionsSkip',
  6430. text: 'steam.follows'
  6431. });
  6432. } else {
  6433. const realFollows = this.getRealParams('follows', followLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6434. if (realFollows.length > 0) {
  6435. for (const game of realFollows) {
  6436. prom.push(this.#toggleFollowGame(game, doTask));
  6437. await delay(1e3);
  6438. }
  6439. }
  6440. }
  6441. if (doTask && !globalOptions.doTask.steam.forums || !doTask && !globalOptions.undoTask.steam.forums) {
  6442. scripts_echoLog({
  6443. type: 'globalOptionsSkip',
  6444. text: 'steam.forums'
  6445. });
  6446. } else {
  6447. const realForums = this.getRealParams('forums', forumLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6448. if (realForums.length > 0) {
  6449. for (const forum of realForums) {
  6450. prom.push(this.#toggleForum(forum, doTask));
  6451. await delay(1e3);
  6452. }
  6453. }
  6454. }
  6455. if (doTask && !globalOptions.doTask.steam.workshops || !doTask && !globalOptions.undoTask.steam.workshops) {
  6456. scripts_echoLog({
  6457. type: 'globalOptionsSkip',
  6458. text: 'steam.workshops'
  6459. });
  6460. } else {
  6461. const realWorkshops = this.getRealParams('workshops', workshopLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  6462. if (realWorkshops.length > 0) {
  6463. for (const workshop of realWorkshops) {
  6464. prom.push(this.#toggleFavoriteWorkshop(workshop, doTask));
  6465. await delay(1e3);
  6466. }
  6467. }
  6468. }
  6469. if (doTask && !globalOptions.doTask.steam.workshopVotes) {
  6470. scripts_echoLog({
  6471. type: 'globalOptionsSkip',
  6472. text: 'steam.workshopVotes'
  6473. });
  6474. } else {
  6475. const realworkshopVotes = this.getRealParams('workshopVotes', workshopVoteLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  6476. if (doTask && realworkshopVotes.length > 0) {
  6477. for (const workshop of realworkshopVotes) {
  6478. prom.push(this.#voteUpWorkshop(workshop));
  6479. await delay(1e3);
  6480. }
  6481. }
  6482. }
  6483. if (doTask && !globalOptions.doTask.steam.curators || !doTask && !globalOptions.undoTask.steam.curators) {
  6484. scripts_echoLog({
  6485. type: 'globalOptionsSkip',
  6486. text: 'steam.curators'
  6487. });
  6488. } else {
  6489. const realCurators = this.getRealParams('curators', curatorLinks, doTask, link => link.match(/curator\/([\d]+)/)?.[1]);
  6490. const realCuratorLikes = this.getRealParams('curatorLikes', curatorLikeLinks, doTask, link => link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3).join('/'));
  6491. if (realCurators.length > 0) {
  6492. for (const curator of realCurators) {
  6493. prom.push(this.#toggleCurator(curator, doTask));
  6494. await delay(1e3);
  6495. }
  6496. }
  6497. if (realCuratorLikes.length > 0) {
  6498. for (const curatorLike of realCuratorLikes) {
  6499. prom.push(this.#toggleCuratorLike(curatorLike, doTask));
  6500. await delay(1e3);
  6501. }
  6502. }
  6503. }
  6504. if (doTask && !globalOptions.doTask.steam.announcements) {
  6505. scripts_echoLog({
  6506. type: 'globalOptionsSkip',
  6507. text: 'steam.announcements'
  6508. });
  6509. } else {
  6510. const realAnnouncements = this.getRealParams('announcements', announcementLinks, doTask, link => {
  6511. if (link.includes('store.steampowered.com')) {
  6512. return link.match(/store\.steampowered\.com\/news\/app\/([\d]+)\/view\/([\d]+)/)?.slice(1, 3).join('/');
  6513. }
  6514. return link.match(/steamcommunity\.com\/games\/([\d]+)\/announcements\/detail\/([\d]+)/)?.slice(1, 3).join('/');
  6515. });
  6516. if (doTask && realAnnouncements.length > 0) {
  6517. for (const id of realAnnouncements) {
  6518. prom.push(this.#likeAnnouncement(id));
  6519. await delay(1e3);
  6520. }
  6521. }
  6522. }
  6523. if (doTask && !globalOptions.doTask.steam.licenses) {
  6524. scripts_echoLog({
  6525. type: 'globalOptionsSkip',
  6526. text: 'steam.licenses'
  6527. });
  6528. } else if (doTask && globalOptions.doTask.steam.licenses && licenseLinks.length > 0) {
  6529. for (const ids of licenseLinks) {
  6530. const [ type, idsStr ] = ids.split('-');
  6531. const idsArr = idsStr.split(',');
  6532. for (const id of idsArr) {
  6533. prom.push(this.#addLicense(`${type}-${id}`));
  6534. await delay(1e3);
  6535. }
  6536. }
  6537. }
  6538. if (doTask && !globalOptions.doTask.steam.playtests) {
  6539. scripts_echoLog({
  6540. type: 'globalOptionsSkip',
  6541. text: 'steam.playtests'
  6542. });
  6543. } else {
  6544. const realPlaytests = this.getRealParams('playtests', playtestLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6545. if (doTask && globalOptions.doTask.steam.playtests && realPlaytests.length > 0) {
  6546. for (const id of realPlaytests) {
  6547. prom.push(this.#requestPlayTestAccess(id));
  6548. await delay(1e3);
  6549. }
  6550. }
  6551. }
  6552. return Promise.all(prom).then(async () => {
  6553. if (this.#oldArea && this.#area !== this.#oldArea) {
  6554. scripts_echoLog({}).warning(i18n('steamFinishNotice') + this.#oldArea);
  6555. await this.#changeArea(this.#oldArea);
  6556. }
  6557. return true;
  6558. });
  6559. } catch (error) {
  6560. throwError(error, 'Steam.toggle');
  6561. return false;
  6562. }
  6563. }
  6564. #setCache(type, name, id) {
  6565. try {
  6566. this.#cache[type][name] = id;
  6567. GM_setValue('steamCache', this.#cache);
  6568. } catch (error) {
  6569. throwError(error, 'Steam.setCache');
  6570. }
  6571. }
  6572. }
  6573. const social_Steam = Steam;
  6574. class Website {
  6575. undoneTasks;
  6576. socialTasks;
  6577. giveawayId;
  6578. socialInitialized = {
  6579. discord: false,
  6580. instagram: false,
  6581. reddit: false,
  6582. twitch: false,
  6583. twitter: false,
  6584. vk: false,
  6585. youtube: false,
  6586. steamStore: false,
  6587. steamCommunity: false
  6588. };
  6589. initialized = false;
  6590. social = {};
  6591. async #bind(name, init) {
  6592. try {
  6593. return {
  6594. name: name,
  6595. result: await init
  6596. };
  6597. } catch (error) {
  6598. throwError(error, 'Website.bind');
  6599. return {
  6600. name: name,
  6601. result: false
  6602. };
  6603. }
  6604. }
  6605. async initSocial(action) {
  6606. try {
  6607. const pro = [];
  6608. const tasks = action === 'do' ? this.undoneTasks : this.socialTasks;
  6609. if (tasks.discord) {
  6610. const hasDiscord = Object.values(tasks.discord).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6611. if (hasDiscord && (!this.socialInitialized.discord || !this.social.discord)) {
  6612. this.social.discord = new social_Discord();
  6613. pro.push(this.#bind('discord', this.social.discord.init(action)));
  6614. }
  6615. }
  6616. if (tasks.instagram) {
  6617. const hasInstagram = Object.values(tasks.instagram).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6618. if (hasInstagram && (!this.socialInitialized.instagram || !this.social.instagram)) {
  6619. this.social.instagram = new social_Instagram();
  6620. pro.push(this.#bind('instagram', this.social.instagram.init()));
  6621. }
  6622. }
  6623. if (tasks.reddit) {
  6624. const hasReddit = Object.values(tasks.reddit).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6625. if (hasReddit && (!this.socialInitialized.reddit || !this.social.reddit)) {
  6626. this.social.reddit = new social_Reddit();
  6627. pro.push(this.#bind('reddit', this.social.reddit.init()));
  6628. }
  6629. }
  6630. if (tasks.twitch) {
  6631. const hasTwitch = Object.values(tasks.twitch).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6632. if (hasTwitch && (!this.socialInitialized.twitch || !this.social.twitch)) {
  6633. this.social.twitch = new social_Twitch();
  6634. pro.push(this.#bind('twitch', this.social.twitch.init()));
  6635. }
  6636. }
  6637. if (tasks.twitter) {
  6638. const hasTwitter = Object.values(tasks.twitter).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6639. if (hasTwitter && (!this.socialInitialized.twitter || !this.social.twitter)) {
  6640. this.social.twitter = new social_Twitter();
  6641. pro.push(this.#bind('twitter', this.social.twitter.init()));
  6642. }
  6643. }
  6644. if (tasks.vk) {
  6645. const hasVk = Object.values(tasks.vk).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6646. if (hasVk && (!this.socialInitialized.vk || !this.social.vk)) {
  6647. this.social.vk = new social_Vk();
  6648. pro.push(this.#bind('vk', this.social.vk.init()));
  6649. }
  6650. }
  6651. if (tasks.youtube) {
  6652. const hasYoutube = Object.values(tasks.youtube).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6653. if (hasYoutube && (!this.socialInitialized.youtube || !this.social.youtube)) {
  6654. this.social.youtube = new Youtube();
  6655. pro.push(this.#bind('youtube', this.social.youtube.init()));
  6656. }
  6657. }
  6658. if (tasks.steam) {
  6659. const steamLength = Object.values(tasks.steam).reduce((total, arr) => [ ...total, ...arr ]).length;
  6660. if (steamLength > 0) {
  6661. if (!this.social.steam) {
  6662. this.social.steam = new social_Steam();
  6663. }
  6664. 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);
  6665. if (steamLength - steamCommunityLength > 0 && !this.socialInitialized.steamStore) {
  6666. pro.push(this.#bind('steamStore', this.social.steam.init('store')));
  6667. }
  6668. if (steamCommunityLength > 0 && !this.socialInitialized.steamCommunity) {
  6669. pro.push(this.#bind('steamCommunity', this.social.steam.init('community')));
  6670. }
  6671. }
  6672. }
  6673. if (tasks.links && tasks.links.length > 0) {
  6674. this.social.visitLink = visitLink;
  6675. }
  6676. return await Promise.all(pro).then(result => {
  6677. let checked = true;
  6678. for (const data of result) {
  6679. if (data.result) {
  6680. this.socialInitialized[data.name] = data.result;
  6681. } else {
  6682. checked = false;
  6683. }
  6684. }
  6685. return checked;
  6686. });
  6687. } catch (error) {
  6688. throwError(error, 'Website.initSocial');
  6689. return false;
  6690. }
  6691. }
  6692. uniqueTasks(allTasks) {
  6693. try {
  6694. const result = {};
  6695. for (const [ social, types ] of Object.entries(allTasks)) {
  6696. result[social] = {};
  6697. for (const [ type, tasks ] of Object.entries(types)) {
  6698. result[social][type] = unique(tasks);
  6699. }
  6700. }
  6701. return result;
  6702. } catch (error) {
  6703. throwError(error, 'Website.uniqueTasks');
  6704. return allTasks;
  6705. }
  6706. }
  6707. async toggleTask(action) {
  6708. try {
  6709. if (!this.initialized && !this.init()) {
  6710. return false;
  6711. }
  6712. if (!await this.classifyTask(action)) {
  6713. return false;
  6714. }
  6715. if (!await this.initSocial(action)) {
  6716. return false;
  6717. }
  6718. const pro = [];
  6719. const doTask = action === 'do';
  6720. const tasks = doTask ? this.undoneTasks : this.socialTasks;
  6721. if (this.socialInitialized.discord !== 'skip' && this.social.discord) {
  6722. pro.push(this.social.discord.toggle({
  6723. doTask: doTask,
  6724. ...tasks.discord
  6725. }));
  6726. }
  6727. if (this.social.instagram) {
  6728. pro.push(this.social.instagram.toggle({
  6729. doTask: doTask,
  6730. ...tasks.instagram
  6731. }));
  6732. }
  6733. if (this.social.reddit) {
  6734. pro.push(this.social.reddit.toggle({
  6735. doTask: doTask,
  6736. ...tasks.reddit
  6737. }));
  6738. }
  6739. if (this.social.twitch) {
  6740. pro.push(this.social.twitch.toggle({
  6741. doTask: doTask,
  6742. ...tasks.twitch
  6743. }));
  6744. }
  6745. if (this.social.twitter) {
  6746. pro.push(this.social.twitter.toggle({
  6747. doTask: doTask,
  6748. ...tasks.twitter
  6749. }));
  6750. }
  6751. if (this.social.vk) {
  6752. pro.push(this.social.vk.toggle({
  6753. doTask: doTask,
  6754. ...tasks.vk
  6755. }));
  6756. }
  6757. if (this.social.youtube) {
  6758. pro.push(this.social.youtube.toggle({
  6759. doTask: doTask,
  6760. ...tasks.youtube
  6761. }));
  6762. }
  6763. if (this.social.steam) {
  6764. pro.push(this.social.steam.toggle({
  6765. doTask: doTask,
  6766. ...tasks.steam
  6767. }));
  6768. }
  6769. if (this.social.visitLink && tasks.links && doTask) {
  6770. for (const link of tasks.links) {
  6771. pro.push(this.social.visitLink(link));
  6772. }
  6773. }
  6774. if (doTask && tasks.extra && this.extraDoTask) {
  6775. const hasExtra = Object.values(tasks.extra).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6776. if (hasExtra) {
  6777. pro.push(this.extraDoTask(tasks.extra));
  6778. }
  6779. }
  6780. await Promise.all(pro);
  6781. scripts_echoLog({}).success(i18n('allTasksComplete'));
  6782. return true;
  6783. } catch (error) {
  6784. throwError(error, 'Website.toggleTask');
  6785. return false;
  6786. }
  6787. }
  6788. async doTask() {
  6789. try {
  6790. return await this.toggleTask('do');
  6791. } catch (error) {
  6792. throwError(error, 'Website.doTask');
  6793. return false;
  6794. }
  6795. }
  6796. async undoTask() {
  6797. try {
  6798. return await this.toggleTask('undo');
  6799. } catch (error) {
  6800. throwError(error, 'Website.undoTask');
  6801. return false;
  6802. }
  6803. }
  6804. }
  6805. const website_Website = Website;
  6806. const defaultTasksTemplate = {
  6807. steam: {
  6808. groupLinks: [],
  6809. wishlistLinks: [],
  6810. curatorLinks: [],
  6811. followLinks: []
  6812. },
  6813. vk: {
  6814. nameLinks: []
  6815. }
  6816. };
  6817. const defaultTasks = JSON.stringify(defaultTasksTemplate);
  6818. class FreeAnyWhere extends website_Website {
  6819. name = 'FreeAnyWhere';
  6820. tasks = [];
  6821. socialTasks = JSON.parse(defaultTasks);
  6822. undoneTasks = JSON.parse(defaultTasks);
  6823. buttons = [ 'doTask', 'undoTask', 'verifyTask', 'getKey' ];
  6824. static test() {
  6825. return window.location.host === 'freeanywhere.net';
  6826. }
  6827. async init() {
  6828. try {
  6829. const logStatus = scripts_echoLog({
  6830. text: i18n('initing')
  6831. });
  6832. if ($('a[href="#/login"]').length > 0) {
  6833. window.open('/#/login', '_self');
  6834. logStatus.warning(i18n('needLogin'));
  6835. return false;
  6836. }
  6837. if (window.location.href.includes('/login')) {
  6838. logStatus.warning(i18n('needLogin'));
  6839. return false;
  6840. }
  6841. if (!/^https?:\/\/freeanywhere\.net\/#\/giveaway\/[\d]+/.test(window.location.href)) {
  6842. const id = window.location.href.match(/https?:\/\/freeanywhere\.net\/.*?#\/giveaway\/([\d]+)/)?.[1];
  6843. if (!id) {
  6844. logStatus.error(i18n('getFailed', 'Id'));
  6845. return false;
  6846. }
  6847. window.location.href = `https://freeanywhere.net/#/giveaway/${id}`;
  6848. }
  6849. if (!this.#getGiveawayId()) {
  6850. return false;
  6851. }
  6852. if (!await this.#checkLeftKey()) {
  6853. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  6854. }
  6855. this.initialized = true;
  6856. logStatus.success();
  6857. return true;
  6858. } catch (error) {
  6859. throwError(error, 'Freeanywhere.init');
  6860. return false;
  6861. }
  6862. }
  6863. async classifyTask(action) {
  6864. try {
  6865. const logStatus = scripts_echoLog({
  6866. text: i18n('getTasksInfo')
  6867. });
  6868. if (action === 'undo') {
  6869. this.socialTasks = GM_getValue(`fawTasks-${this.giveawayId}`)?.tasks || JSON.parse(defaultTasks);
  6870. }
  6871. const {
  6872. result,
  6873. statusText,
  6874. status,
  6875. data
  6876. } = await tools_httpRequest({
  6877. url: `https://freeanywhere.net/api/v1/giveaway/${this.giveawayId}/?format=json`,
  6878. method: 'GET',
  6879. headers: {
  6880. authorization: `Token ${window.localStorage.getItem('token')}`,
  6881. 'x-csrftoken': external_Cookies_default().get('csrftoken')
  6882. },
  6883. responseType: 'json'
  6884. });
  6885. if (result === 'Success') {
  6886. const tasks = data?.response?.challenges;
  6887. if (tasks) {
  6888. if (action === 'verify') {
  6889. this.tasks = [];
  6890. }
  6891. for (const task of tasks) {
  6892. const type = task.challenge;
  6893. const social = task.challenge_provider;
  6894. const taskInfo = {
  6895. id: task.id,
  6896. title: task.title
  6897. };
  6898. if (action === 'verify' && !task.is_success) {
  6899. this.tasks.push(taskInfo);
  6900. continue;
  6901. }
  6902. switch (social) {
  6903. case 'steam':
  6904. taskInfo.social = 'steam';
  6905. switch (type) {
  6906. case 'WL':
  6907. if (action === 'undo') {
  6908. this.socialTasks.steam.wishlistLinks.push(task.link);
  6909. }
  6910. if (action === 'do' && !task.is_success) {
  6911. this.undoneTasks.steam.wishlistLinks.push(task.link);
  6912. }
  6913. break;
  6914.  
  6915. case 'JTG':
  6916. if (action === 'undo') {
  6917. this.socialTasks.steam.groupLinks.push(task.link);
  6918. }
  6919. if (action === 'do' && !task.is_success) {
  6920. this.undoneTasks.steam.groupLinks.push(task.link);
  6921. }
  6922. break;
  6923.  
  6924. case 'STC':
  6925. if (action === 'undo') {
  6926. this.socialTasks.steam.curatorLinks.push(task.link);
  6927. }
  6928. if (action === 'do' && !task.is_success) {
  6929. this.undoneTasks.steam.curatorLinks.push(task.link);
  6930. }
  6931. break;
  6932.  
  6933. case 'GF':
  6934. if (action === 'undo') {
  6935. this.socialTasks.steam.followLinks.push(task.link);
  6936. }
  6937. if (action === 'do' && !task.is_success) {
  6938. this.undoneTasks.steam.followLinks.push(task.link);
  6939. }
  6940. break;
  6941. }
  6942. break;
  6943.  
  6944. case 'vk-oauth2':
  6945. if (action === 'undo') {
  6946. this.socialTasks.vk.nameLinks.push(task.link);
  6947. }
  6948. if (action === 'do' && !task.is_success) {
  6949. this.undoneTasks.vk.nameLinks.push(task.link);
  6950. }
  6951. break;
  6952.  
  6953. case 'website':
  6954. break;
  6955.  
  6956. default:
  6957. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${social}`);
  6958. break;
  6959. }
  6960. }
  6961. logStatus.success();
  6962. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  6963. this.socialTasks = this.uniqueTasks(this.socialTasks);
  6964. if (window.DEBUG) {
  6965. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  6966. }
  6967. GM_setValue(`fawTasks-${this.giveawayId}`, {
  6968. tasks: this.socialTasks,
  6969. time: new Date().getTime()
  6970. });
  6971. return true;
  6972. }
  6973. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6974. return false;
  6975. }
  6976. logStatus.error(`${result}:${statusText}(${status})`);
  6977. return false;
  6978. } catch (error) {
  6979. throwError(error, 'Freeanywhere.classifyTask');
  6980. return false;
  6981. }
  6982. }
  6983. async verifyTask() {
  6984. try {
  6985. if (!this.initialized && !this.init()) {
  6986. return false;
  6987. }
  6988. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  6989. return false;
  6990. }
  6991. const pro = [];
  6992. for (const task of this.tasks) {
  6993. pro.push(this.#verify(task));
  6994. await delay(1e3);
  6995. }
  6996. await Promise.all(pro);
  6997. scripts_echoLog({}).success(i18n('allTasksComplete'));
  6998. return !!await this.getKey(true);
  6999. } catch (error) {
  7000. throwError(error, 'Freeanywhere.verifyTask');
  7001. return false;
  7002. }
  7003. }
  7004. async getKey(initialized) {
  7005. try {
  7006. if (!initialized && !this.initialized && !this.init()) {
  7007. return false;
  7008. }
  7009. const logStatus = scripts_echoLog({
  7010. text: i18n('gettingKey')
  7011. });
  7012. const {
  7013. result,
  7014. statusText,
  7015. status,
  7016. data
  7017. } = await tools_httpRequest({
  7018. url: `https://freeanywhere.net/api/v1/giveaway/${this.giveawayId}/reward/?format=json`,
  7019. method: 'GET',
  7020. dataType: 'json',
  7021. headers: {
  7022. authorization: `Token ${window.localStorage.getItem('token')}`
  7023. }
  7024. });
  7025. if (result === 'Success') {
  7026. if (data?.response?.reward) {
  7027. logStatus.success();
  7028. scripts_echoLog({}).success(data.response.reward);
  7029. return data.response.reward;
  7030. }
  7031. if (data?.response?.completed === false) {
  7032. logStatus.error(i18n('tasksNotCompleted'));
  7033. return false;
  7034. }
  7035. if (data?.response?.completed === true) {
  7036. await this.#checkLeftKey();
  7037. }
  7038. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7039. return false;
  7040. }
  7041. logStatus.error(`${result}:${statusText}(${status})`);
  7042. return false;
  7043. } catch (error) {
  7044. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7045. return false;
  7046. }
  7047. }
  7048. #getGiveawayId() {
  7049. try {
  7050. const giveawayId = window.location.href.match(/\/giveaway\/([\d]+)/)?.[1];
  7051. if (giveawayId) {
  7052. this.giveawayId = giveawayId;
  7053. return true;
  7054. }
  7055. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  7056. return false;
  7057. } catch (error) {
  7058. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7059. return false;
  7060. }
  7061. }
  7062. async #verify(task) {
  7063. try {
  7064. const logStatus = scripts_echoLog({
  7065. html: `<li>${i18n('verifyingTask')}${task.title.trim()}...<font></font></li>`
  7066. });
  7067. const {
  7068. result,
  7069. statusText,
  7070. status,
  7071. data
  7072. } = await tools_httpRequest({
  7073. url: `https://freeanywhere.net/api/v1/giveaway/${this.giveawayId}/challenge-status/${task.id}/?format=json`,
  7074. method: 'GET',
  7075. dataType: 'json',
  7076. headers: {
  7077. authorization: `Token ${window.localStorage.getItem('token')}`,
  7078. 'x-csrftoken': external_Cookies_default().get('csrftoken')
  7079. }
  7080. });
  7081. if (result === 'Success') {
  7082. if (data?.response?.status) {
  7083. logStatus.success();
  7084. return true;
  7085. }
  7086. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7087. return false;
  7088. }
  7089. logStatus.error(`${result}:${statusText}(${status})`);
  7090. return false;
  7091. } catch (error) {
  7092. throwError(error, 'Freeanywhere.verify');
  7093. return false;
  7094. }
  7095. }
  7096. async #checkLeftKey() {
  7097. try {
  7098. if (!globalOptions.other.checkLeftKey) {
  7099. return true;
  7100. }
  7101. const {
  7102. data
  7103. } = await tools_httpRequest({
  7104. url: 'https://freeanywhere.net/api/v1/widget/?format=json',
  7105. method: 'GET',
  7106. dataType: 'json',
  7107. headers: {
  7108. authorization: `Token ${window.localStorage.getItem('token')}`
  7109. }
  7110. });
  7111. if (data?.response?.giveaways.find(giveaway => `${giveaway?.id}` === this.giveawayId)) {
  7112. return true;
  7113. }
  7114. await external_Swal_default().fire({
  7115. icon: 'warning',
  7116. title: i18n('notice'),
  7117. text: i18n('noKeysLeft'),
  7118. confirmButtonText: i18n('confirm'),
  7119. cancelButtonText: i18n('cancel'),
  7120. showCancelButton: true
  7121. }).then(({
  7122. value
  7123. }) => {
  7124. if (value) {
  7125. window.close();
  7126. }
  7127. });
  7128. return true;
  7129. } catch (error) {
  7130. throwError(error, 'Giveawaysu.checkLeftKey');
  7131. return false;
  7132. }
  7133. }
  7134. }
  7135. const Freeanywhere = FreeAnyWhere;
  7136. const Giveawaysu_defaultTasks = {
  7137. steam: {
  7138. groupLinks: [],
  7139. wishlistLinks: [],
  7140. curatorLinks: [],
  7141. curatorLikeLinks: [],
  7142. followLinks: [],
  7143. forumLinks: [],
  7144. announcementLinks: [],
  7145. workshopVoteLinks: [],
  7146. playtestLinks: []
  7147. },
  7148. discord: {
  7149. serverLinks: []
  7150. },
  7151. instagram: {
  7152. userLinks: []
  7153. },
  7154. vk: {
  7155. nameLinks: []
  7156. },
  7157. twitch: {
  7158. channelLinks: []
  7159. },
  7160. reddit: {
  7161. redditLinks: []
  7162. },
  7163. youtube: {
  7164. channelLinks: [],
  7165. likeLinks: []
  7166. },
  7167. twitter: {
  7168. userLinks: [],
  7169. retweetLinks: []
  7170. }
  7171. };
  7172. class GiveawaySu extends website_Website {
  7173. name = 'GiveawaySu';
  7174. socialTasks = Giveawaysu_defaultTasks;
  7175. undoneTasks = Giveawaysu_defaultTasks;
  7176. buttons = [ 'doTask', 'undoTask' ];
  7177. static test() {
  7178. return /^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(window.location.href);
  7179. }
  7180. async after() {
  7181. try {
  7182. if (!this.#checkLogin()) {
  7183. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7184. }
  7185. if (!await this.#checkLeftKey()) {
  7186. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7187. }
  7188. scripts_echoLog({}).warning(i18n('gsNotice'));
  7189. } catch (error) {
  7190. throwError(error, 'Giveawaysu.after');
  7191. }
  7192. }
  7193. init() {
  7194. try {
  7195. const logStatus = scripts_echoLog({
  7196. text: i18n('initing')
  7197. });
  7198. if ($('a.steam-login').length > 0) {
  7199. window.open('/steam/redirect', '_self');
  7200. logStatus.warning(i18n('needLogin'));
  7201. return false;
  7202. }
  7203. if (!this.#getGiveawayId()) {
  7204. return false;
  7205. }
  7206. this.initialized = true;
  7207. logStatus.success();
  7208. return true;
  7209. } catch (error) {
  7210. throwError(error, 'Giveawaysu.init');
  7211. return false;
  7212. }
  7213. }
  7214. async classifyTask(action) {
  7215. try {
  7216. const logStatus = scripts_echoLog({
  7217. text: i18n('getTasksInfo')
  7218. });
  7219. if (action === 'undo') {
  7220. this.socialTasks = GM_getValue(`gasTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  7221. return true;
  7222. }
  7223. const pro = [];
  7224. const tasks = $('#actions tr');
  7225. if ($('div.bind-discord').is(':visible')) {
  7226. $('div.bind-discord a')[0].click();
  7227. }
  7228. if ($('div.bind-twitch').is(':visible')) {
  7229. $('div.bind-twitch a')[0].click();
  7230. }
  7231. for (const task of tasks) {
  7232. pro.push(new Promise(resolve => {
  7233. const td = $(task).find('td:not(".hidden")');
  7234. const colorfulTask = td.eq(1).find('a:not([data-trigger="link"])');
  7235. const colorlessTask = td.eq(2).find('a:not([data-trigger="link"])');
  7236. const taskDes = colorfulTask.length > 0 ? colorfulTask : colorlessTask;
  7237. const taskIcon = td.eq(0).find('i').attr('class') || '';
  7238. const taskName = taskDes.text().trim();
  7239. if (taskIcon.includes('ban') || /disable adblock/gi.test(taskName)) {
  7240. return resolve(true);
  7241. }
  7242. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  7243. if (!taskLink) {
  7244. return resolve(false);
  7245. }
  7246. if (taskIcon.includes('steam') && /join/gi.test(taskName)) {
  7247. this.undoneTasks.steam.groupLinks.push(taskLink);
  7248. } else if (/like.*announcement/gi.test(taskName)) {
  7249. this.undoneTasks.steam.announcementLinks.push(taskLink);
  7250. } else if (/(follow|subscribe).*curator/gim.test(taskName) && /^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  7251. this.undoneTasks.steam.curatorLinks.push(taskLink);
  7252. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  7253. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  7254. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  7255. this.undoneTasks.steam.forumLinks.push(taskLink);
  7256. } else if (taskIcon.includes('thumbs-up') && /^https?:\/\/steamcommunity\.com\/sharedfiles\/filedetails\/\?id=[\d]+/.test(taskLink)) {
  7257. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7258. } else if (taskIcon.includes('plus') && /request.*playtest/gim.test(taskName)) {
  7259. this.undoneTasks.steam.playtestLinks.push(taskLink);
  7260. } else if (taskIcon.includes('discord') || /join.*discord/gim.test(taskName)) {
  7261. this.undoneTasks.discord.serverLinks.push(taskLink);
  7262. } else if (taskIcon.includes('instagram') || /follow.*instagram/gim.test(taskName)) {
  7263. this.undoneTasks.instagram.userLinks.push(taskLink);
  7264. } else if (taskIcon.includes('twitch') || /follow.*twitch.*channel/gim.test(taskName)) {
  7265. this.undoneTasks.twitch.channelLinks.push(taskLink);
  7266. } else if (taskIcon.includes('reddit') || /subscribe.*subreddit/gim.test(taskName) || /follow.*reddit/gim.test(taskName)) {
  7267. this.undoneTasks.reddit.redditLinks.push(taskLink);
  7268. } else if (/watch.*art/gim.test(taskName)) {
  7269. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7270. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  7271. this.undoneTasks.youtube.channelLinks.push(taskLink);
  7272. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  7273. this.undoneTasks.youtube.likeLinks.push(taskLink);
  7274. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  7275. this.undoneTasks.vk.nameLinks.push(taskLink);
  7276. } else {
  7277. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  7278. if (/wishlist.*game|add.*wishlist/gim.test(taskName)) {
  7279. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  7280. }
  7281. if (/follow.*button/gim.test(taskName)) {
  7282. this.undoneTasks.steam.followLinks.push(taskLink);
  7283. }
  7284. }
  7285. }
  7286. resolve(true);
  7287. }).catch(error => {
  7288. throwError(error, 'Giveawaysu.classifyTask->getRedirectLink');
  7289. return false;
  7290. });
  7291. }));
  7292. }
  7293. await Promise.all(pro);
  7294. logStatus.success();
  7295. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7296. this.socialTasks = this.undoneTasks;
  7297. if (window.DEBUG) {
  7298. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7299. }
  7300. GM_setValue(`gasTasks-${this.giveawayId}`, {
  7301. tasks: this.socialTasks,
  7302. time: new Date().getTime()
  7303. });
  7304. return true;
  7305. } catch (error) {
  7306. throwError(error, 'Giveawaysu.classifyTask');
  7307. return false;
  7308. }
  7309. }
  7310. #checkLogin() {
  7311. try {
  7312. if (!globalOptions.other.checkLogin) {
  7313. return true;
  7314. }
  7315. if ($('a.steam-login').length > 0) {
  7316. window.open('/steam/redirect', '_self');
  7317. }
  7318. return true;
  7319. } catch (error) {
  7320. throwError(error, 'Giveawaysu.checkLogin');
  7321. return false;
  7322. }
  7323. }
  7324. async #checkLeftKey() {
  7325. try {
  7326. if (!globalOptions.other.checkLeftKey) {
  7327. return true;
  7328. }
  7329. if ($('.giveaway-ended').length > 0 && $('.giveaway-key').length === 0) {
  7330. await external_Swal_default().fire({
  7331. icon: 'warning',
  7332. title: i18n('notice'),
  7333. text: i18n('noKeysLeft'),
  7334. confirmButtonText: i18n('confirm'),
  7335. cancelButtonText: i18n('cancel'),
  7336. showCancelButton: true
  7337. }).then(({
  7338. value
  7339. }) => {
  7340. if (value) {
  7341. window.close();
  7342. }
  7343. });
  7344. }
  7345. return true;
  7346. } catch (error) {
  7347. throwError(error, 'Giveawaysu.checkLeftKey');
  7348. return false;
  7349. }
  7350. }
  7351. #getGiveawayId() {
  7352. try {
  7353. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  7354. if (giveawayId) {
  7355. this.giveawayId = giveawayId;
  7356. return true;
  7357. }
  7358. scripts_echoLog({
  7359. text: i18n('getFailed', 'GiveawayId')
  7360. });
  7361. return false;
  7362. } catch (error) {
  7363. throwError(error, 'Giveawaysu.getGiveawayId');
  7364. return false;
  7365. }
  7366. }
  7367. }
  7368. class Indiedb {
  7369. name = 'Indiedb';
  7370. buttons = [ 'doTask' ];
  7371. static test() {
  7372. return window.location.host === 'www.indiedb.com';
  7373. }
  7374. async after() {
  7375. try {
  7376. if (!this.#checkLogin()) {
  7377. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7378. }
  7379. if (!await this.#checkLeftKey()) {
  7380. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7381. }
  7382. } catch (error) {
  7383. throwError(error, 'Indiedb.after');
  7384. }
  7385. }
  7386. async doTask() {
  7387. try {
  7388. if (!await this.#join()) {
  7389. return false;
  7390. }
  7391. return await this.#do();
  7392. } catch (error) {
  7393. throwError(error, 'Indiedb.doTask');
  7394. return false;
  7395. }
  7396. }
  7397. async #join() {
  7398. try {
  7399. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7400. scripts_echoLog({}).error(i18n('needLogin'));
  7401. return false;
  7402. }
  7403. const currentoption = $('a.buttonenter.buttongiveaway');
  7404. if (/join giveaway/gim.test(currentoption.text())) {
  7405. const logStatus = scripts_echoLog({
  7406. text: `${i18n('joiningGiveaway')}...`
  7407. });
  7408. const {
  7409. result,
  7410. statusText,
  7411. status,
  7412. data
  7413. } = await tools_httpRequest({
  7414. url: currentoption.attr('href'),
  7415. method: 'POST',
  7416. data: 'ajax=t',
  7417. dataType: 'json',
  7418. headers: {
  7419. 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
  7420. accept: 'application/json, text/javascript, */*; q=0.01',
  7421. origin: window.location.origin
  7422. }
  7423. });
  7424. if (result === 'Success') {
  7425. if (data?.status === 200) {
  7426. if (data.response?.success) {
  7427. currentoption.addClass('buttonentered').text('Success - Giveaway joined');
  7428. $('#giveawaysjoined').slideDown();
  7429. $('#giveawaysrecommend').slideDown();
  7430. logStatus.success(`Success${data.response?.text ? `:${data.response?.text}` : ''}`);
  7431. return true;
  7432. }
  7433. logStatus.error(`Error${data.response?.text ? `:${data.response?.text}` : ''}`);
  7434. return false;
  7435. }
  7436. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7437. return false;
  7438. }
  7439. logStatus.error(`${result}:${statusText}(${status})`);
  7440. return false;
  7441. } else if (/success/gim.test($('a.buttonenter.buttongiveaway').text())) {
  7442. return true;
  7443. }
  7444. scripts_echoLog({}).warning(i18n('needJoinGiveaway'));
  7445. return false;
  7446. } catch (error) {
  7447. throwError(error, 'Indiedb.init');
  7448. return false;
  7449. }
  7450. }
  7451. async #do() {
  7452. try {
  7453. const id = $('script').map((index, script) => {
  7454. if (/\$\(document\)/gim.test(script.innerHTML)) {
  7455. return [ script.innerHTML.match(/"\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0], script.innerHTML.match(/"\/newsletter\/ajax\/subscribeprofile\/optin\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0] ];
  7456. }
  7457. return null;
  7458. });
  7459. if (id.length === 2) {
  7460. const pro = [];
  7461. const tasks = $('#giveawaysjoined a[class*=promo]');
  7462. for (const task of tasks) {
  7463. const promo = $(task);
  7464. if (!promo.hasClass('buttonentered')) {
  7465. const status = scripts_echoLog({
  7466. text: `${i18n('doing')}:${promo.parents('p').text()}...`
  7467. });
  7468. if (/facebookpromo|twitterpromo|visitpromo/gim.test(task.className)) {
  7469. let text = '';
  7470. if (promo.hasClass('facebookpromo')) {
  7471. text = 'facebookpromo';
  7472. } else if (promo.hasClass('twitterpromo')) {
  7473. text = 'twitterpromo';
  7474. } else {
  7475. text = 'visitpromo';
  7476. }
  7477. pro.push(new Promise(resolve => {
  7478. $.ajax({
  7479. type: 'POST',
  7480. url: urlPath(`/giveaways/ajax/${text}/${id[0]}`),
  7481. timeout: 6e4,
  7482. dataType: 'json',
  7483. data: {
  7484. ajax: 't'
  7485. },
  7486. error(response, error, exception) {
  7487. if (window.DEBUG) {
  7488. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7489. response: response,
  7490. error: error,
  7491. exception: exception
  7492. });
  7493. }
  7494. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7495. resolve(true);
  7496. },
  7497. success(response) {
  7498. if (response.success) {
  7499. status.success(`Success:${response.text}`);
  7500. promo.addClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7501. resolve(true);
  7502. } else {
  7503. status.error(`Error:${response.text}`);
  7504. resolve(true);
  7505. }
  7506. }
  7507. });
  7508. }));
  7509. } else if (promo.hasClass('emailoptinpromo')) {
  7510. pro.push(new Promise(resolve => {
  7511. $.ajax({
  7512. type: 'POST',
  7513. url: urlPath(`/newsletter/ajax/subscribeprofile/optin/${id[1]}`),
  7514. timeout: 6e4,
  7515. dataType: 'json',
  7516. data: {
  7517. ajax: 't',
  7518. emailsystoggle: 4
  7519. },
  7520. error(response, error, exception) {
  7521. if (window.DEBUG) {
  7522. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7523. response: response,
  7524. error: error,
  7525. exception: exception
  7526. });
  7527. }
  7528. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7529. resolve(true);
  7530. },
  7531. success(response) {
  7532. if (response.success) {
  7533. status.success(`Success:${response.text}`);
  7534. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7535. resolve(true);
  7536. } else {
  7537. status.error(`Error:${response.text}`);
  7538. resolve(true);
  7539. }
  7540. }
  7541. });
  7542. }));
  7543. } else if (promo.hasClass('watchingpromo')) {
  7544. pro.push(new Promise(resolve => {
  7545. const data = getUrlQuery(promo.attr('href'));
  7546. data.ajax = 't';
  7547. $.ajax({
  7548. type: 'POST',
  7549. url: urlPath(promo.attr('href')?.split(/[?#]/)[0]),
  7550. timeout: 6e4,
  7551. dataType: 'json',
  7552. data: data,
  7553. error(response, error, exception) {
  7554. if (window.DEBUG) {
  7555. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7556. response: response,
  7557. error: error,
  7558. exception: exception
  7559. });
  7560. }
  7561. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7562. resolve(true);
  7563. },
  7564. success(response) {
  7565. if (response.success) {
  7566. status.success(`Success:${response.text}`);
  7567. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7568. resolve(true);
  7569. } else {
  7570. status.error(`Error:${response.text}`);
  7571. resolve(true);
  7572. }
  7573. }
  7574. });
  7575. }));
  7576. } else if (!/the-challenge-of-adblock/gim.test(promo.attr('href'))) {
  7577. pro.push(new Promise(resolve => {
  7578. $.ajax({
  7579. type: 'POST',
  7580. url: urlPath(promo.attr('href')),
  7581. timeout: 6e4,
  7582. dataType: 'json',
  7583. data: {
  7584. ajax: 't'
  7585. },
  7586. error(response, error, exception) {
  7587. if (window.DEBUG) {
  7588. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7589. response: response,
  7590. error: error,
  7591. exception: exception
  7592. });
  7593. }
  7594. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7595. resolve(true);
  7596. },
  7597. success(response) {
  7598. if (response.success) {
  7599. status.success(`Success:${response.text}`);
  7600. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7601. resolve(true);
  7602. } else {
  7603. status.error(`Error:${response.text}`);
  7604. resolve(true);
  7605. }
  7606. }
  7607. });
  7608. }));
  7609. } else {
  7610. status.error(`Error:${i18n('unKnownTaskType')}`);
  7611. }
  7612. }
  7613. }
  7614. await Promise.all(pro);
  7615. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7616. return true;
  7617. }
  7618. scripts_echoLog({}).error(i18n('getFailed', 'TaskId'));
  7619. return false;
  7620. } catch (error) {
  7621. throwError(error, 'Indiedb.classifyTask');
  7622. return false;
  7623. }
  7624. }
  7625. #checkLogin() {
  7626. try {
  7627. if (!globalOptions.other.checkLogin) {
  7628. return true;
  7629. }
  7630. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7631. window.open('/members/login', '_self');
  7632. }
  7633. return true;
  7634. } catch (error) {
  7635. throwError(error, 'Indiedb.checkLogin');
  7636. return false;
  7637. }
  7638. }
  7639. async #checkLeftKey() {
  7640. try {
  7641. if (!globalOptions.other.checkLeftKey) {
  7642. return true;
  7643. }
  7644. if ($('a.buttonenter:contains("next time"), a.buttonenter:contains("Giveaway is closed")').length > 0) {
  7645. await external_Swal_default().fire({
  7646. icon: 'warning',
  7647. title: i18n('notice'),
  7648. text: i18n('giveawayEnded'),
  7649. confirmButtonText: i18n('confirm'),
  7650. cancelButtonText: i18n('cancel'),
  7651. showCancelButton: true
  7652. }).then(({
  7653. value
  7654. }) => {
  7655. if (value) {
  7656. window.close();
  7657. }
  7658. });
  7659. }
  7660. return true;
  7661. } catch (error) {
  7662. throwError(error, 'Indiedb.checkLeftKey');
  7663. return false;
  7664. }
  7665. }
  7666. }
  7667. const website_Indiedb = Indiedb;
  7668. const Keyhub_defaultTasksTemplate = {
  7669. steam: {
  7670. groupLinks: [],
  7671. officialGroupLinks: [],
  7672. wishlistLinks: [],
  7673. curatorLinks: []
  7674. },
  7675. discord: {
  7676. serverLinks: []
  7677. },
  7678. extra: {
  7679. videoTasks: []
  7680. },
  7681. links: []
  7682. };
  7683. const Keyhub_defaultTasks = JSON.stringify(Keyhub_defaultTasksTemplate);
  7684. class Keyhub extends website_Website {
  7685. name = 'Keyhub';
  7686. socialTasks = JSON.parse(Keyhub_defaultTasks);
  7687. undoneTasks = JSON.parse(Keyhub_defaultTasks);
  7688. buttons = [ 'doTask', 'undoTask' ];
  7689. static test() {
  7690. return window.location.host === 'key-hub.eu';
  7691. }
  7692. async after() {
  7693. try {
  7694. if (!this.#checkLogin()) {
  7695. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7696. }
  7697. if (!await this.#checkLeftKey()) {
  7698. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7699. }
  7700. $('.NSFW').hide();
  7701. } catch (error) {
  7702. throwError(error, 'Keyhub.after');
  7703. }
  7704. }
  7705. init() {
  7706. try {
  7707. const logStatus = scripts_echoLog({
  7708. text: i18n('initing')
  7709. });
  7710. if ($('a[href*="/connect/steam"]').length > 0) {
  7711. window.open('/connect/steam', '_self');
  7712. logStatus.warning(i18n('needLogin'));
  7713. return false;
  7714. }
  7715. if (!this.#getGiveawayId()) {
  7716. return false;
  7717. }
  7718. $('#VPNoverlay').hide();
  7719. $('#mainArticleSection').show();
  7720. this.initialized = true;
  7721. logStatus.success();
  7722. return true;
  7723. } catch (error) {
  7724. throwError(error, 'Keyhub.init');
  7725. return false;
  7726. }
  7727. }
  7728. async classifyTask(action) {
  7729. try {
  7730. const logStatus = scripts_echoLog({
  7731. text: i18n('getTasksInfo')
  7732. });
  7733. if (action === 'undo') {
  7734. this.socialTasks = GM_getValue(`khTasks-${this.giveawayId}`)?.tasks || JSON.parse(Keyhub_defaultTasks);
  7735. }
  7736. const tasks = $('.task:not(".googleads")').filter((index, element) => action === 'do' ? $(element).find('i.fa-check-circle:visible').length === 0 : true).find('a');
  7737. for (const task of tasks) {
  7738. let link = $(task).attr('href');
  7739. const taskDes = $(task).text().trim();
  7740. if (!link) {
  7741. continue;
  7742. }
  7743. if (/\/away\?data=/.test(link) || /steamcommunity\.com\/gid\//.test(link)) {
  7744. link = await getRedirectLink(link) || link;
  7745. }
  7746. if (/https?:\/\/key-hub\.eu\/connect\/discord/.test(link)) {
  7747. GM_openInTab(link, {
  7748. active: true
  7749. });
  7750. } else if (/steamcommunity\.com\/groups\//.test(link)) {
  7751. if (action === 'undo') {
  7752. this.socialTasks.steam.groupLinks.push(link);
  7753. }
  7754. if (action === 'do') {
  7755. this.undoneTasks.steam.groupLinks.push(link);
  7756. }
  7757. } else if (/steamcommunity\.com\/games\/[\d]+/.test(link)) {
  7758. if (action === 'undo') {
  7759. this.socialTasks.steam.officialGroupLinks.push(link);
  7760. }
  7761. if (action === 'do') {
  7762. this.undoneTasks.steam.officialGroupLinks.push(link);
  7763. }
  7764. } else if (/store\.steampowered\.com\/app\//.test(link) && /wishlist/gim.test(taskDes)) {
  7765. if (action === 'undo') {
  7766. this.socialTasks.steam.wishlistLinks.push(link);
  7767. }
  7768. if (action === 'do') {
  7769. this.undoneTasks.steam.wishlistLinks.push(link);
  7770. }
  7771. } else if (/store\.steampowered\.com\/curator\//.test(link)) {
  7772. if (action === 'undo') {
  7773. this.socialTasks.steam.curatorLinks.push(link);
  7774. }
  7775. if (action === 'do') {
  7776. this.undoneTasks.steam.curatorLinks.push(link);
  7777. }
  7778. } else if (/^https?:\/\/discord\.com\/invite\//.test(link)) {
  7779. if (action === 'undo') {
  7780. this.socialTasks.discord.serverLinks.push(link);
  7781. }
  7782. if (action === 'do') {
  7783. this.undoneTasks.discord.serverLinks.push(link);
  7784. }
  7785. } else if (/^javascript:videoTask.+/.test(link)) {
  7786. if (action === 'do') {
  7787. const taskData = link.match(/javascript:videoTask\('.+?','(.+?)'/)?.[1];
  7788. if (taskData) {
  7789. this.undoneTasks.extra.videoTasks.push(taskData);
  7790. }
  7791. }
  7792. } 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 {
  7793. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  7794. }
  7795. }
  7796. logStatus.success();
  7797. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7798. this.socialTasks = this.uniqueTasks(this.socialTasks);
  7799. if (window.DEBUG) {
  7800. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7801. }
  7802. GM_setValue(`khTasks-${this.giveawayId}`, {
  7803. tasks: this.socialTasks,
  7804. time: new Date().getTime()
  7805. });
  7806. return true;
  7807. } catch (error) {
  7808. throwError(error, 'Keyhub.classifyTask');
  7809. return false;
  7810. }
  7811. }
  7812. async #doScriptTask(data) {
  7813. try {
  7814. const logStatus = scripts_echoLog({
  7815. text: i18n('doingKeyhubTask')
  7816. });
  7817. const {
  7818. result,
  7819. statusText,
  7820. status,
  7821. data: response
  7822. } = await tools_httpRequest({
  7823. url: `/away?data=${data}`,
  7824. method: 'GET',
  7825. headers: {
  7826. origin: 'https://key-hub.eu',
  7827. referer: 'https://key-hub.eu/'
  7828. }
  7829. });
  7830. if (result === 'Success') {
  7831. if (response?.status === 200) {
  7832. logStatus.success();
  7833. return true;
  7834. }
  7835. logStatus.error(`Error:${response?.statusText}(${response?.status})`);
  7836. return false;
  7837. }
  7838. logStatus.error(`${result}:${statusText}(${status})`);
  7839. return false;
  7840. } catch (error) {
  7841. throwError(error, 'Keyhub.doScriptTask');
  7842. return false;
  7843. }
  7844. }
  7845. async extraDoTask({
  7846. videoTasks
  7847. }) {
  7848. try {
  7849. const pro = [];
  7850. for (const data of videoTasks) {
  7851. pro.push(this.#doScriptTask(data));
  7852. }
  7853. return Promise.all(pro).then(() => true);
  7854. } catch (error) {
  7855. throwError(error, 'Keyhub.extraDoTask');
  7856. return false;
  7857. }
  7858. }
  7859. #getGiveawayId() {
  7860. try {
  7861. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  7862. if (giveawayId) {
  7863. this.giveawayId = giveawayId;
  7864. return true;
  7865. }
  7866. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  7867. return false;
  7868. } catch (error) {
  7869. throwError(error, 'Keyhub.getGiveawayId');
  7870. return false;
  7871. }
  7872. }
  7873. async #checkLeftKey() {
  7874. try {
  7875. if (!globalOptions.other.checkLeftKey) {
  7876. return true;
  7877. }
  7878. const leftKey = $('#keysleft').text().trim();
  7879. if (leftKey === '0') {
  7880. await external_Swal_default().fire({
  7881. icon: 'warning',
  7882. title: i18n('notice'),
  7883. text: i18n('noKeysLeft'),
  7884. confirmButtonText: i18n('confirm'),
  7885. cancelButtonText: i18n('cancel'),
  7886. showCancelButton: true
  7887. }).then(({
  7888. value
  7889. }) => {
  7890. if (value) {
  7891. window.close();
  7892. }
  7893. });
  7894. }
  7895. return true;
  7896. } catch (error) {
  7897. throwError(error, 'Keyhub.checkLeftKey');
  7898. return false;
  7899. }
  7900. }
  7901. #checkLogin() {
  7902. try {
  7903. if (!globalOptions.other.checkLogin) {
  7904. return true;
  7905. }
  7906. if ($('a[href*="/connect/steam"]').length > 0) {
  7907. window.open('/connect/steam', '_self');
  7908. }
  7909. return true;
  7910. } catch (error) {
  7911. throwError(error, 'Keyhub.checkLogin');
  7912. return false;
  7913. }
  7914. }
  7915. }
  7916. const website_Keyhub = Keyhub;
  7917. const Givekey_defaultTasksTemplate = {
  7918. steam: {
  7919. groupLinks: [],
  7920. wishlistLinks: [],
  7921. curatorLinks: [],
  7922. curatorLikeLinks: []
  7923. },
  7924. twitter: {
  7925. userLinks: []
  7926. },
  7927. vk: {
  7928. nameLinks: []
  7929. },
  7930. discord: {
  7931. serverLinks: []
  7932. }
  7933. };
  7934. const Givekey_defaultTasks = JSON.stringify(Givekey_defaultTasksTemplate);
  7935. class Givekey extends website_Website {
  7936. name = 'Givekey';
  7937. tasks = [];
  7938. socialTasks = JSON.parse(Givekey_defaultTasks);
  7939. undoneTasks = JSON.parse(Givekey_defaultTasks);
  7940. userId;
  7941. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  7942. static test() {
  7943. return window.location.host === 'givekey.ru';
  7944. }
  7945. async after() {
  7946. try {
  7947. await new Promise(resolve => {
  7948. const checker = setInterval(() => {
  7949. if ($('#navbarDropdown').length > 0) {
  7950. clearInterval(checker);
  7951. resolve(true);
  7952. }
  7953. }, 500);
  7954. });
  7955. if (!await this.#checkLeftKey()) {
  7956. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7957. }
  7958. } catch (error) {
  7959. throwError(error, 'Givekey.after');
  7960. }
  7961. }
  7962. init() {
  7963. try {
  7964. const logStatus = scripts_echoLog({
  7965. text: i18n('initing')
  7966. });
  7967. if ($('a[href*="/auth/steam"]').length > 0) {
  7968. window.open('/auth/steam', '_self');
  7969. logStatus.warning(i18n('needLogin'));
  7970. return false;
  7971. }
  7972. if (!this.#getGiveawayId()) {
  7973. return false;
  7974. }
  7975. const userId = $('meta[name="user-id"]').attr('content');
  7976. if (!userId) {
  7977. logStatus.error(i18n('getFailed', i18n('userId')));
  7978. return false;
  7979. }
  7980. this.userId = userId;
  7981. this.initialized = true;
  7982. logStatus.success();
  7983. return true;
  7984. } catch (error) {
  7985. throwError(error, 'Givekey.init');
  7986. return false;
  7987. }
  7988. }
  7989. async classifyTask(action) {
  7990. try {
  7991. const logStatus = scripts_echoLog({
  7992. text: i18n('getTasksInfo')
  7993. });
  7994. if (action === 'undo') {
  7995. this.socialTasks = GM_getValue(`gkTasks-${this.giveawayId}`)?.tasks || JSON.parse(Givekey_defaultTasks);
  7996. }
  7997. const tasks = $('.card-body:has("button") .row');
  7998. for (const task of tasks) {
  7999. const taskEle = $(task);
  8000. const isSuccess = /Complete/i.test(taskEle.find('button').text().trim());
  8001. if (isSuccess && action !== 'undo') {
  8002. continue;
  8003. }
  8004. const checkButton = taskEle.find('#task_check');
  8005. const taskId = checkButton.attr('data-id');
  8006. if (taskId) {
  8007. this.tasks.push(taskId);
  8008. }
  8009. if (action === 'verify') {
  8010. continue;
  8011. }
  8012. let href = taskEle.find('a').attr('href') || null;
  8013. const text = taskEle.find('a').text().trim();
  8014. const icon = taskEle.find('i');
  8015. if (!href || !text) {
  8016. continue;
  8017. }
  8018. if (/^https?:\/\/givekey\.ru\/giveaway\/[\d]+\/execution_task/.test(href)) {
  8019. href = await getRedirectLink(href);
  8020. }
  8021. if (!href) {
  8022. continue;
  8023. }
  8024. if (/^https?:\/\/vk\.com\//.test(href)) {
  8025. this.socialTasks.vk.nameLinks.push(href);
  8026. if (action === 'do' && !isSuccess) {
  8027. this.undoneTasks.vk.nameLinks.push(href);
  8028. }
  8029. } else if (/^https?:\/\/steamcommunity\.com\/groups/.test(href)) {
  8030. this.socialTasks.steam.groupLinks.push(href);
  8031. if (action === 'do' && !isSuccess) {
  8032. this.undoneTasks.steam.groupLinks.push(href);
  8033. }
  8034. } else if (/^https?:\/\/store\.steampowered\.com\/app\//.test(href)) {
  8035. this.socialTasks.steam.wishlistLinks.push(href);
  8036. if (action === 'do' && !isSuccess) {
  8037. this.undoneTasks.steam.wishlistLinks.push(href);
  8038. }
  8039. } else if (/Subscribe/gi.test(text) && icon.hasClass('fa-steam-square')) {
  8040. if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(href)) {
  8041. this.socialTasks.steam.curatorLinks.push(href);
  8042. if (action === 'do' && !isSuccess) {
  8043. this.undoneTasks.steam.curatorLinks.push(href);
  8044. }
  8045. } else {
  8046. this.socialTasks.steam.curatorLikeLinks.push(href);
  8047. if (action === 'do' && !isSuccess) {
  8048. this.undoneTasks.steam.curatorLikeLinks.push(href);
  8049. }
  8050. }
  8051. } else if (/^https?:\/\/twitter\.com\//.test(href) && /Subscribe/gi.test(text)) {
  8052. this.socialTasks.twitter.userLinks.push(href);
  8053. if (action === 'do' && !isSuccess) {
  8054. this.undoneTasks.twitter.userLinks.push(href);
  8055. }
  8056. } else if (icon.hasClass('fa-discord') || /^https?:\/\/discord\.com\/invite\//.test(href)) {
  8057. this.socialTasks.discord.serverLinks.push(href);
  8058. if (action === 'do' && !isSuccess) {
  8059. this.undoneTasks.discord.serverLinks.push(href);
  8060. }
  8061. } else {
  8062. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${text}(${href})`);
  8063. }
  8064. }
  8065. logStatus.success();
  8066. this.tasks = unique(this.tasks);
  8067. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8068. this.socialTasks = this.uniqueTasks(this.socialTasks);
  8069. if (window.DEBUG) {
  8070. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8071. }
  8072. GM_setValue(`gkTasks-${this.giveawayId}`, {
  8073. tasks: this.socialTasks,
  8074. time: new Date().getTime()
  8075. });
  8076. return true;
  8077. } catch (error) {
  8078. throwError(error, 'Givekey.classifyTask');
  8079. return false;
  8080. }
  8081. }
  8082. async verifyTask() {
  8083. try {
  8084. if (!this.initialized && !this.init()) {
  8085. return false;
  8086. }
  8087. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  8088. return false;
  8089. }
  8090. scripts_echoLog({}).warning(i18n('giveKeyNoticeBefore'));
  8091. const taskLength = this.tasks.length;
  8092. for (let i = 0; i < taskLength; i++) {
  8093. await this.#verify(this.tasks[i]);
  8094. if (i < taskLength - 1) {
  8095. await delay(15e3);
  8096. }
  8097. }
  8098. scripts_echoLog({}).success(i18n('allTasksComplete'));
  8099. scripts_echoLog({
  8100. html: `<li><font class="warning">${i18n('giveKeyNoticeAfter')}</font></li>`
  8101. });
  8102. return true;
  8103. } catch (error) {
  8104. throwError(error, 'Givekey.verifyTask');
  8105. return false;
  8106. }
  8107. }
  8108. async #verify(task) {
  8109. try {
  8110. const logStatus = scripts_echoLog({
  8111. html: `<li>${i18n('verifyingTask')}${task}...<font></font></li>`
  8112. });
  8113. return await new Promise(resolve => {
  8114. $.ajax({
  8115. url: 'https://givekey.ru/giveaway/task',
  8116. method: 'POST',
  8117. data: `id=${task}&user_id=${this.userId}`,
  8118. dataType: 'json',
  8119. headers: {
  8120. 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  8121. },
  8122. success: data => {
  8123. if (data.btn) {
  8124. $(`button[data-id=${this.userId}]`).html(data.btn);
  8125. }
  8126. if (data.status === 'ok') {
  8127. $(`.task_check_${data.id}`).html(`<button class="btn btn-success mb-2 btn-block" disabled>${data.btn}</button>`);
  8128. logStatus.success();
  8129. resolve(true);
  8130. } else if (data.status === 'end') {
  8131. logStatus.success();
  8132. scripts_echoLog({}).success(data.key);
  8133. resolve(true);
  8134. } else {
  8135. logStatus.error(`Error:${data.msg}`);
  8136. resolve(false);
  8137. }
  8138. },
  8139. error: xhr => {
  8140. logStatus.error(`Error:${xhr.statusText}(${xhr.status})`);
  8141. resolve(false);
  8142. }
  8143. });
  8144. });
  8145. } catch (error) {
  8146. throwError(error, 'Givekey.verify');
  8147. return false;
  8148. }
  8149. }
  8150. #getGiveawayId() {
  8151. try {
  8152. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  8153. if (giveawayId) {
  8154. this.giveawayId = giveawayId;
  8155. return true;
  8156. }
  8157. scripts_echoLog({
  8158. text: i18n('getFailed', 'GiveawayId')
  8159. });
  8160. return false;
  8161. } catch (error) {
  8162. throwError(error, 'Givekey.getGiveawayId');
  8163. return false;
  8164. }
  8165. }
  8166. async #checkLeftKey() {
  8167. try {
  8168. if (!globalOptions.other.checkLeftKey) {
  8169. return true;
  8170. }
  8171. if (!$('#keys_count').text()) {
  8172. await external_Swal_default().fire({
  8173. icon: 'warning',
  8174. title: i18n('notice'),
  8175. text: i18n('noKeysLeft'),
  8176. confirmButtonText: i18n('confirm'),
  8177. cancelButtonText: i18n('cancel'),
  8178. showCancelButton: true
  8179. }).then(({
  8180. value
  8181. }) => {
  8182. if (value) {
  8183. window.close();
  8184. }
  8185. });
  8186. }
  8187. return true;
  8188. } catch (error) {
  8189. throwError(error, 'Givekey.checkLeftKey');
  8190. return false;
  8191. }
  8192. }
  8193. }
  8194. const website_Givekey = Givekey;
  8195. class GiveeClub extends GiveawaySu {
  8196. name = 'GiveeClub';
  8197. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8198. static test() {
  8199. return /^https?:\/\/givee\.club\/.*?\/event\/[\d]+/.test(window.location.href);
  8200. }
  8201. async after() {
  8202. try {
  8203. if (!this.#checkLogin()) {
  8204. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8205. }
  8206. if (!await this.#checkLeftKey()) {
  8207. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8208. }
  8209. } catch (error) {
  8210. throwError(error, 'GiveeClub.after');
  8211. }
  8212. }
  8213. init() {
  8214. try {
  8215. const logStatus = scripts_echoLog({
  8216. text: i18n('initing')
  8217. });
  8218. if (!this.#checkLogin()) {
  8219. logStatus.warning(i18n('needLogin'));
  8220. return false;
  8221. }
  8222. if (!this.#getGiveawayId()) {
  8223. return false;
  8224. }
  8225. this.initialized = true;
  8226. logStatus.success();
  8227. return true;
  8228. } catch (error) {
  8229. throwError(error, 'GiveeClub.init');
  8230. return false;
  8231. }
  8232. }
  8233. async classifyTask(action) {
  8234. try {
  8235. const logStatus = scripts_echoLog({
  8236. text: i18n('getTasksInfo')
  8237. });
  8238. if (action === 'undo') {
  8239. this.socialTasks = GM_getValue(`gcTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  8240. return true;
  8241. }
  8242. this.undoneTasks = Giveawaysu_defaultTasks;
  8243. const pro = [];
  8244. const tasks = $('.event-actions tr');
  8245. for (const task of tasks) {
  8246. pro.push(new Promise(resolve => {
  8247. const taskDes = $(task).find('.event-action-label a');
  8248. const taskIcon = $(task).find('.event-action-icon i').attr('class') || '';
  8249. const taskName = taskDes.text().trim();
  8250. const taskType = $(task).find('button[data-type]')?.attr('data-type');
  8251. const taskFinished = $(task).find('.event-action-buttons .btn-success')?.length;
  8252. if (taskIcon.includes('ban') || /AdBlock/i.test(taskName) || taskIcon.includes('envelope') || taskFinished) {
  8253. return resolve(true);
  8254. }
  8255. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  8256. if (!taskLink) {
  8257. return resolve(false);
  8258. }
  8259. if (taskType === 'steam.group.join' && /^https?:\/\/steamcommunity\.com\/groups/.test(taskLink)) {
  8260. this.undoneTasks.steam.groupLinks.push(taskLink);
  8261. } else if (/like.*announcement/gi.test(taskName)) {
  8262. this.undoneTasks.steam.announcementLinks.push(taskLink);
  8263. } else if (taskType === 'steam.game.wishlist' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8264. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  8265. } else if (taskType === 'steam.game.wishlist' && taskDes.attr('data-steam-wishlist-appid')) {
  8266. this.undoneTasks.steam.wishlistLinks.push(`https://store.steampowered.com/app/${taskDes.attr('data-steam-wishlist-appid')}`);
  8267. } else if (taskType === 'steam.game.follow' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8268. this.undoneTasks.steam.followLinks.push(taskLink);
  8269. } else if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  8270. this.undoneTasks.steam.curatorLinks.push(taskLink);
  8271. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  8272. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  8273. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  8274. this.undoneTasks.steam.forumLinks.push(taskLink);
  8275. } else if (taskIcon.includes('discord')) {
  8276. this.undoneTasks.discord.serverLinks.push(taskLink);
  8277. } else if (taskIcon.includes('instagram')) {
  8278. this.undoneTasks.instagram.userLinks.push(taskLink);
  8279. } else if (taskIcon.includes('twitch')) {
  8280. this.undoneTasks.twitch.channelLinks.push(taskLink);
  8281. } else if (taskIcon.includes('reddit')) {
  8282. this.undoneTasks.reddit.redditLinks.push(taskLink);
  8283. } else if (/watch.*art/gim.test(taskName)) {
  8284. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  8285. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  8286. this.undoneTasks.youtube.channelLinks.push(taskLink);
  8287. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  8288. this.undoneTasks.youtube.likeLinks.push(taskLink);
  8289. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  8290. this.undoneTasks.vk.nameLinks.push(taskLink);
  8291. } else if (taskIcon.includes('twitter')) {
  8292. if (/https?:\/\/twitter\.com\/[^/]+\/?$/gim.test(taskLink)) {
  8293. this.undoneTasks.twitter.userLinks.push(taskLink);
  8294. } else if (/https?:\/\/twitter\.com\/[^/]+?\/status\/[\d]+/gim.test(taskLink)) {
  8295. this.undoneTasks.twitter.retweetLinks.push(taskLink);
  8296. }
  8297. } else {
  8298. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  8299. if (/follow.*button/gim.test(taskName)) {
  8300. this.undoneTasks.steam.followLinks.push(taskLink);
  8301. }
  8302. }
  8303. }
  8304. resolve(true);
  8305. }).catch(error => {
  8306. throwError(error, 'GiveeClub.classifyTask->getRedirectLink');
  8307. return false;
  8308. });
  8309. }));
  8310. }
  8311. await Promise.all(pro);
  8312. logStatus.success();
  8313. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8314. this.socialTasks = this.undoneTasks;
  8315. if (window.DEBUG) {
  8316. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8317. }
  8318. GM_setValue(`gcTasks-${this.giveawayId}`, {
  8319. tasks: this.socialTasks,
  8320. time: new Date().getTime()
  8321. });
  8322. return true;
  8323. } catch (error) {
  8324. throwError(error, 'GiveeClub.classifyTask');
  8325. return false;
  8326. }
  8327. }
  8328. async verifyTask() {
  8329. try {
  8330. const logStatus = scripts_echoLog({
  8331. text: i18n('giveeClubVerifyNotice')
  8332. });
  8333. const taskButtons = $('.event-actions tr button').has('i.glyphicon-refresh').not('[data-type="user.adblock"]');
  8334. for (const button of taskButtons) {
  8335. button.click();
  8336. if ($(button).attr('data-type') !== 'steam.game.wishlist') {
  8337. await delay(1e3);
  8338. }
  8339. }
  8340. logStatus.warning(i18n('giveeClubVerifyFinished'));
  8341. return true;
  8342. } catch (error) {
  8343. throwError(error, 'Givekey.verifyTask');
  8344. return false;
  8345. }
  8346. }
  8347. #checkLogin() {
  8348. try {
  8349. if (!globalOptions.other.checkLogin) {
  8350. return true;
  8351. }
  8352. if ($('a[href*="/account/auth"]').length > 0) {
  8353. window.open($('a[href*="/account/auth"]').attr('href'), '_self');
  8354. }
  8355. return true;
  8356. } catch (error) {
  8357. throwError(error, 'GiveeClub.checkLogin');
  8358. return false;
  8359. }
  8360. }
  8361. #getGiveawayId() {
  8362. const giveawayId = window.location.href.match(/\/event\/([\d]+)/)?.[1];
  8363. if (giveawayId) {
  8364. this.giveawayId = giveawayId;
  8365. return true;
  8366. }
  8367. scripts_echoLog({
  8368. text: i18n('getFailed', 'GiveawayId')
  8369. });
  8370. return false;
  8371. }
  8372. async #checkLeftKey() {
  8373. try {
  8374. if (!globalOptions.other.checkLeftKey) {
  8375. return true;
  8376. }
  8377. if ($('.event-ended').length > 0 && $('.event-winner').length === 0) {
  8378. await external_Swal_default().fire({
  8379. icon: 'warning',
  8380. title: i18n('notice'),
  8381. text: i18n('giveawayEnded'),
  8382. confirmButtonText: i18n('confirm'),
  8383. cancelButtonText: i18n('cancel'),
  8384. showCancelButton: true
  8385. }).then(({
  8386. value
  8387. }) => {
  8388. if (value) {
  8389. window.close();
  8390. }
  8391. });
  8392. }
  8393. return true;
  8394. } catch (error) {
  8395. throwError(error, 'Giveawaysu.checkLeftKey');
  8396. return false;
  8397. }
  8398. }
  8399. }
  8400. const website_GiveeClub = GiveeClub;
  8401. const defaultOptions = {
  8402. maxPoint: '99999999'
  8403. };
  8404. class OpiumPulses {
  8405. name = 'OpiumPulses';
  8406. options = {
  8407. ...defaultOptions,
  8408. ...GM_getValue('OpiumPulsesOptions')
  8409. };
  8410. maxPoints = 99999999;
  8411. myPoints = 0;
  8412. buttons = [ 'doFreeTask', 'doPointTask' ];
  8413. static test() {
  8414. return window.location.host === 'www.opiumpulses.com';
  8415. }
  8416. async after() {
  8417. try {
  8418. if (!this.#checkLogin()) {
  8419. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8420. }
  8421. this.maxPoints = parseInt(this.options.maxPoint, 10);
  8422. } catch (error) {
  8423. throwError(error, 'OpiumPulses.after');
  8424. }
  8425. }
  8426. async doFreeTask() {
  8427. try {
  8428. this.#toggleTask('FREE');
  8429. } catch (error) {
  8430. throwError(error, 'OpiumPulses.doFreeTask');
  8431. }
  8432. }
  8433. async doPointTask() {
  8434. try {
  8435. this.myPoints = parseInt($('.page-header__nav-func-user-nav-items.points-items').text().match(/[\d]+/gim)?.[0] || '0', 10);
  8436. this.#toggleTask('points');
  8437. } catch (error) {
  8438. throwError(error, 'OpiumPulses.doPointTask');
  8439. }
  8440. }
  8441. async #toggleTask(type) {
  8442. try {
  8443. const items = $(`.giveaways-page-item:contains('${type}'):not(:contains('ENTERED'))`);
  8444. for (const item of items) {
  8445. const needPoints = parseInt($(item).find('.giveaways-page-item-header-points').text().match(/[\d]+/gim)?.[0] || '999999', 10);
  8446. const name = $(item).find('.giveaways-page-item-footer-name').text().trim();
  8447. if (type === 'points' && needPoints > this.myPoints) {
  8448. scripts_echoLog({}).warning(`${i18n('noPoints')}: ${name}`);
  8449. } else if (type === 'points' && !needPoints) {
  8450. scripts_echoLog({}).warning(`${i18n('getNeedPointsFailed')}: ${name}`);
  8451. } else if (!(type === 'points' && needPoints > this.maxPoints)) {
  8452. const logStatus = scripts_echoLog({
  8453. text: `${i18n('joiningLottery')}<a href="${$(item).find('a.giveaways-page-item-img-btn-more').attr('href')}" target="_blank">${name}</a>...`
  8454. });
  8455. const aElement = $(item).find('a.giveaways-page-item-img-btn-enter:contains(\'enter\')');
  8456. if (aElement?.attr('onclick')?.includes('checkUser')) {
  8457. const giveawayId = aElement.attr('onclick')?.match(/[\d]+/)?.[0];
  8458. if (giveawayId) {
  8459. checkUser(giveawayId);
  8460. }
  8461. }
  8462. if (!aElement.attr('href')) {
  8463. logStatus.error('Error: No "href".');
  8464. continue;
  8465. }
  8466. const {
  8467. result,
  8468. statusText,
  8469. status,
  8470. data
  8471. } = await tools_httpRequest({
  8472. url: aElement.attr('href'),
  8473. method: 'GET'
  8474. });
  8475. if (result === 'Success') {
  8476. const {
  8477. result: result0,
  8478. statusText: statusText0,
  8479. status: status0,
  8480. data: data0
  8481. } = await tools_httpRequest({
  8482. url: data?.finalUrl,
  8483. method: 'GET'
  8484. });
  8485. if (data0?.responseText && /You've entered this giveaway/gim.test(data0.responseText)) {
  8486. logStatus.success();
  8487. const points = data0.responseText.match(/Points:[\s]*?([\d]+)/)?.[1];
  8488. if (type === 'points' && points) {
  8489. this.myPoints = parseInt(points, 10);
  8490. }
  8491. } else if (data0?.responseText && /You're not eligible to enter/gim.test(data0.responseText)) {
  8492. logStatus.error('You\'re not eligible to enter');
  8493. } else {
  8494. logStatus.error(`${result0}:${statusText0}(${status0})`);
  8495. }
  8496. } else {
  8497. logStatus.error(`${result}:${statusText}(${status})`);
  8498. }
  8499. }
  8500. }
  8501. scripts_echoLog({
  8502. text: '-----END-----'
  8503. });
  8504. } catch (error) {
  8505. throwError(error, 'OpiumPulses.toggleTask');
  8506. }
  8507. }
  8508. init() {
  8509. return true;
  8510. }
  8511. classifyTask() {
  8512. return true;
  8513. }
  8514. #checkLogin() {
  8515. try {
  8516. if (!globalOptions.other.checkLogin) {
  8517. return true;
  8518. }
  8519. if ($('a[href*="/site/login"]').length > 1) {
  8520. window.open('/site/login', '_self');
  8521. }
  8522. return true;
  8523. } catch (error) {
  8524. throwError(error, 'OpiumPulses.checkLogin');
  8525. return false;
  8526. }
  8527. }
  8528. }
  8529. const website_OpiumPulses = OpiumPulses;
  8530. const external_dayjs_namespaceObject = dayjs;
  8531. var external_dayjs_default = __webpack_require__.n(external_dayjs_namespaceObject);
  8532. const leftKeyChecker = {
  8533. async classify(link) {
  8534. try {
  8535. if (/^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(link)) {
  8536. return await this.giveawaySu(link);
  8537. }
  8538. if (/^https?:\/\/givee\.club\/[\w]+?\/event\/[\d]+/.test(link)) {
  8539. return await this.giveeClub(link);
  8540. }
  8541. if (/^https?:\/\/gleam\.io\/.+?\/.+/.test(link)) {
  8542. return await this.gleam(link);
  8543. }
  8544. if (/^https?:\/\/www\.indiedb\.com\/giveaways\/.+/.test(link)) {
  8545. return await this.indieDb(link);
  8546. }
  8547. if (/^https?:\/\/key-hub\.eu\/giveaway\/[\d]+/.test(link)) {
  8548. return await this.keyhub(link);
  8549. }
  8550. if (/^https?:\/\/opquests\.com\/quests\/[\d]+/.test(link)) {
  8551. return await this.opquests(link);
  8552. }
  8553. if (/^https?:\/\/itch\.io\/s\/[\d]+?\/.*/.test(link)) {
  8554. return await this.itch(link);
  8555. }
  8556. return false;
  8557. } catch (error) {
  8558. throwError(error, 'leftKeyChecker.classify');
  8559. return false;
  8560. }
  8561. },
  8562. async giveawaySu(link) {
  8563. try {
  8564. const {
  8565. result,
  8566. data
  8567. } = await tools_httpRequest({
  8568. url: link,
  8569. method: 'GET'
  8570. });
  8571. if (result === 'Success' && data?.status === 200) {
  8572. if (data.responseText.includes('class="steam-login"')) {
  8573. return false;
  8574. }
  8575. if (data.responseText.includes('class="giveaway-ended"')) {
  8576. return 'Ended';
  8577. }
  8578. return 'Active';
  8579. }
  8580. return false;
  8581. } catch (error) {
  8582. throwError(error, 'leftKeyChecker.giveawaySu');
  8583. return false;
  8584. }
  8585. },
  8586. async giveeClub(link) {
  8587. try {
  8588. const {
  8589. result,
  8590. data
  8591. } = await tools_httpRequest({
  8592. url: link,
  8593. method: 'GET'
  8594. });
  8595. if (result === 'Success' && data?.status === 200) {
  8596. if (data.responseText.includes('class="event-winner"')) {
  8597. return 'Won';
  8598. }
  8599. if (data.responseText.includes('class="event-ended"')) {
  8600. return 'Ended';
  8601. }
  8602. return 'Active';
  8603. }
  8604. return false;
  8605. } catch (error) {
  8606. throwError(error, 'leftKeyChecker.giveeClub');
  8607. return false;
  8608. }
  8609. },
  8610. async gleam(link) {
  8611. try {
  8612. const {
  8613. result,
  8614. data
  8615. } = await tools_httpRequest({
  8616. url: link,
  8617. method: 'GET'
  8618. });
  8619. if (result === 'Success' && data?.status === 200) {
  8620. if (/incentives&quot;:{&quot;[\d]+?&quot;:\[&quot;.+?&quot;\]/.test(data.responseText)) {
  8621. return 'Won';
  8622. }
  8623. const campaignDiv = data.responseText.match(/<div class='popup-blocks-container'[\w\W]+?'>/)?.[0];
  8624. if (!campaignDiv) {
  8625. return false;
  8626. }
  8627. const campaignString = $(campaignDiv).attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  8628. if (!campaignString) {
  8629. return false;
  8630. }
  8631. const {
  8632. campaign
  8633. } = JSON.parse(campaignString);
  8634. if (campaign.banned) {
  8635. return 'Banned';
  8636. }
  8637. if (campaign.finished) {
  8638. return 'Ended';
  8639. }
  8640. if (campaign.paused) {
  8641. return 'Paused';
  8642. }
  8643. if (new Date().getTime() < campaign.starts_at * 1e3) {
  8644. return 'NotStart';
  8645. }
  8646. return 'Active';
  8647. }
  8648. return false;
  8649. } catch (error) {
  8650. throwError(error, 'leftKeyChecker.gleam');
  8651. return false;
  8652. }
  8653. },
  8654. async indieDb(link) {
  8655. try {
  8656. const {
  8657. result,
  8658. data
  8659. } = await tools_httpRequest({
  8660. url: link,
  8661. method: 'GET'
  8662. });
  8663. if (result === 'Success' && data?.status === 200) {
  8664. if (data.responseText.includes('Congrats you WON')) {
  8665. return 'Won';
  8666. }
  8667. if (data.responseText.includes('Giveaway is closed') || data.responseText.includes('next time')) {
  8668. return 'Ended';
  8669. }
  8670. return 'Active';
  8671. }
  8672. return false;
  8673. } catch (error) {
  8674. throwError(error, 'leftKeyChecker.indieDb');
  8675. return false;
  8676. }
  8677. },
  8678. async keyhub(link) {
  8679. try {
  8680. const {
  8681. result,
  8682. data
  8683. } = await tools_httpRequest({
  8684. url: link,
  8685. method: 'GET'
  8686. });
  8687. if (result === 'Success' && data?.status === 200) {
  8688. const keysleft = data.responseText.match(/<span id="keysleft">([\d]+?)<\/span>/)?.[1];
  8689. if (!keysleft) {
  8690. return false;
  8691. }
  8692. if (keysleft === '0') {
  8693. return 'Ended';
  8694. }
  8695. return `Active(${keysleft})`;
  8696. }
  8697. return false;
  8698. } catch (error) {
  8699. throwError(error, 'leftKeyChecker.keyhub');
  8700. return false;
  8701. }
  8702. },
  8703. async opquests(link) {
  8704. try {
  8705. const {
  8706. result,
  8707. data
  8708. } = await tools_httpRequest({
  8709. url: link,
  8710. method: 'GET'
  8711. });
  8712. if (result === 'Success' && data?.status === 200) {
  8713. const keysleft = data.responseText.match(/<div class="">[\s]*?([\d]+?)[\s]*?of/)?.[1];
  8714. if (!keysleft) {
  8715. return false;
  8716. }
  8717. if (keysleft === '0') {
  8718. return 'Ended';
  8719. }
  8720. return `Active(${keysleft})`;
  8721. } else if (data?.status === 404) {
  8722. return 'Ended';
  8723. }
  8724. return false;
  8725. } catch (error) {
  8726. throwError(error, 'leftKeyChecker.opquests');
  8727. return false;
  8728. }
  8729. },
  8730. async itch(link) {
  8731. try {
  8732. const {
  8733. result,
  8734. data
  8735. } = await tools_httpRequest({
  8736. url: link,
  8737. method: 'GET'
  8738. });
  8739. if (result === 'Success' && data?.status === 200) {
  8740. const endDate = data.responseText.match(/{"start_date":"[0-9A-Z-:]+?".*?"end_date":"([0-9A-Z-:]+?)".*?}/)?.[1];
  8741. if (!endDate) {
  8742. return false;
  8743. }
  8744. if (new Date().getTime() > new Date(endDate).getTime()) {
  8745. return 'Ended';
  8746. }
  8747. return `Active(${external_dayjs_default()(endDate).format('YYYY-MM-DD HH:mm:ss')})`;
  8748. }
  8749. return false;
  8750. } catch (error) {
  8751. throwError(error, 'leftKeyChecker.itch');
  8752. return false;
  8753. }
  8754. }
  8755. };
  8756. const website_leftKeyChecker = leftKeyChecker;
  8757. const Keylol_defaultTasksTemplate = {
  8758. steam: {
  8759. groupLinks: [],
  8760. wishlistLinks: [],
  8761. curatorLinks: [],
  8762. curatorLikeLinks: [],
  8763. followLinks: [],
  8764. forumLinks: [],
  8765. announcementLinks: [],
  8766. workshopVoteLinks: [],
  8767. licenseLinks: []
  8768. },
  8769. discord: {
  8770. serverLinks: []
  8771. },
  8772. instagram: {
  8773. userLinks: []
  8774. },
  8775. vk: {
  8776. nameLinks: []
  8777. },
  8778. twitch: {
  8779. channelLinks: []
  8780. },
  8781. reddit: {
  8782. redditLinks: []
  8783. },
  8784. twitter: {
  8785. userLinks: [],
  8786. retweetLinks: []
  8787. },
  8788. youtube: {
  8789. channelLinks: [],
  8790. likeLinks: []
  8791. }
  8792. };
  8793. const Keylol_defaultTasks = JSON.stringify(Keylol_defaultTasksTemplate);
  8794. class Keylol extends website_Website {
  8795. name = 'Keylol';
  8796. socialTasks = JSON.parse(Keylol_defaultTasks);
  8797. undoneTasks = JSON.parse(Keylol_defaultTasks);
  8798. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect' ];
  8799. static test() {
  8800. 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'));
  8801. }
  8802. init() {
  8803. return true;
  8804. }
  8805. after() {
  8806. try {
  8807. const selector = this.name === 'Keylol' ? '#postlist>div[id^="post_"]:first' : 'div.container';
  8808. const mainPost = $(selector);
  8809. const discordLinks = mainPost.find('a[href*="discord.com"]:visible');
  8810. const redditLinks = mainPost.find('a[href*="reddit.com"]:visible');
  8811. const insLinks = mainPost.find('a[href*="instagram.com"]:visible');
  8812. const twitterLinks = mainPost.find('a[href*="twitter.com"]:visible,a[href*="x.com"]:visible');
  8813. const twitchLinks = mainPost.find('a[href*="twitch.tv"]:visible');
  8814. const vkLinks = mainPost.find('a[href*="vk.com"]:visible');
  8815. const steamStoreLinks = mainPost.find('a[href*="store.steampowered.com"]:visible');
  8816. const steamCommunityLinks = mainPost.find('a[href*="steamcommunity.com"]:visible');
  8817. const ytbLinks = mainPost.find('a[href*="youtube.com"]:visible');
  8818. if (discordLinks.length > 0) {
  8819. for (const discordLink of discordLinks) {
  8820. const link = $(discordLink).attr('href');
  8821. if (!(link && /^https?:\/\/discord\.com\/invite\/.+/.test(link))) {
  8822. continue;
  8823. }
  8824. this.#addBtn(discordLink, 'discord', 'serverLinks', link);
  8825. }
  8826. }
  8827. if (redditLinks.length > 0) {
  8828. for (const redditLink of redditLinks) {
  8829. const link = $(redditLink).attr('href');
  8830. if (!(link && /^https?:\/\/www\.reddit\.com\/(r|user)\/.+/.test(link))) {
  8831. continue;
  8832. }
  8833. this.#addBtn(redditLink, 'reddit', 'redditLinks', link);
  8834. }
  8835. }
  8836. if (insLinks.length > 0) {
  8837. for (const insLink of insLinks) {
  8838. const link = $(insLink).attr('href');
  8839. if (!(link && /^https:\/\/www\.instagram\.com\/.+/.test(link))) {
  8840. continue;
  8841. }
  8842. this.#addBtn(insLink, 'instagram', 'userLinks', link);
  8843. }
  8844. }
  8845. if (twitterLinks.length > 0) {
  8846. for (const twitterLink of twitterLinks) {
  8847. const link = $(twitterLink).attr('href');
  8848. if (!(link && /^https:\/\/twitter\.com\/.+/.test(link))) {
  8849. continue;
  8850. }
  8851. if (/https:\/\/twitter\.com\/.*?\/status\/[\d]+/.test(link)) {
  8852. this.#addBtn(twitterLink, 'twitter', 'retweetLinks', link);
  8853. } else {
  8854. this.#addBtn(twitterLink, 'twitter', 'userLinks', link);
  8855. }
  8856. }
  8857. }
  8858. if (twitchLinks.length > 0) {
  8859. for (const twitchLink of twitchLinks) {
  8860. const link = $(twitchLink).attr('href');
  8861. if (!(link && /^https:\/\/(www\.)?twitch\.tv\/.+/.test(link))) {
  8862. continue;
  8863. }
  8864. this.#addBtn(twitchLink, 'twitch', 'channelLinks', link);
  8865. }
  8866. }
  8867. if (vkLinks.length > 0) {
  8868. for (const vkLink of vkLinks) {
  8869. const link = $(vkLink).attr('href');
  8870. if (!(link && /^https:\/\/vk\.com\/.+/.test(link))) {
  8871. continue;
  8872. }
  8873. this.#addBtn(vkLink, 'vk', 'nameLinks', link);
  8874. }
  8875. }
  8876. if (steamStoreLinks.length > 0) {
  8877. for (const steamStoreLink of steamStoreLinks) {
  8878. const link = $(steamStoreLink).attr('href');
  8879. if (!link) {
  8880. continue;
  8881. }
  8882. if (/curator\/[\d]+/.test(link)) {
  8883. this.#addBtn(steamStoreLink, 'steam', 'curatorLinks', link);
  8884. } else if (/(publisher|developer|franchise)\/.+/.test(link)) {
  8885. this.#addBtn(steamStoreLink, 'steam', 'curatorLikeLinks', link);
  8886. } else if (/news(hub)?\/app\/[\d]+\/view\/[\d]+/.test(link)) {
  8887. this.#addBtn(steamStoreLink, 'steam', 'announcementLinks', link);
  8888. } else if (/app\/[\d]+/.test(link)) {
  8889. this.#addBtn(steamStoreLink, 'steam', 'followLinks', link);
  8890. this.#addBtn(steamStoreLink, 'steam', 'wishlistLinks', link);
  8891. }
  8892. }
  8893. }
  8894. if (steamCommunityLinks.length > 0) {
  8895. for (const steamCommunityLink of steamCommunityLinks) {
  8896. const link = $(steamCommunityLink).attr('href');
  8897. if (!link) {
  8898. continue;
  8899. }
  8900. if (/groups\/.+/.test(link)) {
  8901. this.#addBtn(steamCommunityLink, 'steam', 'groupLinks', link);
  8902. } else if (/announcements\/detail\/[\d]+/.test(link)) {
  8903. this.#addBtn(steamCommunityLink, 'steam', 'announcementLinks', link);
  8904. }
  8905. }
  8906. }
  8907. if (ytbLinks.length > 0) {
  8908. for (const ytbLink of ytbLinks) {
  8909. const link = $(ytbLink).attr('href');
  8910. if (!link) {
  8911. continue;
  8912. }
  8913. this.#addBtn(ytbLink, 'youtube', 'channelLinks', link);
  8914. this.#addBtn(ytbLink, 'youtube', 'likeLinks', link);
  8915. }
  8916. }
  8917. 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');
  8918. if (giveawayLinks.length > 0) {
  8919. for (const giveawayLink of giveawayLinks) {
  8920. const link = $(giveawayLink).attr('href');
  8921. if (!link) {
  8922. continue;
  8923. }
  8924. website_leftKeyChecker.classify(link).then(status => {
  8925. if (!status) {
  8926. return;
  8927. }
  8928. if (/^Active/.test(status)) {
  8929. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status active" title="${i18n('Active')}">${status}</font>`);
  8930. return;
  8931. }
  8932. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status not-active" title="${i18n(status)}">${status}</font>`);
  8933. }).catch(error => {
  8934. throwError(error, 'keylol.after -> leftKeyChecker');
  8935. });
  8936. }
  8937. }
  8938. if (this.name === 'Keylol') {
  8939. const asfLinks = mainPost.find('a[href^="#asf"]:visible');
  8940. if (asfLinks.length > 0) {
  8941. for (const asfLink of asfLinks) {
  8942. const link = $(asfLink).attr('href');
  8943. if (!link) {
  8944. continue;
  8945. }
  8946. this.#addBtn($(`a[href="${link}"]`).after('<span style="color: #ccc; margin: 0 -5px 0 5px"> | </span>').next()[0], 'steam', 'licenseLinks', `appid-${link.replace('#asf', '')}`);
  8947. }
  8948. }
  8949. const subLinks = mainPost.find('a[href*="steamdb.info/sub/"]:visible');
  8950. if (subLinks.length > 0) {
  8951. for (const subLink of subLinks) {
  8952. const link = $(subLink).attr('href');
  8953. if (!link) {
  8954. continue;
  8955. }
  8956. const subid = link.match(/^https:\/\/steamdb\.info\/sub\/([\d]+)/)?.[1];
  8957. if (!subid) {
  8958. continue;
  8959. }
  8960. this.#addBtn(subLink, 'steam', 'licenseLinks', `subid-${subid}`);
  8961. }
  8962. }
  8963. const asfLinks2 = mainPost.find('.blockcode:contains("addlicense"):visible');
  8964. if (asfLinks2.length > 0) {
  8965. for (const asfLink of asfLinks2) {
  8966. const appid = [ ...asfLink.innerText.matchAll(/a(pp)?\/([\d]+)/g) ].map(matched => matched?.[2]).filter(id => id) || [];
  8967. if (appid.length > 0) {
  8968. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `appid-${appid.join(',')}`);
  8969. }
  8970. const subid = asfLink.innerText.match(/[\d]+/g)?.filter(matched => !appid.includes(matched));
  8971. if (!subid || subid.length === 0) {
  8972. continue;
  8973. }
  8974. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `subid-${subid.join(',')}`);
  8975. }
  8976. }
  8977. }
  8978. } catch (error) {
  8979. throwError(error, 'keylol.after');
  8980. }
  8981. }
  8982. classifyTask(action) {
  8983. try {
  8984. this.socialTasks = JSON.parse(Keylol_defaultTasks);
  8985. this.undoneTasks = JSON.parse(Keylol_defaultTasks);
  8986. const selectedBtns = $('.auto-task-keylol[selected="selected"]:visible');
  8987. for (const btn of selectedBtns) {
  8988. const button = $(btn);
  8989. const social = button.attr('data-social');
  8990. const type = button.attr('data-type');
  8991. const link = button.attr('data-link');
  8992. if (!(social && type && link)) {
  8993. continue;
  8994. }
  8995. if (action === 'do') {
  8996. this.undoneTasks[social][type].push(link);
  8997. }
  8998. if (action === 'undo') {
  8999. this.socialTasks[social][type].push(link);
  9000. }
  9001. }
  9002. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9003. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9004. if (window.DEBUG) {
  9005. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9006. }
  9007. return true;
  9008. } catch (error) {
  9009. throwError(error, 'Keylol.classifyTask');
  9010. return false;
  9011. }
  9012. }
  9013. selectAll() {
  9014. try {
  9015. $('.auto-task-keylol:visible').attr('selected', 'selected');
  9016. } catch (error) {
  9017. throwError(error, 'Keylol.selectAll');
  9018. }
  9019. }
  9020. selectNone() {
  9021. try {
  9022. $('.auto-task-keylol:visible').removeAttr('selected');
  9023. } catch (error) {
  9024. throwError(error, 'Keylol.selectNone');
  9025. }
  9026. }
  9027. invertSelect() {
  9028. try {
  9029. $('.auto-task-keylol:visible').each((index, element) => {
  9030. element.getAttribute('selected') ? element.removeAttribute('selected') : element.setAttribute('selected', 'selected');
  9031. });
  9032. } catch (error) {
  9033. throwError(error, 'Keylol.invertSelect');
  9034. }
  9035. }
  9036. #addBtn(before, social, linkType, link) {
  9037. try {
  9038. $(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>`);
  9039. } catch (error) {
  9040. throwError(error, 'keylol.addBtn');
  9041. }
  9042. }
  9043. }
  9044. const website_Keylol = Keylol;
  9045. const Opquests_defaultTasks = {
  9046. steam: {
  9047. groupLinks: [],
  9048. wishlistLinks: [],
  9049. followLinks: [],
  9050. curatorLikeLinks: []
  9051. }
  9052. };
  9053. class Opquests extends website_Website {
  9054. name = 'Opquests';
  9055. undoneTasks = {
  9056. ...Opquests_defaultTasks
  9057. };
  9058. buttons = [ 'doTask', 'verifyTask', 'getKey' ];
  9059. static test() {
  9060. return window.location.host === 'opquests.com';
  9061. }
  9062. async before() {
  9063. try {
  9064. const opquestsVerifyTasks = GM_getValue('opquestsVerifyTasks') || [];
  9065. if (opquestsVerifyTasks.length > 0) {
  9066. const taskId = opquestsVerifyTasks.pop();
  9067. GM_setValue('opquestsVerifyTasks', opquestsVerifyTasks);
  9068. const [ verifyBtn ] = $(`#task_id[value="${taskId}"]`).parent().children('button[type="submit"]');
  9069. if (verifyBtn) {
  9070. verifyBtn.click();
  9071. return;
  9072. }
  9073. this.before();
  9074. return;
  9075. }
  9076. if (GM_getValue('opquestsVerifyTasks')) {
  9077. GM_deleteValue('opquestsVerifyTasks');
  9078. }
  9079. } catch (error) {
  9080. throwError(error, 'Opquests.before');
  9081. }
  9082. }
  9083. async after() {
  9084. try {
  9085. if (!this.#checkLogin()) {
  9086. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9087. }
  9088. } catch (error) {
  9089. throwError(error, 'Opquests.after');
  9090. }
  9091. }
  9092. init() {
  9093. try {
  9094. const logStatus = scripts_echoLog({
  9095. text: i18n('initing')
  9096. });
  9097. if ($('a[href*="/auth/redirect"]').length > 0) {
  9098. window.open('/auth/redirect', '_self');
  9099. logStatus.warning(i18n('needLogin'));
  9100. return false;
  9101. }
  9102. if (!this.#getGiveawayId()) {
  9103. return false;
  9104. }
  9105. this.initialized = true;
  9106. logStatus.success();
  9107. return true;
  9108. } catch (error) {
  9109. throwError(error, 'Opquests.init');
  9110. return false;
  9111. }
  9112. }
  9113. async classifyTask(action) {
  9114. try {
  9115. if (action === 'undo') {
  9116. scripts_echoLog({
  9117. text: i18n('cannotUndo')
  9118. });
  9119. return false;
  9120. }
  9121. const logStatus = scripts_echoLog({
  9122. text: i18n('getTasksInfo')
  9123. });
  9124. const tasks = $('.w-full:contains("Validate") .items-center');
  9125. for (const task of tasks) {
  9126. const link = $(task).find('a:contains("Open")').attr('href');
  9127. const taskDes = $(task).find('div').eq(1).text().trim();
  9128. if (!link) {
  9129. continue;
  9130. }
  9131. if (/steamcommunity\.com\/groups\//.test(link)) {
  9132. this.undoneTasks.steam.groupLinks.push(link);
  9133. } else if (/store\.steampowered\.com\/app\//.test(link)) {
  9134. if (/wishlist/gim.test(taskDes)) {
  9135. this.undoneTasks.steam.wishlistLinks.push(link);
  9136. } else if (/follow/gim.test(taskDes)) {
  9137. this.undoneTasks.steam.followLinks.push(link);
  9138. }
  9139. } else if (/store\.steampowered\.com\/(publisher|developer|curator)\//.test(link) && /follow/gim.test(taskDes)) {
  9140. this.undoneTasks.steam.curatorLikeLinks.push(link);
  9141. } else {
  9142. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  9143. }
  9144. }
  9145. logStatus.success();
  9146. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9147. if (window.DEBUG) {
  9148. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9149. }
  9150. return true;
  9151. } catch (error) {
  9152. throwError(error, 'Opquests.classifyTask');
  9153. return false;
  9154. }
  9155. }
  9156. async verifyTask() {
  9157. try {
  9158. if (!this.initialized) {
  9159. this.init();
  9160. }
  9161. const tasks = $.makeArray($('div.w-full').find('.items-center').has('button.submit-loader')).map(ele => $(ele).find('input[name="task_id"]').val());
  9162. await this.#confirm();
  9163. const taskId = tasks.pop();
  9164. GM_setValue('opquestsVerifyTasks', tasks);
  9165. $(`#task_id[value="${taskId}"]`).parent().children('button[type="submit"]')[0]?.click();
  9166. return true;
  9167. } catch (error) {
  9168. throwError(error, 'Opquests.verifyTask');
  9169. return false;
  9170. }
  9171. }
  9172. async #confirm() {
  9173. try {
  9174. const logStatus = scripts_echoLog({
  9175. html: `<li>${i18n('confirmingTask')}...<font></font></li>`
  9176. });
  9177. const {
  9178. result,
  9179. statusText,
  9180. status,
  9181. data
  9182. } = await tools_httpRequest({
  9183. url: `https://opquests.com/quests/${this.giveawayId}?confirm=1`,
  9184. method: 'GET',
  9185. nochche: true,
  9186. headers: {
  9187. origin: 'https://opquests.com',
  9188. referer: `https://opquests.com/warning?id=${this.giveawayId}`
  9189. }
  9190. });
  9191. if (result === 'Success') {
  9192. if (data?.status === 200) {
  9193. logStatus.success();
  9194. return true;
  9195. }
  9196. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9197. return false;
  9198. }
  9199. logStatus.error(`${result}:${statusText}(${status})`);
  9200. return false;
  9201. } catch (error) {
  9202. throwError(error, 'Opquests.confirm');
  9203. return false;
  9204. }
  9205. }
  9206. async getKey(isButton) {
  9207. try {
  9208. const logStatus = scripts_echoLog({
  9209. text: i18n('gettingKey')
  9210. });
  9211. const {
  9212. result,
  9213. statusText,
  9214. status,
  9215. data
  9216. } = await tools_httpRequest({
  9217. url: 'https://opquests.com/keys',
  9218. method: 'GET'
  9219. });
  9220. if (result === 'Success') {
  9221. if (data?.responseText) {
  9222. const key = $(data?.responseText).find(`div.items-center:contains("${$('h1.font-bold').text().trim().replace(' Quest', '')}")`).find('div.font-bold').next().text();
  9223. if (!key) {
  9224. logStatus.error('Error: Key was not found');
  9225. if (isButton) {
  9226. window.open('https://opquests.com/keys', '_self');
  9227. }
  9228. return false;
  9229. }
  9230. logStatus.success();
  9231. scripts_echoLog({}).success(key);
  9232. return true;
  9233. }
  9234. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9235. return false;
  9236. }
  9237. logStatus.error(`${result}:${statusText}(${status})`);
  9238. return false;
  9239. } catch (error) {
  9240. throwError(error, 'Opquests.getGiveawayId');
  9241. return false;
  9242. }
  9243. }
  9244. #getGiveawayId() {
  9245. try {
  9246. const giveawayId = window.location.href.match(/quests\/([\d]+)/)?.[1];
  9247. if (giveawayId) {
  9248. this.giveawayId = giveawayId;
  9249. return true;
  9250. }
  9251. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  9252. return false;
  9253. } catch (error) {
  9254. throwError(error, 'Opquests.getGiveawayId');
  9255. return false;
  9256. }
  9257. }
  9258. #checkLogin() {
  9259. try {
  9260. if (!globalOptions.other.checkLogin) {
  9261. return true;
  9262. }
  9263. if ($('a[href*="/auth/redirect"]').length > 0) {
  9264. window.open('/auth/redirect', '_self');
  9265. }
  9266. return true;
  9267. } catch (error) {
  9268. throwError(error, 'Opquests.checkLogin');
  9269. return false;
  9270. }
  9271. }
  9272. }
  9273. const website_Opquests = Opquests;
  9274. const Gleam_defaultTasksTemplate = {
  9275. steam: {
  9276. groupLinks: [],
  9277. wishlistLinks: [],
  9278. followLinks: [],
  9279. curatorLinks: [],
  9280. curatorLikeLinks: []
  9281. },
  9282. twitter: {
  9283. userLinks: [],
  9284. retweetLinks: []
  9285. },
  9286. twitch: {
  9287. channelLinks: []
  9288. },
  9289. discord: {
  9290. serverLinks: []
  9291. },
  9292. youtube: {
  9293. channelLinks: []
  9294. },
  9295. extra: {
  9296. gleam: []
  9297. }
  9298. };
  9299. const Gleam_defaultTasks = JSON.stringify(Gleam_defaultTasksTemplate);
  9300. class Gleam extends website_Website {
  9301. name = 'Gleam';
  9302. undoneTasks = JSON.parse(Gleam_defaultTasks);
  9303. socialTasks = JSON.parse(Gleam_defaultTasks);
  9304. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  9305. static test() {
  9306. return window.location.host === 'gleam.io';
  9307. }
  9308. before() {
  9309. try {
  9310. unsafeWindow.confirm = () => {};
  9311. unsafeWindow.alert = () => {};
  9312. unsafeWindow.prompt = () => {};
  9313. } catch (error) {
  9314. throwError(error, 'Gleam.before');
  9315. }
  9316. }
  9317. async after() {
  9318. try {
  9319. if (window.location.search.includes('8b07d23f4bfa65f9')) {
  9320. const checkComplete = setInterval(() => {
  9321. if ($('.entry-content .entry-method i.fa-check').length > 0) {
  9322. clearInterval(checkComplete);
  9323. window.close();
  9324. }
  9325. });
  9326. for (const task of $('.entry-content .entry-method')) {
  9327. const taskInfo = $(task).find('.user-links');
  9328. const expandInfo = $(task).find('.expandable');
  9329. const aElements = expandInfo.find('a.btn,a:contains(Continue),button:contains(Continue)');
  9330. if (aElements.length > 0) {
  9331. for (const element of aElements) {
  9332. const $element = $(element);
  9333. const href = $element.attr('href');
  9334. $element.removeAttr('href')[0].click();
  9335. $element.attr('href', href);
  9336. await delay(1e3);
  9337. }
  9338. }
  9339. taskInfo[0].click();
  9340. await delay(1e3);
  9341. }
  9342. scripts_echoLog({}).warning(i18n('gleamTaskNotice'));
  9343. } else if (!await this.#checkLeftKey()) {
  9344. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  9345. }
  9346. } catch (error) {
  9347. throwError(error, 'Gleam.after');
  9348. }
  9349. }
  9350. init() {
  9351. try {
  9352. const logStatus = scripts_echoLog({
  9353. text: i18n('initing')
  9354. });
  9355. if (!this.#getGiveawayId()) {
  9356. return false;
  9357. }
  9358. this.initialized = true;
  9359. logStatus.success();
  9360. return true;
  9361. } catch (error) {
  9362. throwError(error, 'Gleam.init');
  9363. return false;
  9364. }
  9365. }
  9366. async classifyTask(action) {
  9367. try {
  9368. const logStatus = scripts_echoLog({
  9369. text: i18n('getTasksInfo')
  9370. });
  9371. if (action === 'undo') {
  9372. this.socialTasks = GM_getValue(`gleamTasks-${this.giveawayId}`)?.tasks || JSON.parse(Gleam_defaultTasks);
  9373. }
  9374. const tasks = $('.entry-content .entry-method');
  9375. for (const task of tasks) {
  9376. const $task = $(task);
  9377. if (action === 'do' && $task.find('i.fa-question').length === 0) {
  9378. continue;
  9379. }
  9380. const socialIcon = $task.find('.icon-wrapper i');
  9381. const taskInfo = $task.find('.user-links');
  9382. const taskText = taskInfo.text().trim();
  9383. const expandInfo = $task.find('.expandable');
  9384. const aElements = expandInfo.find('a.btn');
  9385. if (aElements.length > 0) {
  9386. for (const element of aElements) {
  9387. const $element = $(element);
  9388. const href = $element.attr('href');
  9389. $element.removeAttr('href')[0].click();
  9390. $element.attr('href', href);
  9391. }
  9392. }
  9393. if (socialIcon.hasClass('fa-twitter') || socialIcon.hasClass('fa-x-twitter')) {
  9394. const link = $task.find('a[href^="https://twitter.com/"],a[href^="https://x.com/"]').attr('href');
  9395. if (!link) {
  9396. continue;
  9397. }
  9398. if (/follow/gi.test(taskText)) {
  9399. if (action === 'undo') {
  9400. this.socialTasks.twitter.userLinks.push(link);
  9401. }
  9402. if (action === 'do') {
  9403. this.undoneTasks.twitter.userLinks.push(link);
  9404. }
  9405. } else if (/retweet/gim.test(taskText)) {
  9406. if (action === 'undo') {
  9407. this.socialTasks.twitter.retweetLinks.push(link);
  9408. }
  9409. if (action === 'do') {
  9410. this.undoneTasks.twitter.retweetLinks.push(link);
  9411. }
  9412. }
  9413. } else if (socialIcon.hasClass('fa-twitch')) {
  9414. if (/follow/gim.test(taskText)) {
  9415. const link = $task.find('a[href^="https://twitch.tv/"]').attr('href');
  9416. if (!link) {
  9417. continue;
  9418. }
  9419. if (action === 'undo') {
  9420. this.socialTasks.twitch.channelLinks.push(link);
  9421. }
  9422. if (action === 'do') {
  9423. this.undoneTasks.twitch.channelLinks.push(link);
  9424. }
  9425. }
  9426. } else if (socialIcon.hasClass('fa-discord')) {
  9427. if (/join/gim.test(taskText)) {
  9428. let link = $task.find('a[href^="https://discord.com/invite/"]').attr('href');
  9429. if (!link) {
  9430. const ggLink = $task.find('a[href^="https://discord.gg/"]').attr('href')?.match(/discord\.gg\/([^/]+)/)?.[1];
  9431. if (!ggLink) {
  9432. continue;
  9433. }
  9434. link = `https://discord.com/invite/${ggLink}`;
  9435. }
  9436. if (action === 'undo') {
  9437. this.socialTasks.discord.serverLinks.push(link);
  9438. }
  9439. if (action === 'do') {
  9440. this.undoneTasks.discord.serverLinks.push(link);
  9441. }
  9442. }
  9443. } else if (socialIcon.hasClass('fa-external-link-square-alt')) {
  9444. continue;
  9445. } else if (socialIcon.hasClass('fa-youtube')) {
  9446. if (/subscribe/gim.test(taskText)) {
  9447. const link = $task.find('a[href^="https://www.youtube.com/channel/"]').attr('href');
  9448. if (!link) {
  9449. continue;
  9450. }
  9451. if (action === 'undo') {
  9452. this.socialTasks.youtube.channelLinks.push(link);
  9453. }
  9454. if (action === 'do') {
  9455. this.undoneTasks.youtube.channelLinks.push(link);
  9456. }
  9457. }
  9458. } else if (socialIcon.attr('class')?.includes('steam')) {
  9459. if (/join.*group/gi.test(taskText)) {
  9460. const link = $task.find('a[href^="https://steamcommunity.com/groups/"]').attr('href');
  9461. if (!link) {
  9462. continue;
  9463. }
  9464. if (action === 'undo') {
  9465. this.socialTasks.steam.groupLinks.push(link);
  9466. }
  9467. if (action === 'do') {
  9468. this.undoneTasks.steam.groupLinks.push(link);
  9469. }
  9470. } else if (/follow.*curator/gi.test(taskText)) {
  9471. const link = $task.find('a[href^="https://store.steampowered.com/curator/"]').attr('href');
  9472. if (!link) {
  9473. continue;
  9474. }
  9475. if (action === 'undo') {
  9476. this.socialTasks.steam.curatorLinks.push(link);
  9477. }
  9478. if (action === 'do') {
  9479. this.undoneTasks.steam.curatorLinks.push(link);
  9480. }
  9481. }
  9482. } else if (socialIcon.hasClass('fa-bullhorn') && /Complete/gi.test(taskText)) {
  9483. if (action !== 'do') {
  9484. continue;
  9485. }
  9486. const gleamLink = await this.#getGleamLink(taskText);
  9487. if (!gleamLink) {
  9488. continue;
  9489. }
  9490. this.undoneTasks.extra.gleam.push(gleamLink);
  9491. } 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 {
  9492. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskText}`);
  9493. }
  9494. }
  9495. logStatus.success();
  9496. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9497. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9498. if (window.DEBUG) {
  9499. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9500. }
  9501. GM_setValue(`gleamTasks-${this.giveawayId}`, {
  9502. tasks: this.socialTasks,
  9503. time: new Date().getTime()
  9504. });
  9505. return true;
  9506. } catch (error) {
  9507. throwError(error, 'Gleam.classifyTask');
  9508. return false;
  9509. }
  9510. }
  9511. async extraDoTask({
  9512. gleam
  9513. }) {
  9514. try {
  9515. const pro = [];
  9516. for (const link of gleam) {
  9517. pro.push(this.#doGleamTask(link));
  9518. }
  9519. return Promise.all(pro).then(() => true);
  9520. } catch (error) {
  9521. throwError(error, 'Gleam.extraDoTask');
  9522. return false;
  9523. }
  9524. }
  9525. async verifyTask() {
  9526. try {
  9527. scripts_echoLog({
  9528. text: `${i18n('verifyingTask')}...`
  9529. });
  9530. const tasks = $('.entry-content .entry-method');
  9531. unsafeWindow._OxA = '_OxA';
  9532. for (const task of tasks) {
  9533. if ($('[campaign-key="campaign.key"]').length > 0) {
  9534. return scripts_echoLog({
  9535. text: i18n('campaign')
  9536. });
  9537. }
  9538. const $task = $(task);
  9539. if ($task.find('i.fa-question').length === 0) {
  9540. continue;
  9541. }
  9542. const taskInfo = $task.find('.user-links');
  9543. taskInfo[0].click();
  9544. const aElements = $task.find('.expandable').find('a.btn');
  9545. if (aElements.length > 0) {
  9546. for (const element of aElements) {
  9547. const $element = $(element);
  9548. const href = $element.attr('href');
  9549. $element.removeAttr('href')[0].click();
  9550. $element.attr('href', href);
  9551. }
  9552. }
  9553. unsafeWindow.$hookTimer?.setSpeed(1e3);
  9554. const visitBtn = $task.find('.expandable').find('span:contains(more seconds),button:contains(more seconds)').filter(':visible');
  9555. if (visitBtn.length > 0 && unsafeWindow.$hookTimer) {
  9556. const newTab = GM_openInTab('', {
  9557. active: true
  9558. });
  9559. await delay(1e3);
  9560. newTab?.close();
  9561. window.focus();
  9562. }
  9563. await delay(3e3);
  9564. unsafeWindow.$hookTimer?.setSpeed(1);
  9565. const expandInfo = $task.find('.expandable');
  9566. const [ input ] = expandInfo.find('input');
  9567. if (input) {
  9568. const evt = new Event('input', {
  9569. bubbles: true,
  9570. cancelable: true,
  9571. composed: true
  9572. });
  9573. const valuelimit = [ ...expandInfo.text().matchAll(/"(.+?)"/g) ].at(-1)?.[1];
  9574. input.value = valuelimit || 'vloot';
  9575. input.dispatchEvent(evt);
  9576. await delay(1e3);
  9577. }
  9578. await this.#checkSync();
  9579. const continueBtn = $task.find('.expandable').find('span:contains(Continue),button:contains(Continue)');
  9580. for (const button of continueBtn) {
  9581. button.click();
  9582. await delay(500);
  9583. await this.#checkSync();
  9584. }
  9585. }
  9586. scripts_echoLog({
  9587. text: i18n('verifiedGleamTasks')
  9588. });
  9589. } catch (error) {
  9590. throwError(error, 'Gleam.verifyTask');
  9591. return false;
  9592. }
  9593. }
  9594. async #checkSync() {
  9595. try {
  9596. return await new Promise(resolve => {
  9597. const checker = setInterval(() => {
  9598. if ($('.entry-content .entry-method i.fa-sync').length === 0) {
  9599. clearInterval(checker);
  9600. resolve(true);
  9601. }
  9602. }, 500);
  9603. });
  9604. } catch (error) {
  9605. throwError(error, 'Gleam.checkSync');
  9606. return false;
  9607. }
  9608. }
  9609. async #doGleamTask(link) {
  9610. try {
  9611. const logStatus = scripts_echoLog({
  9612. text: i18n('doingGleamTask')
  9613. });
  9614. return await new Promise(resolve => {
  9615. GM_openInTab(`${link}?8b07d23f4bfa65f9`, {
  9616. active: true,
  9617. insert: true,
  9618. setParent: true
  9619. }).onclose = () => {
  9620. logStatus.success();
  9621. resolve(true);
  9622. };
  9623. });
  9624. } catch (error) {
  9625. throwError(error, 'Gleam.doGleamTask');
  9626. return false;
  9627. }
  9628. }
  9629. #getGiveawayId() {
  9630. try {
  9631. const giveawayId = window.location.pathname;
  9632. if (giveawayId) {
  9633. this.giveawayId = giveawayId;
  9634. return true;
  9635. }
  9636. scripts_echoLog({
  9637. text: i18n('getFailed', 'GiveawayId')
  9638. });
  9639. return false;
  9640. } catch (error) {
  9641. throwError(error, 'Gleam.getGiveawayId');
  9642. return false;
  9643. }
  9644. }
  9645. async #getGleamLink(title) {
  9646. try {
  9647. const logStatus = scripts_echoLog({
  9648. text: i18n('gettingGleamLink')
  9649. });
  9650. const {
  9651. result,
  9652. statusText,
  9653. status,
  9654. data
  9655. } = await tools_httpRequest({
  9656. url: 'https://www.vloot.io/api/v1/giveaways',
  9657. method: 'GET',
  9658. responseType: 'json'
  9659. });
  9660. if (result === 'Success') {
  9661. if (data?.status === 200 && data?.response?.Success === true && data?.response?.Data) {
  9662. const {
  9663. link
  9664. } = data.response.Data.find(giveaway => title.replace(/[\s]/g, '').toLowerCase().includes(giveaway.title.replace(/[\s]/g, '').toLowerCase())) || {};
  9665. if (link) {
  9666. logStatus.success();
  9667. return link;
  9668. }
  9669. logStatus.error(`Error:${i18n('getLinkFailed')}`);
  9670. return false;
  9671. }
  9672. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9673. return false;
  9674. }
  9675. logStatus.error(`${result}:${statusText}(${status})`);
  9676. return false;
  9677. } catch (error) {
  9678. throwError(error, 'Gleam.getGleamLink');
  9679. return false;
  9680. }
  9681. }
  9682. async #checkLeftKey() {
  9683. try {
  9684. if (!globalOptions.other.checkLeftKey) {
  9685. return true;
  9686. }
  9687. const campaignString = $('div.popup-blocks-container').attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  9688. if (!campaignString) {
  9689. return false;
  9690. }
  9691. const {
  9692. campaign,
  9693. incentive
  9694. } = JSON.parse(campaignString);
  9695. const controllerString = $('div.campaign.reward').attr('ng-init')?.match(/initContestant\(([\w\W]+?)\);/)?.[1];
  9696. let ownedKey = false;
  9697. if (controllerString) {
  9698. if (JSON.parse(controllerString).contestant?.claims?.incentives?.[incentive.id]?.length) {
  9699. ownedKey = true;
  9700. }
  9701. }
  9702. if (campaign.banned || campaign.finished && !ownedKey || campaign.paused || new Date().getTime() < campaign.starts_at * 1e3) {
  9703. await external_Swal_default().fire({
  9704. icon: 'warning',
  9705. title: i18n('notice'),
  9706. text: i18n('giveawayNotWork'),
  9707. confirmButtonText: i18n('confirm'),
  9708. cancelButtonText: i18n('cancel'),
  9709. showCancelButton: true
  9710. }).then(({
  9711. value
  9712. }) => {
  9713. if (value) {
  9714. window.close();
  9715. }
  9716. });
  9717. }
  9718. return true;
  9719. } catch (error) {
  9720. throwError(error, 'Gleam.checkLeftKey');
  9721. return false;
  9722. }
  9723. }
  9724. }
  9725. const website_Gleam = Gleam;
  9726. const SweepWidget_defaultOptions = {
  9727. username: '',
  9728. email: ''
  9729. };
  9730. class SweepWidget extends website_Website {
  9731. name = 'SweepWidget';
  9732. options = {
  9733. ...SweepWidget_defaultOptions,
  9734. ...GM_getValue('SweepWidgetOptions')
  9735. };
  9736. buttons = [ 'doTask' ];
  9737. static test() {
  9738. return /^https?:\/\/sweepwidget\.com\/view\/[\d]+/.test(window.location.href);
  9739. }
  9740. async after() {
  9741. try {
  9742. if (!this.#checkLogin()) {
  9743. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9744. }
  9745. } catch (error) {
  9746. throwError(error, 'SweepWidget.after');
  9747. }
  9748. }
  9749. init() {
  9750. try {
  9751. const logStatus = scripts_echoLog({
  9752. text: i18n('initing')
  9753. });
  9754. if (!this.#checkLogin()) {
  9755. logStatus.warning(i18n('needLogin'));
  9756. return false;
  9757. }
  9758. if (!this.#getGiveawayId()) {
  9759. return false;
  9760. }
  9761. this.initialized = true;
  9762. logStatus.success();
  9763. return true;
  9764. } catch (error) {
  9765. throwError(error, 'SweepWidget.init');
  9766. return false;
  9767. }
  9768. }
  9769. classifyTask() {
  9770. return true;
  9771. }
  9772. async doTask() {
  9773. try {
  9774. if ($('#unlock_rewards_main_wrapper').length === 0) {
  9775. if ($('input[name="sw__login_name"]:visible').length > 0) {
  9776. $('input[name="sw__login_name"]').val(this.options.username);
  9777. }
  9778. if ($('input[name="sw__login_email"]:visible').length > 0) {
  9779. $('input[name="sw__login_email"]').val(this.options.email);
  9780. }
  9781. if ($('#sw_login_button:visible').length > 0) {
  9782. $('#sw_login_button')[0].click();
  9783. }
  9784. if (!await this.#checkEnter()) {
  9785. return false;
  9786. }
  9787. }
  9788. const logStatus = scripts_echoLog({
  9789. text: i18n('SweepWidgetNotice')
  9790. });
  9791. const tasks = $('#sw_inner_entry_methods_l2_wrapper>div.sw_entry');
  9792. for (const task of tasks) {
  9793. const $task = $(task);
  9794. if ($task.find('i.fa-check:visible').length > 0) {
  9795. continue;
  9796. }
  9797. const title = $task.find('.sw_text_inner');
  9798. title[0].click();
  9799. const aElement = $task.find('a.sw_link');
  9800. const link = aElement.attr('href');
  9801. aElement.attr('href', '#a').attr('target', '_self');
  9802. aElement[0]?.click();
  9803. await delay(300);
  9804. aElement.attr('href', link).attr('target', '_blank');
  9805. $task.find('input[type="text"]').val('test');
  9806. const verifyBtn = $task.find('input.sw_verify');
  9807. if (verifyBtn.prop('disabled') === true) {
  9808. title[0].click();
  9809. await delay(300);
  9810. title[0].click();
  9811. await delay(300);
  9812. }
  9813. $task.find('input.sw_verify').removeAttr('disabled')[0]?.click();
  9814. await this.#checkFinish($task);
  9815. await delay(parseInt(`${Math.random() * (3e3 - 1e3 + 1) + 1e3}`, 10));
  9816. }
  9817. logStatus.success();
  9818. return true;
  9819. } catch (error) {
  9820. throwError(error, 'SweepWidget.doTask');
  9821. return false;
  9822. }
  9823. }
  9824. #checkLogin() {
  9825. try {
  9826. if ($('#twitter_login_button').length > 0) {
  9827. $('#twitter_login_button')[0].click();
  9828. }
  9829. return true;
  9830. } catch (error) {
  9831. throwError(error, 'SweepWidget.checkLogin');
  9832. return false;
  9833. }
  9834. }
  9835. #getGiveawayId() {
  9836. try {
  9837. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  9838. if (giveawayId) {
  9839. this.giveawayId = giveawayId;
  9840. return true;
  9841. }
  9842. scripts_echoLog({
  9843. text: i18n('getFailed', 'GiveawayId')
  9844. });
  9845. return false;
  9846. } catch (error) {
  9847. throwError(error, 'SweepWidget.getGiveawayId');
  9848. return false;
  9849. }
  9850. }
  9851. async #checkEnter() {
  9852. try {
  9853. return new Promise(resolve => {
  9854. const checker = setInterval(() => {
  9855. if ($('#unlock_rewards_main_wrapper').length > 0) {
  9856. clearInterval(checker);
  9857. resolve(true);
  9858. }
  9859. }, 500);
  9860. });
  9861. } catch (error) {
  9862. throwError(error, 'SweepWidget.checkEnter');
  9863. return false;
  9864. }
  9865. }
  9866. async #checkFinish($task) {
  9867. try {
  9868. return new Promise(resolve => {
  9869. const checker = setInterval(() => {
  9870. if ($task.find('i.fa-check:visible').length > 0 || $task.find('.sw_entry_input:visible').length === 0) {
  9871. clearInterval(checker);
  9872. resolve(true);
  9873. }
  9874. }, 500);
  9875. });
  9876. } catch (error) {
  9877. throwError(error, 'SweepWidget.checkFinish');
  9878. return false;
  9879. }
  9880. }
  9881. }
  9882. const website_SweepWidget = SweepWidget;
  9883. const defaultWhiteList = {
  9884. discord: {
  9885. servers: []
  9886. },
  9887. instagram: {
  9888. users: []
  9889. },
  9890. twitch: {
  9891. channels: []
  9892. },
  9893. twitter: {
  9894. users: [],
  9895. retweets: [],
  9896. likes: []
  9897. },
  9898. vk: {
  9899. names: []
  9900. },
  9901. youtube: {
  9902. channels: [],
  9903. likes: []
  9904. },
  9905. reddit: {
  9906. reddits: []
  9907. },
  9908. steam: {
  9909. groups: [],
  9910. officialGroups: [],
  9911. wishlists: [],
  9912. follows: [],
  9913. forums: [],
  9914. workshops: [],
  9915. curators: [],
  9916. workshopVotes: [],
  9917. curatorLikes: [],
  9918. announcements: [],
  9919. licenses: [],
  9920. playtests: []
  9921. }
  9922. };
  9923. const link2id = async function(type) {
  9924. try {
  9925. const link = $('#socialLink').val();
  9926. let id = '';
  9927. switch (type) {
  9928. case 'discord.servers':
  9929. id = link.match(/invite\/(.+)/)?.[1] || '';
  9930. break;
  9931.  
  9932. case 'instagram.users':
  9933. id = link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1] || '';
  9934. break;
  9935.  
  9936. case 'twitch.channels':
  9937. id = link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2] || '';
  9938. break;
  9939.  
  9940. case 'twitter.users':
  9941. id = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || '';
  9942. break;
  9943.  
  9944. case 'twitter.retweets':
  9945. id = link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1] || '';
  9946. break;
  9947.  
  9948. case 'vk.names':
  9949. id = link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1] || '';
  9950. break;
  9951.  
  9952. case 'youtube.channels':
  9953. id = (await getInfo(link, 'channel'))?.params?.channelId || '';
  9954. break;
  9955.  
  9956. case 'youtube.likes':
  9957. id = (await getInfo(link, 'likeVideo'))?.params?.videoId || '';
  9958. break;
  9959.  
  9960. case 'reddit.reddits':
  9961. id = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1] || link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1] || '';
  9962. break;
  9963.  
  9964. case 'steam.groups':
  9965. id = link.match(/groups\/(.+)\/?/)?.[1] || '';
  9966. break;
  9967.  
  9968. case 'steam.wishlists':
  9969. case 'steam.follows':
  9970. case 'steam.forums':
  9971. id = link.match(/app\/([\d]+)/)?.[1] || '';
  9972. break;
  9973.  
  9974. case 'steam.workshops':
  9975. id = link.match(/\?id=([\d]+)/)?.[1] || '';
  9976. break;
  9977.  
  9978. case 'steam.curators':
  9979. {
  9980. if (link.includes('curator')) {
  9981. id = link.match(/curator\/([\d]+)/)?.[1] || '';
  9982. } else {
  9983. const param = link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3);
  9984. if (!param || param.length !== 2) {
  9985. break;
  9986. }
  9987. const steam = new social_Steam();
  9988. if (await steam.init()) {
  9989. id = await steam.getCuratorId(param[0], param[1]) || '';
  9990. }
  9991. }
  9992. }
  9993. break;
  9994. }
  9995. return id;
  9996. } catch (error) {
  9997. throwError(error, 'link2id');
  9998. return i18n('getFailed', 'id');
  9999. }
  10000. };
  10001. const disabledType = {
  10002. steam: [ 'workshopVotes', 'curatorLikes', 'announcements' ],
  10003. twitter: [ 'likes' ]
  10004. };
  10005. const assignWhiteList = whiteList => {
  10006. try {
  10007. const newWhiteList = {};
  10008. for (const [ key, value ] of Object.entries(defaultWhiteList)) {
  10009. newWhiteList[key] = {
  10010. ...value,
  10011. ...whiteList[key]
  10012. };
  10013. }
  10014. return newWhiteList;
  10015. } catch (error) {
  10016. throwError(error, 'assignWhiteList');
  10017. return defaultWhiteList;
  10018. }
  10019. };
  10020. const whiteListOptions = function(showType) {
  10021. try {
  10022. const whiteList = assignWhiteList(GM_getValue('whiteList') || {});
  10023. let whiteListOptionsForm = `<form id="whiteListForm" class="auto-task-form">
  10024. <table class="auto-task-table"><thead><tr><td>${i18n('website')}</td><td>${i18n('type')}</td><td>${i18n('edit')}</td></tr></thead><tbody>`;
  10025. for (const [ social, types ] of Object.entries(whiteList)) {
  10026. 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('');
  10027. }
  10028. whiteListOptionsForm += '</tbody></table></form>';
  10029. if (showType === 'swal') {
  10030. external_Swal_default().fire({
  10031. title: i18n('whiteListOptions'),
  10032. html: whiteListOptionsForm,
  10033. showConfirmButton: false,
  10034. showCloseButton: true
  10035. });
  10036. } else {
  10037. $('body').append(`<h2>${i18n('whiteList')}</h2>${whiteListOptionsForm}`);
  10038. }
  10039. $('.editWhiteList').on('click', function() {
  10040. const value = $(this).attr('data-value');
  10041. if (!value) {
  10042. return;
  10043. }
  10044. const [ social, type ] = value.split('.');
  10045. if (!whiteList?.[social]?.[type]) {
  10046. scripts_echoLog({}).warning(i18n('whiteListNotFound', value));
  10047. return;
  10048. }
  10049. external_Swal_default().fire({
  10050. title: i18n('changeWhiteListOption', value),
  10051. input: 'textarea',
  10052. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10053. <button id="link2id" data-type="${value}" class="swal2-confirm swal2-styled">获取id</button>
  10054. <p style="margin-bottom:0 !important;">在下方填写白名单,每行一个</p>`,
  10055. inputValue: whiteList[social][type].join('\n'),
  10056. showConfirmButton: true,
  10057. confirmButtonText: i18n('save'),
  10058. showCancelButton: true,
  10059. cancelButtonText: i18n('close'),
  10060. showDenyButton: true,
  10061. denyButtonText: i18n('return')
  10062. }).then(({
  10063. isDenied,
  10064. isConfirmed,
  10065. value
  10066. }) => {
  10067. if (isDenied) {
  10068. if (showType === 'swal') {
  10069. whiteListOptions(showType);
  10070. }
  10071. return;
  10072. } else if (isConfirmed) {
  10073. whiteList[social][type] = value.split('\n');
  10074. GM_setValue('whiteList', whiteList);
  10075. external_Swal_default().fire({
  10076. title: i18n('changeWhiteListSuccess'),
  10077. icon: 'success'
  10078. });
  10079. }
  10080. });
  10081. $('#link2id').on('click', async function() {
  10082. const type = $(this).attr('data-type');
  10083. $('#socialLink').val(await link2id(type));
  10084. });
  10085. });
  10086. } catch (error) {
  10087. throwError(error, 'whiteListOptions');
  10088. }
  10089. };
  10090. const whiteList = whiteListOptions;
  10091. const setGistData = async (token, gistId, fileName, content) => {
  10092. try {
  10093. const logStatus = scripts_echoLog({
  10094. text: i18n('settingData')
  10095. });
  10096. const contentData = JSON.stringify({
  10097. files: {
  10098. [fileName]: {
  10099. content: JSON.stringify(content)
  10100. }
  10101. }
  10102. });
  10103. const {
  10104. result,
  10105. statusText,
  10106. status,
  10107. data
  10108. } = await tools_httpRequest({
  10109. url: `https://api.github.com/gists/${gistId}`,
  10110. headers: {
  10111. Accept: 'application/vnd.github.v3+json',
  10112. Authorization: `token ${token}`
  10113. },
  10114. data: contentData,
  10115. responseType: 'json',
  10116. method: 'POST',
  10117. timeout: 3e4
  10118. });
  10119. if (result === 'Success') {
  10120. if (data?.status === 200 && data.response.files?.[fileName]?.content === JSON.stringify(content)) {
  10121. logStatus.success();
  10122. return true;
  10123. }
  10124. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10125. return false;
  10126. }
  10127. logStatus.error(`${result}:${statusText}(${status})`);
  10128. return false;
  10129. } catch (error) {
  10130. throwError(error, 'setGistData');
  10131. return false;
  10132. }
  10133. };
  10134. const getGistData = async (token, gistId, fileName, test = false) => {
  10135. try {
  10136. const logStatus = scripts_echoLog({
  10137. text: i18n('gettingData')
  10138. });
  10139. const {
  10140. result,
  10141. statusText,
  10142. status,
  10143. data
  10144. } = await tools_httpRequest({
  10145. url: `https://api.github.com/gists/${gistId}`,
  10146. headers: {
  10147. Accept: 'application/vnd.github.v3+json',
  10148. Authorization: `token ${token}`
  10149. },
  10150. responseType: 'json',
  10151. method: 'GET',
  10152. timeout: 3e4
  10153. });
  10154. if (result === 'Success') {
  10155. if (data?.status === 200) {
  10156. const content = data.response?.files?.[fileName]?.content;
  10157. let formatedContent;
  10158. if (!content) {
  10159. logStatus.error(`Error:${i18n('noRemoteData')}`);
  10160. return false;
  10161. }
  10162. if (test) {
  10163. logStatus.success();
  10164. return true;
  10165. }
  10166. try {
  10167. formatedContent = JSON.parse(content);
  10168. } catch (error) {
  10169. logStatus.error(`Error:${i18n('errorRemoteDataFormat')}`);
  10170. return false;
  10171. }
  10172. logStatus.success();
  10173. return formatedContent;
  10174. }
  10175. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10176. return false;
  10177. }
  10178. logStatus.error(`${result}:${statusText}(${status})`);
  10179. return false;
  10180. } catch (error) {
  10181. throwError(error, 'getGistData');
  10182. return false;
  10183. }
  10184. };
  10185. const syncOptions = () => {
  10186. try {
  10187. const {
  10188. TOKEN,
  10189. GIST_ID,
  10190. FILE_NAME,
  10191. SYNC_HISTORY
  10192. } = GM_getValue('gistOptions') || {
  10193. TOKEN: '',
  10194. GIST_ID: '',
  10195. FILE_NAME: '',
  10196. SYNC_HISTORY: true
  10197. };
  10198. external_Swal_default().fire({
  10199. title: i18n('gistOptions'),
  10200. 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;">
  10201. ${i18n('upload2gist')}</button>` + `<button id="download-data" type="button" class="swal2-confirm swal2-styled" style="display: inline-block;">
  10202. ${i18n('downloadFromGist')}</button></p>`,
  10203. focusConfirm: false,
  10204. showLoaderOnConfirm: true,
  10205. 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>`,
  10206. preConfirm: async () => {
  10207. const token = $('#github-token').val();
  10208. const gistId = $('#gist-id').val();
  10209. const fileName = $('#file-name').val();
  10210. const syncHistory = $('#sync-history').prop('checked');
  10211. GM_setValue('gistOptions', {
  10212. TOKEN: token,
  10213. GIST_ID: gistId,
  10214. FILE_NAME: fileName,
  10215. SYNC_HISTORY: syncHistory
  10216. });
  10217. return await getGistData(token, gistId, fileName, true);
  10218. },
  10219. allowOutsideClick: () => !external_Swal_default().isLoading(),
  10220. confirmButtonText: i18n('saveAndTest'),
  10221. showCancelButton: true,
  10222. cancelButtonText: i18n('close')
  10223. }).then(({
  10224. value
  10225. }) => {
  10226. if (value) {
  10227. external_Swal_default().fire({
  10228. icon: 'success',
  10229. title: i18n('testSuccess')
  10230. }).then(syncOptions);
  10231. } else if (value !== undefined) {
  10232. external_Swal_default().fire({
  10233. icon: 'error',
  10234. title: i18n('testFailed')
  10235. }).then(syncOptions);
  10236. }
  10237. });
  10238. $('#upload-data').on('click', async () => {
  10239. const {
  10240. TOKEN,
  10241. GIST_ID,
  10242. FILE_NAME
  10243. } = GM_getValue('gistOptions') || {};
  10244. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10245. return external_Swal_default().fire({
  10246. icon: 'error',
  10247. title: i18n('saveAndTestNotice')
  10248. }).then(syncOptions);
  10249. }
  10250. external_Swal_default().fire({
  10251. icon: 'info',
  10252. title: i18n('processingData')
  10253. });
  10254. const data = {};
  10255. const names = GM_listValues();
  10256. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10257. for (const name of names) {
  10258. if (name === 'gistOptions' || /^[\w]+?Auth$/.test(name)) {
  10259. continue;
  10260. }
  10261. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10262. continue;
  10263. }
  10264. data[name] = GM_getValue(name);
  10265. }
  10266. external_Swal_default().update({
  10267. icon: 'info',
  10268. title: i18n('updatingData')
  10269. });
  10270. if (await setGistData(TOKEN, GIST_ID, FILE_NAME, data)) {
  10271. external_Swal_default().fire({
  10272. icon: 'success',
  10273. title: i18n('syncDataSuccess')
  10274. });
  10275. } else {
  10276. external_Swal_default().fire({
  10277. icon: 'error',
  10278. title: i18n('syncDataFailed')
  10279. });
  10280. }
  10281. });
  10282. $('#download-data').on('click', async () => {
  10283. const {
  10284. TOKEN,
  10285. GIST_ID,
  10286. FILE_NAME
  10287. } = GM_getValue('gistOptions') || {};
  10288. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10289. return external_Swal_default().fire({
  10290. icon: 'error',
  10291. title: i18n('saveAndTestNotice')
  10292. }).then(syncOptions);
  10293. }
  10294. external_Swal_default().fire({
  10295. icon: 'info',
  10296. title: i18n('downloadingData')
  10297. });
  10298. const data = await getGistData(TOKEN, GIST_ID, FILE_NAME);
  10299. if (!data) {
  10300. return external_Swal_default().fire({
  10301. icon: 'error',
  10302. title: i18n('checkedNoData')
  10303. }).then(syncOptions);
  10304. }
  10305. external_Swal_default().update({
  10306. icon: 'info',
  10307. title: i18n('savingData')
  10308. });
  10309. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10310. for (const [ name, value ] of Object.entries(data)) {
  10311. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10312. continue;
  10313. }
  10314. GM_setValue(name, value);
  10315. }
  10316. external_Swal_default().fire({
  10317. icon: 'success',
  10318. title: i18n('syncDataSuccess')
  10319. });
  10320. });
  10321. } catch (error) {
  10322. throwError(error, 'syncOptions');
  10323. }
  10324. };
  10325. const dataSync = syncOptions;
  10326. class Setting {
  10327. name = 'Setting';
  10328. buttons = [ 'saveGlobalOptions', 'syncData', 'tasksHistory' ];
  10329. syncData = dataSync;
  10330. tasksHistory() {
  10331. GM_openInTab('https://auto-task-v4.hclonely.com/history.html', {
  10332. active: true
  10333. });
  10334. }
  10335. static test() {
  10336. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/setting.html';
  10337. }
  10338. before() {
  10339. try {
  10340. $('body').html('').addClass('auto-task-options');
  10341. } catch (error) {
  10342. throwError(error, 'Setting.before');
  10343. }
  10344. }
  10345. after() {
  10346. try {
  10347. this.#environment();
  10348. changeGlobalOptions('page');
  10349. whiteList('page');
  10350. $('input[name="other.twitterVerifyId"]').after(`<button id="getTwitterUserId" type="button">${i18n('getTwitterUserId')}</button>`);
  10351. $('#getTwitterUserId').on('click', () => {
  10352. this.#getId('twitterUser');
  10353. });
  10354. $('input[name="other.youtubeVerifyChannel"]').after(`<button id="getYoutubeChannelId" type="button">${i18n('getYoutubeChannelId')}</button>`);
  10355. $('#getYoutubeChannelId').on('click', () => {
  10356. this.#getId('youtubeChannel');
  10357. });
  10358. $('input[name^="position"]').on('input', function() {
  10359. const type = $(this).attr('name').replace('position.', '');
  10360. const xLabel = 'rightleft';
  10361. const yLabel = 'topbottpm';
  10362. switch (type) {
  10363. case 'buttonSideX':
  10364. case 'buttonSideY':
  10365. case 'buttonDistance':
  10366. {
  10367. const distance = $('input[name="position.buttonDistance"]').val();
  10368. const sideX = $('input[name="position.buttonSideX"]').val();
  10369. const sideY = $('input[name="position.buttonSideY"]').val();
  10370. if (![ 'right', 'left' ].includes(sideX)) {
  10371. break;
  10372. }
  10373. if (![ 'top', 'bottom' ].includes(sideY)) {
  10374. break;
  10375. }
  10376. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10377. break;
  10378. }
  10379. const distanceArr = distance.split(',');
  10380. $('#auto-task-buttons').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10381. break;
  10382. }
  10383.  
  10384. case 'showButtonSideX':
  10385. case 'showButtonSideY':
  10386. case 'showButtonDistance':
  10387. {
  10388. const distance = $('input[name="position.showButtonDistance"]').val();
  10389. const sideX = $('input[name="position.showButtonSideX"]').val();
  10390. const sideY = $('input[name="position.showButtonSideY"]').val();
  10391. if (![ 'right', 'left' ].includes(sideX)) {
  10392. break;
  10393. }
  10394. if (![ 'top', 'bottom' ].includes(sideY)) {
  10395. break;
  10396. }
  10397. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10398. break;
  10399. }
  10400. const distanceArr = distance.split(',');
  10401. $('div.show-button-div').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10402. break;
  10403. }
  10404.  
  10405. case 'logSideX':
  10406. case 'logSideY':
  10407. case 'logDistance':
  10408. {
  10409. const distance = $('input[name="position.logDistance"]').val();
  10410. const sideX = $('input[name="position.logSideX"]').val();
  10411. const sideY = $('input[name="position.logSideY"]').val();
  10412. if (![ 'right', 'left' ].includes(sideX)) {
  10413. break;
  10414. }
  10415. if (![ 'top', 'bottom' ].includes(sideY)) {
  10416. break;
  10417. }
  10418. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10419. break;
  10420. }
  10421. const distanceArr = distance.split(',');
  10422. $('#auto-task-info').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10423. break;
  10424. }
  10425.  
  10426. default:
  10427. break;
  10428. }
  10429. });
  10430. $('input[name^="hotKey"]').attr('readonly', 'readonly').off('keydown').on('keydown', function(event) {
  10431. let functionKey = '';
  10432. if (event.altKey) {
  10433. functionKey += 'alt + ';
  10434. } else if (event.ctrlKey) {
  10435. functionKey += 'ctrl + ';
  10436. } else if (event.shiftKey) {
  10437. functionKey += 'shift + ';
  10438. }
  10439. $(this).val(functionKey + (event.key.length === 1 ? event.key.toLowerCase() : ''));
  10440. });
  10441. } catch (error) {
  10442. throwError(error, 'Setting.after');
  10443. }
  10444. }
  10445. saveGlobalOptions() {
  10446. try {
  10447. saveData();
  10448. } catch (error) {
  10449. throwError(error, 'Setting.saveGlobalOptions');
  10450. }
  10451. }
  10452. #getId(social) {
  10453. try {
  10454. external_Swal_default().fire({
  10455. title: i18n('getId', i18n(social)),
  10456. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10457. <button id="link2id" data-type="${social}" class="swal2-confirm swal2-styled">获取id</button>`,
  10458. showCancelButton: true,
  10459. cancelButtonText: i18n('close'),
  10460. showConfirmButton: false
  10461. });
  10462. $('#link2id').on('click', async function() {
  10463. const link = $('#socialLink').val();
  10464. if (!link) {
  10465. return;
  10466. }
  10467. const type = $(this).attr('data-type');
  10468. if (type === 'twitterUser') {
  10469. const name = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || link;
  10470. $('#socialLink').val(await new social_Twitter().userName2id(name) || '');
  10471. } else if (type === 'youtubeChannel') {
  10472. const name = /^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www.youtube.com\/.*/.test(link) ? link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1] : link;
  10473. $('#socialLink').val((await getInfo(name, 'channel'))?.params?.channelId || '');
  10474. }
  10475. });
  10476. } catch (error) {
  10477. throwError(error, 'Setting.getId');
  10478. }
  10479. }
  10480. #environment() {
  10481. try {
  10482. const userAgent = (0, javascript_utils_umd_min.ua)();
  10483. const environmentForm = `<form id="environmentForm" class="auto-task-form">
  10484. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('name')}</td><td>${i18n('version')}</td></tr></thead><tbody>
  10485. <tr><td>${i18n('os')}</td><td>${userAgent.os}</td><td>${userAgent.osVersion}</td></tr>
  10486. <tr><td>${i18n('browser')}</td><td>${userAgent.browserZH}</td><td>${userAgent.browserVersion}</td></tr>
  10487. <tr><td>${i18n('scriptManager')}</td><td>${GM_info.scriptHandler}</td><td>${GM_info.version}</td></tr>
  10488. <tr><td>${i18n('script')}</td><td>${GM_info.script.name}</td><td>${GM_info.script.version}</td></tr>
  10489. </tbody></table></form>`;
  10490. $('body').append(`<h2>${i18n('environment')}</h2>${environmentForm}`);
  10491. } catch (error) {
  10492. throwError(error, 'Setting.environment');
  10493. }
  10494. }
  10495. }
  10496. const website_Setting = Setting;
  10497. class History extends website_Keylol {
  10498. name = 'History';
  10499. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect', 'clearHistory' ];
  10500. static test() {
  10501. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/history.html';
  10502. }
  10503. before() {
  10504. try {
  10505. $('body').html('<div class="container"></div>').addClass('auto-task-history');
  10506. const data = GM_listValues() || [];
  10507. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  10508. for (const item of tasksHistory) {
  10509. this.#addItem(item);
  10510. }
  10511. } catch (error) {
  10512. throwError(error, 'History.before');
  10513. }
  10514. }
  10515. clearHistory() {
  10516. try {
  10517. const data = GM_listValues() || [];
  10518. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  10519. for (const item of tasksHistory) {
  10520. GM_deleteValue(item);
  10521. }
  10522. external_Swal_default().fire({
  10523. title: i18n('clearHistoryFinished'),
  10524. icon: 'success'
  10525. });
  10526. } catch (error) {
  10527. throwError(error, 'History.clearHistory');
  10528. }
  10529. }
  10530. #addItem(item) {
  10531. try {
  10532. const tasksData = GM_getValue(item);
  10533. if (!tasksData?.tasks) {
  10534. return;
  10535. }
  10536. let html = '';
  10537. let title = '';
  10538. let link = '';
  10539. const [ website, id ] = item.split('-');
  10540. switch (website) {
  10541. case 'fawTasks':
  10542. title = `Freeanywhere[${id}]`;
  10543. link = `https://freeanywhere.net/#/giveaway/${id}`;
  10544. break;
  10545.  
  10546. case 'gasTasks':
  10547. title = `Giveawaysu[${id}]`;
  10548. link = `https://giveaway.su/giveaway/view/${id}`;
  10549. break;
  10550.  
  10551. case 'gcTasks':
  10552. title = `GiveeClub[${id}]`;
  10553. link = `https://givee.club/event/${id}`;
  10554. break;
  10555.  
  10556. case 'gkTasks':
  10557. title = `Givekey[${id}]`;
  10558. link = `https://givekey.ru/giveaway/${id}`;
  10559. break;
  10560.  
  10561. case 'gleamTasks':
  10562. title = `Gleam[${id}]`;
  10563. link = `https://gleam.io${id}`;
  10564. break;
  10565.  
  10566. case 'khTasks':
  10567. title = `keyhub[${id}]`;
  10568. link = `https://key-hub.eu/giveaway/${id}`;
  10569. break;
  10570.  
  10571. case 'prysTasks':
  10572. title = `Prys[${id}]`;
  10573. link = `https://prys.revadike.com/giveaway/?id=${id}`;
  10574. break;
  10575.  
  10576. default:
  10577. return;
  10578. }
  10579. for (const [ social, types ] of Object.entries(tasksData.tasks)) {
  10580. for (const [ type, tasks ] of Object.entries(types)) {
  10581. for (const task of tasks) {
  10582. 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>`;
  10583. }
  10584. }
  10585. }
  10586. $('.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>`);
  10587. $('span.delete-task').on('click', function() {
  10588. const itemName = $(this).attr('data-name');
  10589. if (itemName) {
  10590. GM_deleteValue(itemName);
  10591. $(`div.card[data-name="${itemName}"]`).remove();
  10592. external_Swal_default().fire({
  10593. title: i18n('clearTaskFinished'),
  10594. text: itemName,
  10595. icon: 'success'
  10596. });
  10597. } else {
  10598. external_Swal_default().fire({
  10599. title: i18n('clearTaskFailed'),
  10600. icon: 'error'
  10601. });
  10602. }
  10603. });
  10604. } catch (error) {
  10605. throwError(error, 'History.addItem');
  10606. }
  10607. }
  10608. }
  10609. const website_History = History;
  10610. 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 ];
  10611. const websiteOptions = function(website, options) {
  10612. try {
  10613. let websiteOptionsForm = `<form id="websiteOptionsForm" class="auto-task-form">
  10614. <table class="auto-task-table"><thead><tr><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  10615. for (const [ option, value ] of Object.entries(options)) {
  10616. websiteOptionsForm += `<tr><td>${option}</td><td><input class="editOption" type="text" name="${option}" value="${value}"/></td></tr>`;
  10617. }
  10618. websiteOptionsForm += '</tbody></table></form>';
  10619. external_Swal_default().fire({
  10620. title: i18n('websiteOptions'),
  10621. html: websiteOptionsForm,
  10622. showConfirmButton: true,
  10623. confirmButtonText: i18n('save'),
  10624. showCancelButton: true,
  10625. cancelButtonText: i18n('close')
  10626. }).then(({
  10627. isConfirmed
  10628. }) => {
  10629. if (isConfirmed) {
  10630. $('#websiteOptionsForm').serializeArray().map(value => {
  10631. options[value.name] = value.value;
  10632. return value;
  10633. });
  10634. GM_setValue(`${website}Options`, options);
  10635. external_Swal_default().fire({
  10636. title: i18n('changeWebsiteOptionsSuccess'),
  10637. icon: 'success'
  10638. });
  10639. }
  10640. });
  10641. } catch (error) {
  10642. throwError(error, 'websiteOptions');
  10643. }
  10644. };
  10645. const options = websiteOptions;
  10646. const external_keyboardJS_namespaceObject = keyboardJS;
  10647. var external_keyboardJS_default = __webpack_require__.n(external_keyboardJS_namespaceObject);
  10648. const checkUpdate = async (updateLink, auto) => {
  10649. try {
  10650. const checkUrl = `${updateLink}package.json?time=${new Date().getTime()}`;
  10651. const {
  10652. result,
  10653. statusText,
  10654. status,
  10655. data
  10656. } = await tools_httpRequest({
  10657. url: checkUrl,
  10658. responseType: 'json',
  10659. method: 'GET',
  10660. timeout: 3e4
  10661. });
  10662. if (result === 'Success') {
  10663. if (data?.response?.version) {
  10664. return data.response;
  10665. }
  10666. if (!auto) {
  10667. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${data?.statusText}(${data?.status})]`);
  10668. }
  10669. return false;
  10670. }
  10671. if (!auto) {
  10672. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${result}:${statusText}(${status})]`);
  10673. }
  10674. return false;
  10675. } catch (error) {
  10676. throwError(error, 'checkUpdate');
  10677. return false;
  10678. }
  10679. };
  10680. const hasNewVersion = (currentVersion, remoteVersion) => {
  10681. try {
  10682. const [ currentRealVersion ] = currentVersion.split('-');
  10683. const [ remoteRealVersion, isPreview ] = remoteVersion.split('-');
  10684. if (isPreview && !globalOptions.other.receivePreview) {
  10685. return false;
  10686. }
  10687. const [ currentVersion1, currentVersion2, currentVersion3 ] = currentRealVersion.split('.').map(value => parseInt(value, 10));
  10688. const [ remoteVersion1, remoteVersion2, remoteVersion3 ] = remoteRealVersion.split('.').map(value => parseInt(value, 10));
  10689. if (remoteVersion1 > currentVersion1) {
  10690. return true;
  10691. }
  10692. if (remoteVersion1 < currentVersion1) {
  10693. return false;
  10694. }
  10695. if (remoteVersion2 > currentVersion2) {
  10696. return true;
  10697. }
  10698. if (remoteVersion2 < currentVersion2) {
  10699. return false;
  10700. }
  10701. if (remoteVersion3 > currentVersion3) {
  10702. return true;
  10703. }
  10704. return false;
  10705. } catch (error) {
  10706. throwError(error, 'compareVersion');
  10707. return false;
  10708. }
  10709. };
  10710. const updateChecker = async () => {
  10711. try {
  10712. const currentVersion = GM_info.script.version;
  10713. const updateSource = globalOptions.other.autoUpdateSource.toLowerCase();
  10714. const updateLinks = {
  10715. github: 'https://github.com/HCLonely/auto-task-new/raw/main/',
  10716. jsdelivr: 'https://cdn.jsdelivr.net/gh/HCLonely/auto-task-v4@main/',
  10717. standby: 'https://auto-task-v4.hclonely.com/'
  10718. };
  10719. let version;
  10720. let updateLink = '';
  10721. let packageData;
  10722. if ([ 'github', 'jsdelivr', 'standby' ].includes(updateSource)) {
  10723. updateLink = updateLinks[updateSource];
  10724. packageData = await checkUpdate(updateLink, false);
  10725. } else {
  10726. updateLink = updateLinks.github;
  10727. packageData = await checkUpdate(updateLink, true);
  10728. if (!packageData) {
  10729. updateLink = updateLinks.jsdelivr;
  10730. packageData = await checkUpdate(updateLink, true);
  10731. if (!packageData) {
  10732. updateLink = updateLinks.standby;
  10733. packageData = await checkUpdate(updateLink, true);
  10734. }
  10735. }
  10736. }
  10737. if (packageData) {
  10738. version = packageData.version || currentVersion;
  10739. } else {
  10740. version = currentVersion;
  10741. scripts_echoLog({}).error(i18n('checkUpdateFailed'));
  10742. }
  10743. if (packageData && hasNewVersion(currentVersion, version)) {
  10744. scripts_echoLog({
  10745. html: `<li><font>${i18n('newVersionNotice', version, `${updateLink}dist/${GM_info.script.name}.user.js`)}</font></li>`
  10746. });
  10747. scripts_echoLog({
  10748. html: `<li>${i18n('updateText', version)}</li><ol class="update-text">${packageData.change?.map(change => `<li>${change}</li>`).join('')}<li>${i18n('updateHistory')}</li></ol>`
  10749. });
  10750. }
  10751. } catch (error) {
  10752. throwError(error, 'updateChecker');
  10753. }
  10754. };
  10755. const scripts_updateChecker = updateChecker;
  10756. window.STYLE = GM_addStyle(auto_task.A + GM_getResourceText('style'));
  10757. window.DEBUG = !!globalOptions.other?.debug;
  10758. window.TRACE = !!globalOptions.other?.debug && typeof console.trace === 'function';
  10759. const loadScript = async () => {
  10760. if (window.name === 'ATv4_twitchAuth' && window.location.hostname === 'www.twitch.tv') {
  10761. const authToken = external_Cookies_default().get('auth-token');
  10762. const isLogin = !!external_Cookies_default().get('login');
  10763. if (isLogin) {
  10764. GM_setValue('twitchAuth', {
  10765. authToken: authToken,
  10766. clientVersion: __twilightBuildID,
  10767. clientId: commonOptions?.headers?.['Client-ID'],
  10768. deviceId: commonOptions?.headers?.['Device-ID'],
  10769. clientSessionId: window.localStorage.local_storage_app_session_id.replace(/"/g, '')
  10770. });
  10771. window.close();
  10772. external_Swal_default().fire('', i18n('closePageNotice'));
  10773. } else {
  10774. external_Swal_default().fire('', i18n('needLogin'));
  10775. }
  10776. return;
  10777. }
  10778. if (window.name === 'ATv4_redditAuth' && window.location.hostname === 'www.reddit.com') {
  10779. const betaButton = $('#redesign-beta-optin-btn');
  10780. if (betaButton.length > 0) {
  10781. return betaButton[0].click();
  10782. }
  10783. window.close();
  10784. external_Swal_default().fire('', i18n('closePageNotice'));
  10785. return;
  10786. }
  10787. let website;
  10788. for (const Website of Websites) {
  10789. if (Website.test()) {
  10790. website = new Website();
  10791. break;
  10792. }
  10793. }
  10794. if (!website) {
  10795. console.log('%c%s', 'color:#ff0000', 'Auto-Task[Warning]: 脚本停止加载,当前网站不支持!');
  10796. return;
  10797. }
  10798. if (website?.before) {
  10799. await website?.before();
  10800. }
  10801. $('body').append(`
  10802. <div id="auto-task-info"
  10803. style="display:${globalOptions.other.defaultShowLog ? 'block' : 'none'};
  10804. ${globalOptions.position.logSideX}:${globalOptions.position.logDistance.split(',')[0]}px;
  10805. ${globalOptions.position.logSideY}:${globalOptions.position.logDistance.split(',')[1]}px;">
  10806. </div>
  10807. <div id="auto-task-buttons"
  10808. style="display:${globalOptions.other.defaultShowButton ? 'block' : 'none'};
  10809. ${globalOptions.position.buttonSideX}:${globalOptions.position.buttonDistance.split(',')[0]}px;
  10810. ${globalOptions.position.buttonSideY}:${globalOptions.position.buttonDistance.split(',')[1]}px;">
  10811. </div>
  10812. <div class="show-button-div"
  10813. style="display:${globalOptions.other.defaultShowButton ? 'none' : 'block'};
  10814. ${globalOptions.position.showButtonSideX}:${globalOptions.position.showButtonDistance.split(',')[0]}px;
  10815. ${globalOptions.position.showButtonSideY}:${globalOptions.position.showButtonDistance.split(',')[1]}px;">
  10816. <a class="auto-task-website-btn"
  10817. href="javascript:void(0);"
  10818. target="_self"
  10819. title="${i18n('showButton')}"> </a>
  10820. </div>
  10821. `);
  10822. $('div.show-button-div').on('click', () => {
  10823. $('#auto-task-buttons').show();
  10824. $('div.show-button-div').hide();
  10825. });
  10826. const toggleLog = () => {
  10827. const $this = $('#toggle-log');
  10828. const status = $this.attr('data-status');
  10829. if (status === 'show') {
  10830. $('#auto-task-info').hide();
  10831. $this.attr('data-status', 'hide').text(i18n('showLog'));
  10832. } else {
  10833. $('#auto-task-info').show();
  10834. $this.attr('data-status', 'show').text(i18n('hideLog'));
  10835. }
  10836. };
  10837. external_keyboardJS_default().bind(globalOptions.hotKey.doTaskKey, () => {
  10838. if (website.doTask) {
  10839. website.doTask();
  10840. }
  10841. });
  10842. external_keyboardJS_default().bind(globalOptions.hotKey.undoTaskKey, () => {
  10843. if (website.undoTask) {
  10844. website.undoTask();
  10845. }
  10846. });
  10847. external_keyboardJS_default().bind(globalOptions.hotKey.toggleLogKey, toggleLog);
  10848. if (website?.after) {
  10849. await website?.after();
  10850. }
  10851. if (website?.buttons && $('#auto-task-buttons').children().length === 0) {
  10852. $('#auto-task-buttons').addClass(`${website.name}-buttons`);
  10853. for (const button of website.buttons) {
  10854. if (website[button]) {
  10855. const btnElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">${i18n(button)}</a></p>`);
  10856. btnElement.find('a.auto-task-website-btn').on('click', () => {
  10857. website[button]();
  10858. });
  10859. $('#auto-task-buttons').append(btnElement);
  10860. }
  10861. }
  10862. }
  10863. const hideButtonElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">
  10864. ${i18n('hideButton')}</a></p>`);
  10865. hideButtonElement.find('a.auto-task-website-btn').on('click', () => {
  10866. $('#auto-task-buttons').hide();
  10867. $('div.show-button-div').show();
  10868. });
  10869. 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'}">
  10870. ${globalOptions.other.defaultShowLog ? i18n('hideLog') : i18n('showLog')}</a></p>`);
  10871. toggleLogElement.find('a.auto-task-website-btn').on('click', toggleLog);
  10872. $('#auto-task-buttons').append(hideButtonElement).append(toggleLogElement);
  10873. if (website?.options) {
  10874. GM_registerMenuCommand(i18n('changeWebsiteOptions'), () => {
  10875. options(website.name, website.options);
  10876. });
  10877. }
  10878. if (website.name !== 'Setting') {
  10879. GM_registerMenuCommand(i18n('changeGlobalOptions'), () => {
  10880. changeGlobalOptions('swal');
  10881. });
  10882. GM_registerMenuCommand(i18n('settingPage'), () => {
  10883. GM_openInTab('https://auto-task-v4.hclonely.com/setting.html', {
  10884. active: true
  10885. });
  10886. });
  10887. }
  10888. console.log('%c%s', 'color:#1bbe1a', 'Auto-Task[Load]: 脚本加载完成');
  10889. const [ v1, v2 ] = GM_info.version.split('.');
  10890. if (!(parseInt(v1, 10) >= 5 && parseInt(v2, 10) >= 2)) {
  10891. scripts_echoLog({}).error(i18n('versionNotMatched'));
  10892. }
  10893. if (!GM_getValue('notice')) {
  10894. external_Swal_default().fire({
  10895. title: i18n('swalNotice'),
  10896. icon: 'warning'
  10897. }).then(() => {
  10898. GM_openInTab(i18n('noticeLink'), {
  10899. active: true
  10900. });
  10901. GM_setValue('notice', new Date().getTime());
  10902. });
  10903. scripts_echoLog({
  10904. html: `<li><font class="warning">${i18n('echoNotice', i18n('noticeLink'))}</font></li>`
  10905. }).font?.find('a').on('click', () => {
  10906. GM_setValue('notice', new Date().getTime());
  10907. });
  10908. }
  10909. scripts_updateChecker();
  10910. };
  10911. if (window.location.hostname === 'discord.com') {
  10912. const LocalStorage = window.localStorage;
  10913. if (window.name === 'ATv4_discordAuth') {
  10914. window.localStorage.removeItem = () => true;
  10915. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  10916. if (discordAuth && discordAuth.length > 0) {
  10917. GM_setValue('discordAuth', {
  10918. auth: discordAuth
  10919. });
  10920. window.close();
  10921. external_Swal_default().fire('', i18n('closePageNotice'));
  10922. } else {
  10923. external_Swal_default().fire({
  10924. text: i18n('getDiscordAuthFailed'),
  10925. icon: 'error'
  10926. });
  10927. }
  10928. } else {
  10929. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  10930. if (discordAuth && discordAuth.length > 0) {
  10931. GM_setValue('discordAuth', {
  10932. auth: discordAuth
  10933. });
  10934. }
  10935. }
  10936. } else if (window.location.hostname === 'opquests.com') {
  10937. loadScript();
  10938. } else if ((window.name === 'ATv4_updateStoreAuth' || GM_getValue('ATv4_updateStoreAuth')) && window.location.host === 'store.steampowered.com') {
  10939. $(() => {
  10940. if ($('[data-miniprofile]').length === 0) {
  10941. return;
  10942. }
  10943. const storeSessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  10944. if (storeSessionID) {
  10945. GM_deleteValue('ATv4_updateStoreAuth');
  10946. GM_setValue('steamStoreAuth', {
  10947. storeSessionID: storeSessionID
  10948. });
  10949. window.close();
  10950. external_Swal_default().fire('', i18n('closePageNotice'));
  10951. } else {
  10952. external_Swal_default().fire({
  10953. title: 'Error: Get "sessionID" failed',
  10954. icon: 'error'
  10955. });
  10956. }
  10957. });
  10958. } else if ((window.name === 'ATv4_updateCommunityAuth' || GM_getValue('ATv4_updateCommunityAuth')) && window.location.host === 'steamcommunity.com') {
  10959. $(() => {
  10960. const steam64Id = document.body.innerHTML.match(/g_steamID = "(.+?)";/)?.[1];
  10961. const communitySessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  10962. if (steam64Id && communitySessionID) {
  10963. GM_deleteValue('ATv4_updateCommunityAuth');
  10964. GM_setValue('steamCommunityAuth', {
  10965. steam64Id: steam64Id,
  10966. communitySessionID: communitySessionID
  10967. });
  10968. window.close();
  10969. external_Swal_default().fire('', i18n('closePageNotice'));
  10970. } else {
  10971. setTimeout(() => {
  10972. external_Swal_default().fire({
  10973. title: 'Error: Get "sessionID" failed',
  10974. icon: 'error'
  10975. });
  10976. }, 3e3);
  10977. }
  10978. });
  10979. } else {
  10980. if (window.location.hostname === 'key-hub.eu') {
  10981. unsafeWindow.keyhubtracker = 1;
  10982. unsafeWindow.gaData = {};
  10983. }
  10984. $(loadScript);
  10985. }
  10986. }();
  10987. })();