auto-task-v4

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

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

  1. // ==UserScript==
  2. // @name auto-task-v4
  3. // @namespace auto-task-v4
  4. // @version 4.7.0
  5. // @description 自动完成 Freeanywhere,Giveawaysu,GiveeClub,Givekey,Gleam,Indiedb,keyhub,OpiumPulses,Opquests,SweepWidget 等网站的任务。
  6. // @description:en Automatically complete the tasks of FreeAnyWhere, GiveawaySu, GiveeClub, Givekey, Gleam, Indiedb, keyhub, OpiumPulses, Opquests, SweepWidget websites.
  7. // @author HCLonely
  8. // @license MIT
  9. // @run-at document-start
  10. // @homepage https://auto-task-doc.js.org/
  11. // @supportURL https://github.com/HCLonely/auto-task-v4/issues
  12. // @icon https://auto-task-v4.hclonely.com/favicon.ico
  13.  
  14. // @include *://freeanywhere.net/*
  15. // @include *://giveaway.su/giveaway/view/*
  16. // @include *://givee.club/*/event/*
  17. // @include *://givekey.ru/giveaway/*
  18. // @include *://www.indiedb.com/giveaways*
  19. // @include *://key-hub.eu/giveaway/*
  20. // @include *://keylol.com/*
  21. // @include *://www.opiumpulses.com/giveaways
  22. // @include *://prys.revadike.com/giveaway/?id=*
  23. // @include *://opquests.com/quests/*
  24. // @include *://gleam.io/*
  25. // @include *://sweepwidget.com/view/*
  26. // @include *://giveawayhopper.com/c/*
  27.  
  28. // @include *://discord.com/*
  29. // @include *://www.twitch.tv/*
  30. // @include *://www.youtube.com/*
  31. // @include *://*.reddit.com/*
  32. // @include *://twitter.com/settings/account?k*
  33. // @include *://x.com/settings/account*
  34. // @include *://steamcommunity.com/*
  35. // @include *://store.steampowered.com/*
  36. // @include https://auto-task-v4.hclonely.com/setting.html
  37. // @include https://auto-task-v4.hclonely.com/history.html
  38.  
  39. // @grant GM_setValue
  40. // @grant GM_getValue
  41. // @grant GM_listValues
  42. // @grant GM_deleteValue
  43. // @grant GM_addStyle
  44. // @grant GM_xmlhttpRequest
  45. // @grant GM_registerMenuCommand
  46. // @grant GM_info
  47. // @grant GM_openInTab
  48. // @grant GM_setClipboard
  49. // @grant GM_getResourceText
  50. // @grant GM_cookie
  51. // @grant GM_addValueChangeListener
  52. // @grant GM_removeValueChangeListener
  53. // @grant unsafeWindow
  54. // @grant window.close
  55. // @grant window.localStorage
  56. // @grant window.sessionStorage
  57. // @grant window.focus
  58.  
  59. // @connect cdn.jsdelivr.net
  60. // @connect store.steampowered.com
  61. // @connect steamcommunity.com
  62. // @connect login.steampowered.com
  63. // @connect twitter.com
  64. // @connect x.com
  65. // @connect api.twitter.com
  66. // @connect youtube.com
  67. // @connect www.youtube.com
  68. // @connect facebook.com
  69. // @connect instagram.com
  70. // @connect vk.com
  71. // @connect twitch.tv
  72. // @connect www.twitch.tv
  73. // @connect gql.twitch.tv
  74. // @connect github.com
  75. // @connect discordapp.com
  76. // @connect discord.gg
  77. // @connect discord.com
  78. // @connect www.reddit.com
  79. // @connect oauth.reddit.com
  80. // @connect raw.githubusercontent.com
  81. // @connect t.me
  82. // @connect bit.ly
  83. // @connect giveaway.su
  84. // @connect google.com
  85. // @connect www.vloot.io
  86. // @connect givee.club
  87. // @connect gleam.io
  88. // @connect www.indiedb.com
  89. // @connect key-hub.eu
  90. // @connect opquests.com
  91. // @connect itch.io
  92. // @connect auto-task-v4.hclonely.com
  93. // @connect giveawayhopper.com
  94. // @connect *
  95. // @require https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
  96. // @require https://cdn.jsdelivr.net/npm/js-cookie@3.0.1/dist/js.cookie.min.js
  97. // @require https://cdn.jsdelivr.net/npm/regenerator-runtime@0.13.5/runtime.min.js
  98. // @require https://cdn.jsdelivr.net/npm/js-sha1@0.6.0/src/sha1.min.js
  99. // @require https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js
  100. // @resource style https://cdn.jsdelivr.net/npm/sweetalert2@11.3.5/dist/sweetalert2.min.css
  101. // @require https://cdn.jsdelivr.net/npm/keyboardjs@2.6.4/dist/keyboard.min.js
  102. // @require https://cdn.jsdelivr.net/npm/dayjs@1.10.7/dayjs.min.js
  103.  
  104. // @noframes
  105. // ==/UserScript==
  106.  
  107. console.log('%c%s', 'color:blue', 'Auto-Task[Load]: 脚本开始加载');
  108. (function() {
  109. var __webpack_modules__ = {
  110. 991: function(__unused_webpack_module, exports) {
  111. !function(e, n) {
  112. true ? n(exports) : 0;
  113. }(this, function(e) {
  114. 'use strict';
  115. var t = function() {
  116. return (t = Object.assign || function(e) {
  117. for (var n, o = 1, t = arguments.length; o < t; o++) {
  118. for (var r in n = arguments[o]) {
  119. Object.prototype.hasOwnProperty.call(n, r) && (e[r] = n[r]);
  120. }
  121. }
  122. return e;
  123. }).apply(this, arguments);
  124. };
  125. function r(e, n, o) {
  126. if (o || 2 === arguments.length) {
  127. for (var t, r = 0, i = n.length; r < i; r++) {
  128. !t && r in n || ((t = t || Array.prototype.slice.call(n, 0, r))[r] = n[r]);
  129. }
  130. }
  131. return e.concat(t || Array.prototype.slice.call(n));
  132. }
  133. function d(e) {
  134. return '[object Object]' === n(e);
  135. }
  136. function l(e, n) {
  137. var o = r(r([], n || [], !0), [ '_' ], !1).join('|');
  138. return e.replace(new RegExp('(('.concat(o, ')[a-z])+'), 'g'), function(e, n) {
  139. return n.replace(new RegExp(o), '').toLocaleUpperCase();
  140. });
  141. }
  142. var n = function(e) {
  143. return Object.prototype.toString.call(e);
  144. };
  145. var o = (i.prototype.init = function() {
  146. try {
  147. this.getSystemName(), this.getBrowserName();
  148. } catch (e) {
  149. console.warn('[UA formatter error] '.concat(e));
  150. }
  151. }, i.prototype.getEngine = function() {
  152. var e = this.agent;
  153. return -1 !== e.indexOf('Trident') ? 'Trident' : -1 !== e.indexOf('Firefox') ? 'Gecko' : -1 !== e.indexOf('Presto') ? 'Presto' : 'WebKit';
  154. }, i.prototype.getSystemName = function() {
  155. var e, n = (this.agent.match(/^[a-z]+\/\d+\.\d+\s?\(([a-z\d\s:;./_-]+)\)/i) || [])[1];
  156. try {
  157. var o = '';
  158. if (/Windows/i.test(n)) {
  159. var t = (n.match(/NT\s(\d+\.\d+)/) || [])[1];
  160. switch (this.info.os = 'Windows', t) {
  161. case '6.3':
  162. o = '8.1';
  163. break;
  164.  
  165. case '6.2':
  166. o = '8';
  167. break;
  168.  
  169. case '6.1':
  170. o = '7';
  171. break;
  172.  
  173. case '5.2':
  174. case '5.1':
  175. o = 'XP';
  176. break;
  177.  
  178. default:
  179. o = t;
  180. }
  181. return this.info.device = 'PC', void (this.info.osVersion = o);
  182. }
  183. if (/^Macintosh/i.test(n)) {
  184. return o = (n.match(/X\s((\d+(_|\.))+\d+)/) || [])[1], this.info.os = 'Macintosh',
  185. this.info.device = 'PC', void (this.info.osVersion = null !== (e = null == o ? void 0 : o.replace(/_/g, '.')) && void 0 !== e ? e : 'Unknown');
  186. }
  187. if (/^iPad/i.test(n)) {
  188. return o = (n.match(/((\d+_)+\d+)/) || [])[1], this.info.os = 'iPad',
  189. this.info.device = 'Tablet', void (this.info.osVersion = o.replace(/_/g, '.'));
  190. }
  191. if (/^iPhone/i.test(n)) {
  192. return o = (n.match(/((\d+_)+\d+)/) || [])[1], this.info.os = 'iPhone',
  193. this.info.device = 'Mobile', void (this.info.osVersion = o.replace(/_/g, '.'));
  194. }
  195. if (-1 !== n.indexOf('Android')) {
  196. var r = (n.match(/Android\s((\d+\.?)+\d?)/) || [])[1];
  197. return this.info.device = 'Mobile', this.info.os = 'Android', void (this.info.osVersion = r);
  198. }
  199. if (/Linux\s[a-z\d_]+/.test(n)) {
  200. return this.info.os = 'Linux', void (this.info.osVersion = 'Unknown');
  201. }
  202. this.info.os = 'Unknown', this.info.osVersion = 'Unknown';
  203. } catch (e) {
  204. this.info.os = 'Unknown', this.info.osVersion = 'Unknown';
  205. }
  206. }, i.prototype.getBrowserName = function() {
  207. var e = Object.keys(this.browserNameMap).map(function(e) {
  208. return new RegExp(''.concat(e, '(\\/|\\s)(\\d+\\.)+\\d+'));
  209. }), n = 1 < (n = (this.agent.match(/[a-z\d]+(\/|\s)(\d+\.)+\d+/gi) || []).filter(function(n) {
  210. return -1 !== e.findIndex(function(e) {
  211. return e.test(n);
  212. });
  213. })).length && !/^Safari/.test(n[n.length - 1]) ? n.reverse() : n;
  214. this.info = t(t({}, this.info), this._formatBrowserVersion(n[0]));
  215. }, i.prototype._formatBrowserVersion = function(e) {
  216. var n, o, t, r;
  217. try {
  218. for (var i = null !== (o = null === (n = e.match(/(?<name>[a-z\d]+)(\/|\s)(?<version>(\d+\.)+\d+)/i)) || void 0 === n ? void 0 : n.groups) && void 0 !== o ? o : {}, s = i.name, a = i.version, c = {}, f = 0, u = Object.entries(this.browserNameMap); f < u.length; f++) {
  219. var d = u[f], l = d[0], h = d[1];
  220. if (new RegExp(l).test(s)) {
  221. c = h;
  222. break;
  223. }
  224. }
  225. var p = {
  226. browserVersion: null != a ? a : 'Unknown',
  227. browser: null !== (t = c.en) && void 0 !== t ? t : 'Unknown',
  228. browserZH: null !== (r = (null == c ? void 0 : c.zh) || c.en) && void 0 !== r ? r : 'Unknown'
  229. };
  230. return 'Trident' === s && (p.browserVersion = {
  231. '4.0': 8,
  232. '5.0': 9,
  233. '6.0': 10,
  234. '7.0': 11
  235. }[a]), p;
  236. } catch (e) {
  237. return console.warn('[UA formatter error] '.concat(e)), {
  238. browser: 'Unknown',
  239. browserVersion: 'Unknown'
  240. };
  241. }
  242. }, i);
  243. function i(e) {
  244. this.agent = '', this.info = {
  245. browser: '',
  246. browserZH: '',
  247. browserVersion: '',
  248. os: '',
  249. osVersion: '',
  250. device: 'Unknown',
  251. engine: 'WebKit'
  252. }, this.browserNameMap = {
  253. MicroMessenger: {
  254. en: 'MicroMessenger',
  255. zh: '微信'
  256. },
  257. MetaSr: {
  258. en: 'MetaSr',
  259. zh: '搜狗浏览器'
  260. },
  261. 'QQ(Browser)?': {
  262. en: 'QQBrowser',
  263. zh: 'QQ浏览器'
  264. },
  265. UCBrowser: {
  266. en: 'UCBrowser',
  267. zh: 'UC浏览器'
  268. },
  269. '2345Explorer': {
  270. en: '2345Explorer',
  271. zh: '2345极速浏览器'
  272. },
  273. Mb2345Browser: {
  274. en: 'Mb2345Browser',
  275. zh: '2345手机浏览器'
  276. },
  277. Trident: {
  278. en: 'Internet Explorer'
  279. },
  280. 'Edge?': {
  281. en: 'Edge'
  282. },
  283. OPR: {
  284. en: 'Opera'
  285. },
  286. Vivaldi: {
  287. en: 'Vivaldi'
  288. },
  289. Firefox: {
  290. en: 'Firefox'
  291. },
  292. Chrome: {
  293. en: 'Chrome'
  294. },
  295. Safari: {
  296. en: 'Safari'
  297. }
  298. }, this.agent = e, this.init();
  299. var n = this.info, o = n.browser, e = n.browserVersion, n = n.osVersion;
  300. this.info = t(t({}, this.info), {
  301. engine: this.getEngine(),
  302. browserVersion: 'Safari' === o ? n : e
  303. });
  304. }
  305. function s() {
  306. this.cookies = {}, this.init();
  307. }
  308. var a = new (s.prototype.init = function() {
  309. var o = {};
  310. document.cookie.split(/;\s/).forEach(function(e) {
  311. var n = e.split(/=/), e = n[0], n = n[1];
  312. o[e] = n;
  313. }), this.cookies = o;
  314. }, s.prototype.getItem = function(e) {
  315. return this.cookies[e];
  316. }, s.prototype.getAllItems = function() {
  317. return this.cookies;
  318. }, s.prototype.setItem = function(e, n, o, t, r, i) {
  319. document.cookie = ''.concat(e, '=').concat(n).concat(o ? '; expires='.concat(o) : '').concat(t ? '; path='.concat(t) : '').concat(r ? '; domain='.concat(r) : '').concat(i ? '; secure' : '');
  320. }, s)();
  321. e.countDown = function e(n, o, t, r) {
  322. if (!window) {
  323. throw new Error('window is not defind.');
  324. }
  325. if (0 < n) {
  326. return r && r(), n--, window[o] = window.setTimeout(function() {
  327. e(n, o, t, r);
  328. }, 1e3), function() {
  329. return clearTimeout(window[o]);
  330. };
  331. }
  332. clearTimeout(window[o]), t && t();
  333. }, e.createRandomID = function(e) {
  334. void 0 === e && (e = 12);
  335. for (var n = [], o = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''), t = o.length, r = 0; r < e; r++) {
  336. n.push(o[Math.round(Math.random() * t)]);
  337. }
  338. return n.join('');
  339. }, e.dCookie = a, e.debounce = function(o, t, r) {
  340. var i;
  341. void 0 === t && (t = 0);
  342. var s = r = void 0 === r ? !1 : r;
  343. return function() {
  344. var e = this, n = arguments;
  345. s && (o.apply(this, arguments), s = !1), clearTimeout(i), i = setTimeout(function() {
  346. r ? s = !0 : o.apply(e, n);
  347. }, t);
  348. };
  349. }, e.deepCopy = function e(n) {
  350. if (d(n) || Array.isArray(n)) {
  351. var o, t = Array.isArray(n) ? [] : {};
  352. for (o in n) {
  353. t[o] = e(n[o]);
  354. }
  355. return t;
  356. }
  357. return n;
  358. }, e.formatQueryParams = function(e) {
  359. e = null === (e = /\?(?<params>(.*)=.+)/.exec(decodeURIComponent(e))) || void 0 === e ? void 0 : e.groups;
  360. if (!e) {
  361. return {};
  362. }
  363. for (var n = e.params.split('&'), t = {}, o = 0; o < n.length; o++) {
  364. n[o].replace(/([^?&]*)=([^?&]*)/, function(e, n, o) {
  365. return t[n] = o, e;
  366. });
  367. }
  368. return t;
  369. }, e.formatThousandth = function(e) {
  370. var n = ''.concat(e).split('.'), e = n[0], n = n[1], n = void 0 === n ? '' : n, e = e.replace(/\d{1,3}(?=(\d{3})+$)/g, '$&,');
  371. return ''.concat(e).concat(n ? '.'.concat(n) : '');
  372. }, e.generateTree = function e(n, o, t, r) {
  373. for (var i = [], s = 0; s < n.length; s++) {
  374. var a = n[s];
  375. a[t] === o && (i.push(a), a.children = e(n, a[null != r ? r : 'id'], t, r));
  376. }
  377. return i;
  378. }, e.isEmpty = function(e) {
  379. return Array.isArray(e) ? 0 === e.length : d(e) ? 0 === Object.keys(e).length : [ '[object Set]', '[object Map]' ].includes(n(e)) ? 0 === e.size : [ null, void 0, '' ].includes(e);
  380. }, e.isFunction = function(e) {
  381. return '[object Function]' === n(e);
  382. }, e.isImageUrl = function(e) {
  383. return /\.((png)|(jpe?g)|(gif)|(svg)|(webp))$/gi.test(e);
  384. }, e.isObject = d, e.isRegexp = function(e) {
  385. return '[object RegExp]' === n(e);
  386. }, e.objectKeyToCamelCase = function e(n, o, t) {
  387. if (Array.isArray(n)) {
  388. for (var r = [], i = 0; i < n.length; i++) {
  389. r[i] = e(o && n[i][o] ? n[i][o] : n[i], o, t);
  390. }
  391. } else if (d(n)) {
  392. r = {};
  393. for (var s = o && n[o] ? n[o] : n, a = 0, c = Object.entries(s); a < c.length; a++) {
  394. var f = (u = c[a])[0], u = u[1];
  395. Array.isArray(u) || d(s) ? r[l(f, t)] = e(u, o, t) : r[l(f, t)] = u;
  396. }
  397. } else {
  398. r = n;
  399. }
  400. return r;
  401. }, e.realType = n, e.searchParams = function(e, n) {
  402. return void 0 === e && (e = null === location || void 0 === location ? void 0 : location.search),
  403. new URLSearchParams(e).get(n);
  404. }, e.toLowerCamelCase = l, e.toUnderline = function(e) {
  405. return e.replace(/([A-Z])/g, function(e) {
  406. return '_'.concat(e.toLocaleLowerCase());
  407. });
  408. }, e.ua = function(e) {
  409. return void 0 === e && (e = navigator.userAgent), new o(e).info;
  410. }, Object.defineProperty(e, '__esModule', {
  411. value: !0
  412. });
  413. });
  414. },
  415. 675: function(module, __webpack_exports__, __webpack_require__) {
  416. 'use strict';
  417. __webpack_require__.d(__webpack_exports__, {
  418. A: function() {
  419. return __WEBPACK_DEFAULT_EXPORT__;
  420. }
  421. });
  422. var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(601);
  423. var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = __webpack_require__.n(_node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
  424. var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(314);
  425. var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = __webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
  426. var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()(_node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default());
  427. ___CSS_LOADER_EXPORT___.push([ module.id, `.colorful-button,#auto-task-buttons a.auto-task-website-btn,.show-button-div a.auto-task-website-btn,body.auto-task-options .auto-task-form table button{position:relative;padding:5px 10px;text-align:center;color:#fff;text-decoration:none;background:linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);border-radius:30px;background-size:400%;text-transform:capitalize}.colorful-button:hover,#auto-task-buttons a.auto-task-website-btn:hover,.show-button-div a.auto-task-website-btn:hover,body.auto-task-options .auto-task-form table button:hover{transform:scale(1.05);box-shadow:0 6px 20px rgba(0,0,0,.3);cursor:pointer}.colorful-button:hover::before,#auto-task-buttons a.auto-task-website-btn:hover::before,.show-button-div a.auto-task-website-btn:hover::before,body.auto-task-options .auto-task-form table button:hover::before{filter:blur(10px);opacity:1}.colorful-button::before,#auto-task-buttons a.auto-task-website-btn::before,.show-button-div a.auto-task-website-btn::before,body.auto-task-options .auto-task-form table button::before{content:"";position:absolute;top:-5px;left:-5px;right:-5px;bottom:-5px;z-index:-1;background:linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);border-radius:40px;background-size:400%;opacity:-1}#auto-task-info{position:fixed;bottom:10px;right:10px;width:60%;max-width:500px;max-height:60%;overflow-y:auto;color:#000;background-color:#fff;padding-left:5px;z-index:999999999 !important;border:solid 2px #add8e6;border-radius:10px}#auto-task-info li{text-align:left}#auto-task-info li a.high-light{color:#00aeff;font-weight:bold}#auto-task-info .success{color:green}#auto-task-info .error{color:red}#auto-task-info .warning{color:blue}#auto-task-info .info{color:#ff0}#auto-task-info .update-text{color:green;border:solid 2px #8dcb69;margin:5px 10px 5px 20px;border-radius:10px;padding:5px 20px}.auto-task-keylol{display:inline-block;text-transform:capitalize;margin-left:10px;text-decoration:none !important;border:solid 1px;border-radius:5px;padding:0 2px}.auto-task-keylol[selected=selected]{background-color:blue !important;color:#fff !important}.auto-task-form table{font-family:verdana,arial,sans-serif;font-size:11px;color:#333;border-width:1px;border-color:#999;border-collapse:collapse;width:100%}.auto-task-form table thead td{border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9;font-weight:bold;background-color:#fff}.auto-task-form table tbody tr{background-color:#d4e3e5}.auto-task-form table tbody tr:hover{background-color:#ff6 !important}.auto-task-form table tbody tr th{background-color:#c3dde0;border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9;text-transform:capitalize}.auto-task-form table tbody tr td{border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9}.swal2-modal{width:70% !important;max-width:1000px !important}body.auto-task-options{padding-top:10px;text-align:center}body.auto-task-options .auto-task-form{width:80%;max-width:1000px;margin:0 auto;padding-bottom:20px}body.auto-task-options .auto-task-form table input.editOption{width:80%}body.auto-task-options .auto-task-form table #getTwitterUserId,body.auto-task-options .auto-task-form table #getYoutubeChannelId{margin-top:5px}body.auto-task-options .auto-task-form table button{z-index:1}body.auto-task-options .auto-task-form table input[type=text]{outline-style:none;border:1px solid #ccc;border-radius:3px;padding:5px 10px;font-size:14px}body.auto-task-options .auto-task-form table input[type=text]:focus{border-color:#66afe9;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}body.auto-task-options .auto-task-form table label{position:relative;width:160px;height:80px;cursor:pointer;transform:scale(0.25);margin:-25% 0;top:-30px;display:inline-block}body.auto-task-options .auto-task-form table label input{position:relative;z-index:1;appearance:none}body.auto-task-options .auto-task-form table label input:checked~span{background:#05be05;box-shadow:0 15px 25px rgba(5,190,5,.4)}body.auto-task-options .auto-task-form table label input:checked~span i{left:84px}body.auto-task-options .auto-task-form table label input:checked~span i::before{background:#05be05;box-shadow:35px 0 0 #05be05}body.auto-task-options .auto-task-form table label input:checked~span i::after{bottom:12px;height:15px;border-bottom-left-radius:15px;border-bottom-right-radius:15px;background:#05be05}body.auto-task-options .auto-task-form table label span{position:absolute;top:0;left:0;width:100%;height:100%;background:#fe0000;border-radius:80px;transition:.5s;box-shadow:0 15px 25px rgba(254,0,0,.4)}body.auto-task-options .auto-task-form table label span i{position:absolute;top:4px;left:4px;width:72px;height:72px;background:#fff;border-radius:50%}body.auto-task-options .auto-task-form table label span i::before{content:"";position:absolute;top:22px;left:12px;width:12px;height:12px;border-radius:50%;background:#fe0000;box-shadow:35px 0 0 #fe0000;transition:.5s}body.auto-task-options .auto-task-form table label span i::after{content:"";position:absolute;bottom:15px;left:calc(50% - 15px);width:30px;height:6px;border-radius:6px;background:#fe0000;transition:.5s}body.auto-task-history{font-size:15px;font-weight:400;line-height:1.5}body.auto-task-history .container a{color:#007bff;text-decoration:none;background-color:rgba(0,0,0,0)}body.auto-task-history .container .card{width:80%;max-width:800px;border-radius:10px;background:rgba(118,118,118,.1019607843);border-top:1px solid rgba(255,255,255,.5019607843);-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);box-shadow:0 15px 25px rgba(0,0,0,.1019607843);margin:20px auto;position:relative;display:flex;flex-direction:column;word-wrap:break-word;-webkit-background-clip:border-box;background-clip:border-box;border:1px solid rgba(0,0,0,.125);border-radius:.25rem}body.auto-task-history .container .card .title{text-align:center;font-size:30px;font-weight:bold;margin:5px 0}body.auto-task-history .container .card .title a:hover{text-decoration:none;background:#93e1ff;border-radius:10px;padding:3px}body.auto-task-history .container .card ul{margin-bottom:25px}body.auto-task-history .container .card ul li{margin-bottom:5px;line-height:20px}body.auto-task-history .container .card ul a:hover{text-decoration:underline}body.auto-task-history .container .card .delete-task{right:10px;width:38px;height:35px;position:absolute;font-size:24px;cursor:pointer;border-radius:10px}body.auto-task-history .container .card .delete-task:hover{background:#fff}body.auto-task-history .container .card .time{right:5px;position:absolute;bottom:0;color:#e83e8c;font-family:'SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace';font-size:15px}#auto-task-buttons,.show-button-div{position:fixed;top:30px;right:15px;width:124px;z-index:999999999 !important;transform:scale(0.85)}#auto-task-buttons p,.show-button-div p{line-height:30px;height:40px;text-align:center;margin:5px !important}#auto-task-buttons a.auto-task-website-btn,.show-button-div a.auto-task-website-btn{width:105px;line-height:27px;font-size:20px;display:block}.show-button-div{width:20px}.auto-task-capitalize{text-transform:capitalize !important}.swal2-file:focus,.swal2-input:focus,.swal2-textarea:focus{box-shadow:inset 0px 0px 4px 1px rgba(100,150,200,.5) !important}.swal2-checkbox-custom{align-items:center;justify-content:center;background:#fff;color:inherit;margin:1em auto}.swal2-checkbox-custom input{flex-shrink:0;margin:0 .4em}.giveaway-actions #getKey{display:none !important}.auto-task-giveaway-status{color:#fff;border-radius:10px;padding:0 5px;margin-left:5px}.auto-task-giveaway-status.active{background-color:#5cb85c}.auto-task-giveaway-status.not-active{background-color:#d9534f}`, '' ]);
  428. const __WEBPACK_DEFAULT_EXPORT__ = ___CSS_LOADER_EXPORT___.toString();
  429. },
  430. 314: function(module) {
  431. 'use strict';
  432. module.exports = function(cssWithMappingToString) {
  433. var list = [];
  434. list.toString = function toString() {
  435. return this.map(function(item) {
  436. var content = '';
  437. var needLayer = typeof item[5] !== 'undefined';
  438. if (item[4]) {
  439. content += '@supports ('.concat(item[4], ') {');
  440. }
  441. if (item[2]) {
  442. content += '@media '.concat(item[2], ' {');
  443. }
  444. if (needLayer) {
  445. content += '@layer'.concat(item[5].length > 0 ? ' '.concat(item[5]) : '', ' {');
  446. }
  447. content += cssWithMappingToString(item);
  448. if (needLayer) {
  449. content += '}';
  450. }
  451. if (item[2]) {
  452. content += '}';
  453. }
  454. if (item[4]) {
  455. content += '}';
  456. }
  457. return content;
  458. }).join('');
  459. };
  460. list.i = function i(modules, media, dedupe, supports, layer) {
  461. if (typeof modules === 'string') {
  462. modules = [ [ null, modules, undefined ] ];
  463. }
  464. var alreadyImportedModules = {};
  465. if (dedupe) {
  466. for (var k = 0; k < this.length; k++) {
  467. var id = this[k][0];
  468. if (id != null) {
  469. alreadyImportedModules[id] = true;
  470. }
  471. }
  472. }
  473. for (var _k = 0; _k < modules.length; _k++) {
  474. var item = [].concat(modules[_k]);
  475. if (dedupe && alreadyImportedModules[item[0]]) {
  476. continue;
  477. }
  478. if (typeof layer !== 'undefined') {
  479. if (typeof item[5] === 'undefined') {
  480. item[5] = layer;
  481. } else {
  482. item[1] = '@layer'.concat(item[5].length > 0 ? ' '.concat(item[5]) : '', ' {').concat(item[1], '}');
  483. item[5] = layer;
  484. }
  485. }
  486. if (media) {
  487. if (!item[2]) {
  488. item[2] = media;
  489. } else {
  490. item[1] = '@media '.concat(item[2], ' {').concat(item[1], '}');
  491. item[2] = media;
  492. }
  493. }
  494. if (supports) {
  495. if (!item[4]) {
  496. item[4] = ''.concat(supports);
  497. } else {
  498. item[1] = '@supports ('.concat(item[4], ') {').concat(item[1], '}');
  499. item[4] = supports;
  500. }
  501. }
  502. list.push(item);
  503. }
  504. };
  505. return list;
  506. };
  507. },
  508. 601: function(module) {
  509. 'use strict';
  510. module.exports = function(i) {
  511. return i[1];
  512. };
  513. }
  514. };
  515. var __webpack_module_cache__ = {};
  516. function __webpack_require__(moduleId) {
  517. var cachedModule = __webpack_module_cache__[moduleId];
  518. if (cachedModule !== undefined) {
  519. return cachedModule.exports;
  520. }
  521. var module = __webpack_module_cache__[moduleId] = {
  522. id: moduleId,
  523. exports: {}
  524. };
  525. __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  526. return module.exports;
  527. }
  528. !function() {
  529. __webpack_require__.n = function(module) {
  530. var getter = module && module.__esModule ? function() {
  531. return module['default'];
  532. } : function() {
  533. return module;
  534. };
  535. __webpack_require__.d(getter, {
  536. a: getter
  537. });
  538. return getter;
  539. };
  540. }();
  541. !function() {
  542. __webpack_require__.d = function(exports, definition) {
  543. for (var key in definition) {
  544. if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  545. Object.defineProperty(exports, key, {
  546. enumerable: true,
  547. get: definition[key]
  548. });
  549. }
  550. }
  551. };
  552. }();
  553. !function() {
  554. __webpack_require__.o = function(obj, prop) {
  555. return Object.prototype.hasOwnProperty.call(obj, prop);
  556. };
  557. }();
  558. var __webpack_exports__ = {};
  559. !function() {
  560. 'use strict';
  561. const external_Swal_namespaceObject = Swal;
  562. var external_Swal_default = __webpack_require__.n(external_Swal_namespaceObject);
  563. const external_Cookies_namespaceObject = Cookies;
  564. var external_Cookies_default = __webpack_require__.n(external_Cookies_namespaceObject);
  565. var auto_task = __webpack_require__(675);
  566. var javascript_utils_umd_min = __webpack_require__(991);
  567. const httpRequest = async (options, times = 0) => {
  568. if (window.TRACE) {
  569. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  570. }
  571. try {
  572. const result = await new Promise(resolve => {
  573. if (options.dataType) {
  574. options.responseType = options.dataType;
  575. }
  576. const requestObj = {
  577. ...{
  578. timeout: 3e4,
  579. ontimeout(data) {
  580. resolve({
  581. result: 'Error',
  582. statusText: 'Timeout',
  583. status: 601,
  584. data: data,
  585. options: options
  586. });
  587. },
  588. onabort(data) {
  589. resolve({
  590. result: 'Error',
  591. statusText: 'Aborted',
  592. status: 602,
  593. data: data,
  594. options: options
  595. });
  596. },
  597. onerror(data) {
  598. resolve({
  599. result: 'Error',
  600. statusText: 'Error',
  601. status: 603,
  602. data: data,
  603. options: options
  604. });
  605. },
  606. onload(data) {
  607. const headers = {};
  608. data.responseHeaders?.split('\n').forEach(header => {
  609. const headerArr = header.trim().split(':');
  610. const name = headerArr.shift()?.trim() || '';
  611. const value = headerArr.join(':').trim();
  612. if (name && value) {
  613. if (headers[name]) {
  614. if (Array.isArray(headers[name])) {
  615. headers[name].push(value);
  616. } else {
  617. headers[name] = [ headers[name], value ];
  618. }
  619. } else {
  620. headers[name] = value;
  621. }
  622. }
  623. });
  624. if (headers['set-cookie'] && !Array.isArray(headers['set-cookie'])) {
  625. headers['set-cookie'] = [ headers['set-cookie'] ];
  626. }
  627. data.responseHeadersText = data.responseHeaders;
  628. data.responseHeaders = headers;
  629. data.finalUrl = data.responseHeaders?.location || data.finalUrl;
  630. if (options.responseType === 'json' && data?.response && typeof data.response !== 'object') {
  631. try {
  632. data.response = JSON.parse(data.responseText);
  633. } catch (error) {}
  634. }
  635. resolve({
  636. result: 'Success',
  637. statusText: 'Load',
  638. status: 600,
  639. data: data,
  640. options: options
  641. });
  642. }
  643. },
  644. ...options
  645. };
  646. GM_xmlhttpRequest(requestObj);
  647. });
  648. if (window.DEBUG) {
  649. console.log('%cAuto-Task[httpRequest]:', 'color:blue', JSON.stringify(result));
  650. }
  651. if (result.status !== 600 && times < 2) {
  652. return await httpRequest(options, times + 1);
  653. }
  654. return result;
  655. } catch (error) {
  656. console.log('%cAuto-Task[httpRequest]:', 'color:red', JSON.stringify({
  657. errorMsg: error,
  658. options: options
  659. }));
  660. throwError(error, 'httpRequest');
  661. return {
  662. result: 'JsError',
  663. statusText: 'Error',
  664. status: 604,
  665. error: error,
  666. options: options
  667. };
  668. }
  669. };
  670. const tools_httpRequest = httpRequest;
  671. const echoLog = ({
  672. type,
  673. text,
  674. html,
  675. id
  676. }) => {
  677. const emptyStatus = {
  678. success: () => emptyStatus,
  679. error: () => emptyStatus,
  680. warning: () => emptyStatus,
  681. info: () => emptyStatus,
  682. view: () => emptyStatus
  683. };
  684. try {
  685. let ele;
  686. if (type) {
  687. switch (type) {
  688. case 'joiningSteamGroup':
  689. case 'leavingSteamGroup':
  690. case 'gettingSteamGroupId':
  691. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/groups/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  692. break;
  693.  
  694. case 'joiningSteamOfficialGroup':
  695. case 'leavingSteamOfficialGroup':
  696. case 'gettingSteamOfficialGroupId':
  697. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/games/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  698. break;
  699.  
  700. case 'subscribingForum':
  701. case 'unsubscribingForum':
  702. case 'gettingForumId':
  703. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/app/${text}/discussions/" target="_blank">${text}</a>]...<font></font></li>`);
  704. break;
  705.  
  706. case 'followingCurator':
  707. case 'unfollowingCurator':
  708. case 'gettingCuratorId':
  709. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/${text?.includes('/') ? text : `curator/${text}`}" target="_blank">${text}</a>]...<font></font></li>`);
  710. break;
  711.  
  712. case 'addingToWishlist':
  713. case 'removingFromWishlist':
  714. case 'followingGame':
  715. case 'unfollowingGame':
  716. case 'gettingSubid':
  717. case 'addingFreeLicense':
  718. case 'requestingPlayTestAccess':
  719. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/app/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  720. break;
  721.  
  722. case 'addingFreeLicenseSubid':
  723. ele = $(`<li>${i18n('addingFreeLicense')}[<a href="https://steamdb.info/sub/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  724. break;
  725.  
  726. case 'favoritingWorkshop':
  727. case 'unfavoritingWorkshop':
  728. case 'gettingWorkshopAppId':
  729. case 'votingUpWorkshop':
  730. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/sharedfiles/filedetails/?id=${text}" target="_blank">
  731. ${text}</a>]...<font></font></li>`);
  732. break;
  733.  
  734. case 'gettingAnnouncementParams':
  735. case 'likingAnnouncement':
  736. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/news/app/${text}/view/${id}" target="_blank">
  737. ${id}</a>]...<font></font></li>`);
  738. break;
  739.  
  740. case 'joiningDiscordServer':
  741. case 'gettingDiscordGuild':
  742. ele = $(`<li>${i18n(type)}[<a href="https://discord.com/invite/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  743. break;
  744.  
  745. case 'leavingDiscordServer':
  746. ele = $(`<li>${i18n(type)}[<a href="https://discord.com/channels/@me/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  747. break;
  748.  
  749. case 'updateDiscordAuth':
  750. ele = $(`<li style="color:red;">${i18n('updateDiscordAuth')}</li>`);
  751. break;
  752.  
  753. case 'followingTwitchChannel':
  754. case 'unfollowingTwitchChannel':
  755. case 'gettingTwitchChannelId':
  756. ele = $(`<li>${i18n(type)}[<a href="https://www.twitch.tv/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  757. break;
  758.  
  759. case 'gettingInsUserId':
  760. case 'followingIns':
  761. case 'unfollowingIns':
  762. ele = $(`<li>${i18n(type)}[<a href="https://www.instagram.com/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  763. break;
  764.  
  765. case 'gettingTwitterUserId':
  766. case 'followingTwitterUser':
  767. case 'unfollowingTwitterUser':
  768. ele = $(`<li>${i18n(type)}[<a href="https://x.com/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  769. break;
  770.  
  771. case 'retweetting':
  772. case 'unretweetting':
  773. ele = $(`<li>${i18n(type)}${text}...<font></font></li>`);
  774. break;
  775.  
  776. case 'joiningReddit':
  777. case 'leavingReddit':
  778. ele = $(`<li>${i18n(type)}[<a href="https://www.reddit.com/r/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  779. break;
  780.  
  781. case 'followingRedditUser':
  782. case 'unfollowingRedditUser':
  783. ele = $(`<li>${i18n(type)}[<a href="https://www.reddit.com/user/${text?.replace('u_', '')}" target="_blank">
  784. ${text?.replace('u_', '')}</a>]...<font></font></li>`);
  785. break;
  786.  
  787. case 'followingYtbChannel':
  788. case 'unfollowingYtbChannel':
  789. ele = $(`<li>${i18n(type)}[<a href="https://www.youtube.com/channel/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  790. break;
  791.  
  792. case 'likingYtbVideo':
  793. case 'unlikingYtbVideo':
  794. ele = $(`<li>${i18n(type)}[<a href="https://www.youtube.com/watch?v=${text}" target="_blank">${text}</a>]...<font></font></li>`);
  795. break;
  796.  
  797. case 'gettingVkId':
  798. case 'joiningVkGroup':
  799. case 'leavingVkGroup':
  800. case 'joiningVkPublic':
  801. case 'leavingVkPublic':
  802. case 'sendingVkWall':
  803. case 'deletingVkWall':
  804. ele = $(`<li>${i18n(type)}[<a href="https://vk.com/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  805. break;
  806.  
  807. case 'visitingLink':
  808. ele = $(`<li>${i18n('visitingLink')}[<a href="${text}" target="_blank">${text}</a>]...<font></font></li>`);
  809. break;
  810.  
  811. case 'verifyingInsAuth':
  812. case 'text':
  813. ele = $(`<li>${i18n(text)}<font></font></li>`);
  814. break;
  815.  
  816. case 'html':
  817. ele = $(text || html);
  818. break;
  819.  
  820. case 'whiteList':
  821. ele = $(`<li><font class="warning">${i18n('skipTask')}[${text}(${id})](${i18n('whiteList')})</font></li>`);
  822. break;
  823.  
  824. case 'globalOptionsSkip':
  825. ele = $(`<li>${i18n('skipTaskOption')}<font class="warning">${text}</font></li>`);
  826. break;
  827.  
  828. default:
  829. ele = $(`<li>${i18n('unKnown')}:${type}(${text})...<font></font></li>`);
  830. break;
  831. }
  832. } else if (text) {
  833. ele = $(`<li>${i18n(text)}<font></font></li>`);
  834. } else if (html) {
  835. ele = $(html);
  836. } else {
  837. ele = $('<li><font></font></li>');
  838. }
  839. ele.addClass('card-text');
  840. $('#auto-task-info').append(ele);
  841. ele[0]?.scrollIntoView();
  842. const font = ele.find('font');
  843. const status = {
  844. font: font,
  845. success(text = 'Success', html = false) {
  846. this.font?.attr('class', '').addClass('success');
  847. html ? this.font?.html(text) : this.font?.text(text);
  848. return this;
  849. },
  850. error(text = 'Error', html = false) {
  851. this.font?.attr('class', '').addClass('error');
  852. html ? this.font?.html(text) : this.font?.text(text);
  853. return this;
  854. },
  855. warning(text = 'Warning', html = false) {
  856. this.font?.attr('class', '').addClass('warning');
  857. html ? this.font?.html(text) : this.font?.text(text);
  858. return this;
  859. },
  860. info(text = 'Info', html = false) {
  861. this.font?.attr('class', '').addClass('info');
  862. html ? this.font?.html(text) : this.font?.text(text);
  863. return this;
  864. },
  865. view() {
  866. this.font?.[0].scrollIntoView();
  867. return this;
  868. }
  869. };
  870. return status;
  871. } catch (error) {
  872. throwError(error, 'echoLog');
  873. return emptyStatus;
  874. }
  875. };
  876. const scripts_echoLog = echoLog;
  877. const unique = array => {
  878. try {
  879. return [ ...new Set(array) ];
  880. } catch (error) {
  881. throwError(error, 'unique');
  882. return [];
  883. }
  884. };
  885. const delay = (time = 1e3) => new Promise(resolve => {
  886. setTimeout(() => {
  887. resolve(true);
  888. }, time);
  889. });
  890. const getRedirectLink = async link => {
  891. try {
  892. if (!link) {
  893. return null;
  894. }
  895. const redirectLinksCache = GM_getValue('redirectLinks') || {};
  896. if (redirectLinksCache[link]) {
  897. redirectLinksCache[link];
  898. }
  899. return await tools_httpRequest({
  900. url: link,
  901. method: 'GET'
  902. }).then(({
  903. data
  904. }) => {
  905. if (data?.finalUrl) {
  906. redirectLinksCache[link] = data.finalUrl;
  907. GM_setValue('redirectLinks', redirectLinksCache);
  908. return data.finalUrl;
  909. }
  910. return null;
  911. });
  912. } catch (error) {
  913. throwError(error, 'getRedirectLink');
  914. return null;
  915. }
  916. };
  917. const visitLink = async (link, options) => {
  918. try {
  919. const logStatus = scripts_echoLog({
  920. type: 'visitLink',
  921. text: link
  922. });
  923. return await tools_httpRequest({
  924. url: link,
  925. method: 'GET',
  926. ...options
  927. }).then(({
  928. result,
  929. statusText,
  930. status
  931. }) => {
  932. if (result === 'Success') {
  933. logStatus.success();
  934. return true;
  935. }
  936. logStatus.error(`${result}:${statusText}(${status})`);
  937. return false;
  938. });
  939. } catch (error) {
  940. throwError(error, 'visitLink');
  941. return false;
  942. }
  943. };
  944. const getUrlQuery = url => {
  945. try {
  946. const query = {};
  947. if (url) {
  948. if (url.includes('?')) {
  949. url.split('?')[1].replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  950. query[key] = value;
  951. return str;
  952. });
  953. }
  954. } else {
  955. window.location.search.replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  956. query[key] = value;
  957. return str;
  958. });
  959. }
  960. return query;
  961. } catch (error) {
  962. throwError(error, 'getUrlQuery');
  963. return {};
  964. }
  965. };
  966. const getUuid = () => {
  967. const uuidUrl = URL.createObjectURL(new Blob()).toString();
  968. return uuidUrl.slice(uuidUrl.lastIndexOf('/') + 1);
  969. };
  970. const stringToColour = str => {
  971. try {
  972. let hash = 0;
  973. for (let i = 0; i < str.length; i++) {
  974. hash = str.charCodeAt(i) + ((hash << 5) - hash);
  975. }
  976. let colour = '#';
  977. for (let i = 0; i < 3; i++) {
  978. const value = hash >> i * 8 & 255;
  979. colour += `00${value.toString(16)}`.slice(-2);
  980. }
  981. return colour;
  982. } catch (error) {
  983. throwError(error, 'stringToColour');
  984. return '#fff';
  985. }
  986. };
  987. const debug = (log, data) => {
  988. if (!window.DEBUG) {
  989. return;
  990. }
  991. console.log('%c%s', 'color:#a7a7a7', `Auto-Task[Debug]: ${log}`);
  992. if (data) {
  993. console.log('%c%s', 'color:#a7a7a7', 'Auto-Task[Debug]: ', data);
  994. }
  995. };
  996. const defaultGlobalOptions = {
  997. doTask: {
  998. discord: {
  999. servers: true
  1000. },
  1001. instagram: {
  1002. users: true
  1003. },
  1004. twitch: {
  1005. channels: true
  1006. },
  1007. twitter: {
  1008. users: true,
  1009. retweets: true
  1010. },
  1011. vk: {
  1012. names: true
  1013. },
  1014. youtube: {
  1015. channels: true,
  1016. likes: true
  1017. },
  1018. reddit: {
  1019. reddits: true
  1020. },
  1021. steam: {
  1022. groups: true,
  1023. officialGroups: true,
  1024. wishlists: true,
  1025. follows: true,
  1026. forums: true,
  1027. workshops: true,
  1028. curators: true,
  1029. workshopVotes: true,
  1030. announcements: true,
  1031. licenses: true,
  1032. playtests: true
  1033. }
  1034. },
  1035. undoTask: {
  1036. discord: {
  1037. servers: true
  1038. },
  1039. instagram: {
  1040. users: true
  1041. },
  1042. twitch: {
  1043. channels: true
  1044. },
  1045. twitter: {
  1046. users: true,
  1047. retweets: true
  1048. },
  1049. vk: {
  1050. names: true
  1051. },
  1052. youtube: {
  1053. channels: true,
  1054. likes: true
  1055. },
  1056. reddit: {
  1057. reddits: true
  1058. },
  1059. steam: {
  1060. groups: true,
  1061. officialGroups: true,
  1062. wishlists: true,
  1063. follows: true,
  1064. forums: true,
  1065. workshops: true,
  1066. curators: true
  1067. }
  1068. },
  1069. ASF: {
  1070. AsfEnabled: false,
  1071. AsfIpcUrl: '',
  1072. AsfIpcPassword: '',
  1073. AsfBotname: 'asf'
  1074. },
  1075. position: {
  1076. buttonSideX: 'right',
  1077. buttonSideY: 'top',
  1078. buttonDistance: '15,30',
  1079. showButtonSideX: 'right',
  1080. showButtonSideY: 'top',
  1081. showButtonDistance: '15,30',
  1082. logSideX: 'right',
  1083. logSideY: 'bottom',
  1084. logDistance: '10,10'
  1085. },
  1086. hotKey: {
  1087. doTaskKey: 'alt + d',
  1088. undoTaskKey: 'alt + u',
  1089. toggleLogKey: 'alt + l'
  1090. },
  1091. other: {
  1092. twitterVerifyId: '783214',
  1093. youtubeVerifyChannel: 'UCrXUsMBcfTVqwAS7DKg9C0Q',
  1094. autoUpdateSource: 'jsdelivr',
  1095. language: 'zh',
  1096. checkLogin: true,
  1097. checkLeftKey: true,
  1098. defaultShowButton: true,
  1099. defaultShowLog: true,
  1100. debug: false,
  1101. receivePreview: true
  1102. }
  1103. };
  1104. const userDefinedGlobalOptions = GM_getValue('globalOptions') || {};
  1105. const assignObject = (obj1, obj2) => {
  1106. try {
  1107. const newObj = {};
  1108. for (const [ key, value ] of Object.entries(obj1)) {
  1109. if (Object.prototype.toString.call(value) === '[object Object]' && Object.prototype.toString.call(obj2[key]) === '[object Object]') {
  1110. newObj[key] = assignObject(value, obj2[key]);
  1111. } else {
  1112. newObj[key] = obj2[key] ?? value;
  1113. }
  1114. }
  1115. return newObj;
  1116. } catch (error) {
  1117. throwError(error, 'assignObject');
  1118. return defaultGlobalOptions;
  1119. }
  1120. };
  1121. const globalOptions = assignObject(defaultGlobalOptions, userDefinedGlobalOptions);
  1122. const saveData = () => {
  1123. try {
  1124. const data = {};
  1125. $('#globalOptionsForm').serializeArray().map(value => {
  1126. data[value.name] = value.value;
  1127. return value;
  1128. });
  1129. $.makeArray($('#globalOptionsForm input')).map(element => {
  1130. const name = $(element).attr('name');
  1131. const keys = name.split('.');
  1132. if (keys.length === 3) {
  1133. globalOptions[keys[0]][keys[1]][keys[2]] = data[name] ? data[name] === 'on' ? true : data[name] : false;
  1134. } else if (keys.length === 2) {
  1135. globalOptions[keys[0]][keys[1]] = data[name] ? data[name] === 'on' ? true : data[name] : false;
  1136. }
  1137. return element;
  1138. });
  1139. GM_setValue('globalOptions', globalOptions);
  1140. external_Swal_default().fire({
  1141. title: i18n('changeGlobalOptionsSuccess'),
  1142. icon: 'success'
  1143. });
  1144. } catch (error) {
  1145. throwError(error, 'saveData');
  1146. }
  1147. };
  1148. const changeGlobalOptions = showType => {
  1149. try {
  1150. let globalOptionsForm = `<form id="globalOptionsForm" class="auto-task-form">
  1151. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  1152. for (const [ type, data1 ] of Object.entries(globalOptions)) {
  1153. for (const [ option, data2 ] of Object.entries(data1)) {
  1154. if ([ 'other', 'position', 'hotKey', 'ASF' ].includes(type)) {
  1155. if (typeof data2 === 'boolean') {
  1156. globalOptionsForm += `<tr style="background-color: ${stringToColour(type)}44">${Object.keys(data1).indexOf(option) === 0 ? `<th rowspan="${Object.keys(data1).length}">${i18n(type)}</th>` : ''}<td>${i18n(option)}</td><td><label><input type="checkbox" name="${type}.${option}"${data2 ? ' checked="checked"' : ''}/><span><i></i></span></label></td></tr>`;
  1157. } else {
  1158. globalOptionsForm += `<tr style="background-color: ${stringToColour(type)}44">${Object.keys(data1).indexOf(option) === 0 ? `<th rowspan="${Object.keys(data1).length}" style="background-color: ${stringToColour(type)}66">${i18n(type)}</th>` : ''}<td>${i18n(option)}</td><td><input class="editOption" type="text" name="${type}.${option}" value="${data2}"/></td></tr>`;
  1159. }
  1160. } else {
  1161. for (const [ socialType, data3 ] of Object.entries(data2)) {
  1162. globalOptionsForm += `<tr style="background-color: ${stringToColour(option)}66">${Object.keys(data1).indexOf(option) === 0 ? `<th rowspan="${Object.keys(data1).map(key => Object.keys(data1[key]).length).reduce((acr, cur) => acr + cur)}" style="background-color: ${stringToColour(type)}66">${i18n(type)}</th>` : ''}<td>${option}.${i18n(socialType)}</td><td><label><input type="checkbox" name="${type}.${option}.${socialType}"${data3 ? ' checked="checked"' : ''}/><span><i></i></span></label></td></tr>`;
  1163. }
  1164. }
  1165. }
  1166. }
  1167. globalOptionsForm += '</tbody></table></form>';
  1168. if (showType === 'swal') {
  1169. external_Swal_default().fire({
  1170. title: i18n('globalOptions'),
  1171. html: globalOptionsForm,
  1172. showConfirmButton: true,
  1173. confirmButtonText: i18n('save'),
  1174. showCancelButton: true,
  1175. cancelButtonText: i18n('close')
  1176. }).then(({
  1177. isConfirmed
  1178. }) => {
  1179. if (isConfirmed) {
  1180. saveData();
  1181. }
  1182. });
  1183. } else {
  1184. $('body').append(`<h2>${i18n('globalOptions')}</h2>${globalOptionsForm}`);
  1185. }
  1186. } catch (error) {
  1187. throwError(error, 'changeGlobalOptions');
  1188. }
  1189. };
  1190. const data = {
  1191. website: '网站',
  1192. type: '类型',
  1193. edit: '编辑',
  1194. whiteList: '白名单',
  1195. skipTask: '跳过撤销任务',
  1196. whiteListOptions: '白名单设置',
  1197. changeWhiteListOption: '设置白名单(%0)',
  1198. whiteListNotFound: '找不到此项白名单: %0',
  1199. changeWhiteListSuccess: '白名单修改成功,刷新生效!',
  1200. changeWebsiteOptions: '网站设置',
  1201. changeGlobalOptions: '全局设置',
  1202. ok: '是',
  1203. save: '保存',
  1204. close: '关闭',
  1205. return: '返回',
  1206. option: '选项',
  1207. value: '值',
  1208. websiteOptions: '当前网站设置',
  1209. changeWebsiteOptionsSuccess: '更改当前网站设置成功,刷新生效!',
  1210. changeGlobalOptionsSuccess: '更改全局设置成功,刷新生效!',
  1211. needLogin: '请先登录!',
  1212. getTasksInfo: '正在获取并处理任务信息...',
  1213. gettingKey: '正在获取Key...',
  1214. verifyingTask: '正在验证任务',
  1215. notice: '自动任务脚本提醒',
  1216. noKeysLeft: '此页面已经没有剩余key了,是否关闭?',
  1217. giveawayEnded: '此活动已结束,是否关闭?',
  1218. giveawayNotWork: '此活动因某些原因(已结束/暂停/未开始...)不可用(如果是脚本误判请及时反馈),是否关闭?',
  1219. confirm: '确定',
  1220. cancel: '取消',
  1221. unKnown: '未知',
  1222. unKnownTaskType: '未识别的任务',
  1223. doing: '正在做任务',
  1224. allTasksComplete: '所有任务已完成!',
  1225. getTaskIdFailed: '获取任务Id失败!',
  1226. initSuccess: '%0 初始化成功!',
  1227. initFailed: '%0 初始化失败!',
  1228. errorLink: '链接错误: %0',
  1229. needInit: '请先初始化',
  1230. verifyingAuth: '正在验证%0凭证...',
  1231. updatingAuth: '正在更新%0凭证...',
  1232. refreshingToken: '正在刷新%0凭证...',
  1233. settingToken: '正在设置%0凭证...',
  1234. steamStoreTab: 'Steam商店(弹窗)',
  1235. steamCommunityTab: 'Steam社区(弹窗)',
  1236. initing: '正在初始化...',
  1237. getFailed: '获取%0失败!',
  1238. checkLoginFailed: '检测登录状态失败!',
  1239. checkLeftKeyFailed: '检测剩余Key失败!',
  1240. userId: '用户Id',
  1241. joiningGiveaway: '正在加入赠Key',
  1242. needJoinGiveaway: '需要先加入赠Key',
  1243. cannotUndo: '此网站不支持取消任务',
  1244. verifyAuth: '正在验证 %0 凭证...',
  1245. closePageNotice: '如果此页面没有自动关闭,请自行关闭本页面。',
  1246. errorReport: '检测到脚本报错,是否前往反馈BUG?',
  1247. visitingLink: '正在访问链接: ',
  1248. doTask: '做任务',
  1249. undoTask: '撤销任务',
  1250. verifyTask: '验证任务',
  1251. getKey: '获取Key',
  1252. selectAll: '全选',
  1253. selectNone: '全不选',
  1254. invertSelect: '反选',
  1255. doFreeTask: '加入免费赠品',
  1256. doPointTask: '加入点数赠品',
  1257. skipTaskOption: '设置中已配置跳过任务',
  1258. other: '其他',
  1259. globalOptions: '全局设置',
  1260. checkLogin: '登录检测</br>需要登录的网站自动登录,部分网站支持',
  1261. checkLeftKey: '剩余Key检测</br>赠Key活动结束提示是否关闭,部分网站支持',
  1262. twitterVerifyId: '通过尝试关注该账号验证Twitter凭证</br>默认为Twitter官方帐号 783214</br>不想关注官方账号可以改为自己的帐号',
  1263. youtubeVerifyChannel: '通过尝试订阅该频道验证YouTube凭证</br>默认为YouTube官方频道 UCrXUsMBcfTVqwAS7DKg9C0Q</br>不想关注官方频道可以改为自己的频道',
  1264. autoUpdateSource: '更新源</br>github: 需代理,实时更新</br>jsdelivr: 可不用代理,更新有延迟</br>standby: 备用</br>auto: 依次使用github, jsdelivr, standby源进行尝试更新',
  1265. saveGlobalOptions: '保存设置',
  1266. settingPage: '设置页面',
  1267. name: '名称',
  1268. version: '版本',
  1269. scriptManager: '脚本管理器',
  1270. script: '脚本',
  1271. environment: '环境',
  1272. os: '系统',
  1273. browser: '浏览器',
  1274. getId: '获取 %0 id',
  1275. getTwitterUserId: '获取Twitter用户id(获取id功能仅在设置页面可用)',
  1276. getYoutubeChannelId: '获取Youtube频道id(获取id功能仅在设置页面可用)',
  1277. showButton: '显示按钮',
  1278. hideButton: '隐藏按钮',
  1279. showLog: '显示日志',
  1280. hideLog: '隐藏日志',
  1281. defaultShowButton: '默认显示按钮',
  1282. defaultShowLog: '默认显示日志',
  1283. debug: '输出调试日志,不要开启此选项!',
  1284. receivePreview: '接收预览版更新',
  1285. position: '组件位置',
  1286. buttonSideX: '按钮区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1287. buttonSideY: '按钮区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1288. buttonDistance: '按钮区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1289. showButtonSideX: '显示按钮水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1290. showButtonSideY: '显示按钮垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1291. showButtonDistance: '显示按钮距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1292. logSideX: '日志区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1293. logSideY: '日志区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1294. logDistance: '日志区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1295. hotKey: '快捷键',
  1296. doTaskKey: '做任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1297. undoTaskKey: '撤销任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1298. toggleLogKey: '显示/隐藏日志快捷键</br>(实时预览功能仅在设置页面可用)',
  1299. tasksHistory: '任务历史',
  1300. clearHistory: '清空历史',
  1301. clearHistoryFinished: '已清空任务历史!',
  1302. deleteTask: '删除任务',
  1303. lastChangeTime: '最后一次修改时间',
  1304. clearTaskFinished: '删除以下任务完成!',
  1305. clearTaskFailed: '删除任务失败,没有找到任务名!',
  1306. syncData: '数据同步',
  1307. settingData: '正在上传数据...',
  1308. gettingData: '正在获取数据...',
  1309. help: '帮助',
  1310. fileName: '文件名',
  1311. upload2gist: '同步到Gist',
  1312. downloadFromGist: '从Gist同步',
  1313. saveAndTest: '保存配置并测试',
  1314. testSuccess: '测试成功!',
  1315. testFailed: '测试失败!',
  1316. saveAndTestNotice: '请先保存配置并测试!',
  1317. processingData: '正在处理数据...',
  1318. updatingData: '正在上传数据...',
  1319. syncDataSuccess: '同步数据成功!',
  1320. syncDataFailed: '同步数据失败,请在控制台查看错误信息!',
  1321. downloadingData: '正在下载数据...',
  1322. checkedNoData: '没有检测到远程数据,请确认配置是否正确!',
  1323. savingData: '正在保存数据...',
  1324. syncHistory: '同步任务历史',
  1325. checkUpdateFailed: '检测更新失败',
  1326. newVersionNotice: '检测到新版本V%0, <a class="high-light" href="%1" target="_blank">点此更新</a>',
  1327. language: '语言</br>目前仅支持zh: 中文, en: 英文',
  1328. gistOptions: 'Gist 设置',
  1329. swalNotice: '检测到您第一次安装V4版本脚本,请前往阅读用前必读内容!',
  1330. echoNotice: '检测到您第一次安装V4版本脚本,请<a class="high-light" href="%0" target="_blank">点此前往</a>阅读用前必读内容!',
  1331. noticeLink: 'https://auto-task-doc.js.org/guide/#用前必读',
  1332. toGithub: '前往Github反馈',
  1333. toKeylol: '前往其乐论坛反馈',
  1334. copySuccess: '错误信息已复制到剪切板,是否前往其乐论坛反馈?',
  1335. copyFailed: '请复制下方错误信息后前往Keylol论坛反馈!',
  1336. updateText: '%0 版本更新内容:',
  1337. Active: '进行中',
  1338. Ended: '已结束',
  1339. Banned: '已封禁',
  1340. Paused: '已暂停',
  1341. notStart: '未开始',
  1342. noRemoteData: '检测到远程无数据',
  1343. errorRemoteDataFormat: '远程数据格式错误',
  1344. updateHistory: '历史更新记录<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">点此查看</a>',
  1345. AsfEnabled: '使用ASF做Steam相关任务(需<a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a>插件)',
  1346. AsfIpcUrl: 'ASF IPC 地址',
  1347. AsfIpcPassword: 'ASF IPC 密码',
  1348. versionNotMatched: '脚本管理器版本过低,需TamperMonkey >= 5.2.0或TamperMonkey Beta >= 5.2.6196',
  1349. groups: '组',
  1350. officialGroups: '官方组',
  1351. wishlists: '愿望单',
  1352. follows: '游戏关注',
  1353. forums: '论坛',
  1354. workshops: '创意工坊收藏',
  1355. curators: '鉴赏家',
  1356. workshopVotes: '创意工坊点赞',
  1357. announcements: '社区通知',
  1358. steamCommunity: 'Steam社区',
  1359. steamStore: 'Steam商店',
  1360. licenses: '入库免费游戏',
  1361. playtests: '请求访问权限',
  1362. needLoginSteamStore: '请先<a href="https://store.steampowered.com/login/" target="_blank">登录Steam商店</a>',
  1363. needLoginSteamCommunity: '请先<a href="https://steamcommunity.com/login/home/" target="_blank">登录Steam社区</a>',
  1364. joiningSteamGroup: '正在加入Steam组',
  1365. leavingSteamGroup: '正在退出Steam组',
  1366. gettingSteamGroupId: '正在获取Steam组Id',
  1367. joiningSteamOfficialGroup: '正在加入Steam官方组',
  1368. leavingSteamOfficialGroup: '正在退出Steam官方组',
  1369. gettingSteamOfficialGroupId: '正在获取Steam官方组Id',
  1370. subscribingForum: '正在订阅Steam论坛',
  1371. unsubscribingForum: '正在取消订阅Steam论坛',
  1372. gettingForumId: '正在获取Steam论坛Id',
  1373. followingCurator: '正在关注Steam鉴赏家',
  1374. unfollowingCurator: '正在取关Steam鉴赏家',
  1375. gettingCuratorId: '正在获取Steam鉴赏家Id',
  1376. addingToWishlist: '正在添加游戏到Steam愿望单',
  1377. removingFromWishlist: '正在从Steam愿望单移除游戏',
  1378. followingGame: '正在关注Steam游戏',
  1379. unfollowingGame: '正在取关Steam游戏',
  1380. favoritingWorkshop: '正在收藏Steam创意工坊物品',
  1381. unfavoritingWorkshop: '正在取消收藏Steam创意工坊物品',
  1382. gettingWorkshopAppId: '正在获取Steam创意工坊物品Id',
  1383. votingUpWorkshop: '正在点赞Steam创意工坊物品',
  1384. gettingAnnouncementParams: '正在获取Steam通知信息',
  1385. likingAnnouncement: '正在点赞Steam通知',
  1386. changingArea: '正在更换Steam地区: %0...',
  1387. notNeededChangeArea: '当前地区不需要更换',
  1388. noAnotherArea: '请检测是否开启正确开启代理',
  1389. gettingAreaInfo: '正在获取Steam地区信息...',
  1390. changeAreaNotice: '疑似锁区游戏,尝试换区执行',
  1391. steamFinishNotice: 'Steam任务完成,尝试将购物车地区换回',
  1392. gettingSubid: '正在获取游戏subid',
  1393. addingFreeLicense: '正在入库',
  1394. missParams: '缺少参数',
  1395. gettingLicenses: '正在获取Licenses...',
  1396. requestingPlayTestAccess: '正在请求访问权限',
  1397. tryChangeAreaNotice: '此功能无法检测游戏是否限区,因此会尝试换区后再入库,换区失败也不影响后续入库',
  1398. gettingUserLink: '正在获取Steam用户社区链接...',
  1399. retry: '重试',
  1400. owned: '已拥有',
  1401. redirect: '重定向',
  1402. noSubid: '无法获取,跳过',
  1403. initingASF: '正在初始化ASF...',
  1404. servers: '服务器',
  1405. joiningDiscordServer: '正在加入Discord服务器',
  1406. leavingDiscordServer: '正在退出Discord服务器',
  1407. gettingDiscordGuild: '正在获取Discord服务器Id',
  1408. getDiscordAuthFailed: '获取Discord凭证失败,请检测Discord帐号是否已登录',
  1409. discordImportantNotice: '重要提醒!!!',
  1410. discordImportantNoticeText: '由于Discord网站后台更新,目前使用此脚本加组后可能会导致Discord帐号被强制退出,且需要两步验证才能正常登录,请谨慎使用!!!',
  1411. continue: '继续',
  1412. skipDiscordTask: '跳过Discord任务',
  1413. continueAndDontRemindAgain: '继续且不再提醒',
  1414. users: '用户',
  1415. loginIns: '请先<a href="https://www.instagram.com/accounts/login/" target="_blank">登录Instagram</a>',
  1416. insBanned: '您的Instagram账户已被封禁',
  1417. verifyingInsAuth: '正在验证Instagram凭证...',
  1418. gettingInsUserId: '正在获取Instagram用户Id',
  1419. followingIns: '正在关注Instagram用户',
  1420. unfollowingIns: '正在取关Instagram用户',
  1421. reddits: '社区/用户',
  1422. loginReddit: '请先<a href="https://www.reddit.com/login/" target="_blank">登录Reddit</a>',
  1423. changingRedditVersion: '正在切换Reddit为新版页面...',
  1424. joiningReddit: '正在加入Reddit社区',
  1425. leavingReddit: '正在退出Reddit社区',
  1426. followingRedditUser: '正在关注Reddit用户',
  1427. unfollowingRedditUser: '正在取关Reddit用户',
  1428. channels: '频道',
  1429. followingTwitchChannel: '正在关注Twitch频道',
  1430. unfollowingTwitchChannel: '正在取关Twitch频道',
  1431. gettingTwitchChannelId: '正在获取Twitch频道Id',
  1432. checkingTwitchIntegrity: '正在检查Twitch完整性...',
  1433. twitterUser: '推特用户',
  1434. retweets: '转推',
  1435. gettingTwitterUserId: '正在获取推特用户Id',
  1436. followingTwitterUser: '正在关注推特用户',
  1437. unfollowingTwitterUser: '正在取关推特用户',
  1438. retweetting: '正在转推',
  1439. unretweetting: '正在撤销转推',
  1440. names: '组/社区/动态',
  1441. loginVk: '请先<a href="https://vk.com/login/" target="_blank">登录Vk</a>',
  1442. gettingVkId: '正在获取Vk任务Id',
  1443. joiningVkGroup: '正在加入Vk组',
  1444. leavingVkGroup: '正在退出Vk组',
  1445. joiningVkPublic: '正在加入Vk社区',
  1446. leavingVkPublic: '正在退出Vk社区',
  1447. sendingVkWall: '正在转发Vk动态',
  1448. deletingVkWall: '正在撤销转发Vk动态',
  1449. youtubeChannel: 'YouTube频道',
  1450. likes: '点赞',
  1451. loginYtb: '请先<a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">登录YouTube</a>',
  1452. tryUpdateYtbAuth: '请尝试<a href="https://www.youtube.com/#auth" target="_blank">更新YouTube凭证</a>',
  1453. gettingYtbToken: '正在获取YouTube Token...',
  1454. followingYtbChannel: '正在订阅YouTube频道',
  1455. unfollowingYtbChannel: '正在退订YouTube频道',
  1456. likingYtbVideo: '正在点赞YouTube视频',
  1457. unlikingYtbVideo: '正在取消点赞YouTube视频',
  1458. giveKeyNoticeBefore: '每次验证间隔15s',
  1459. giveKeyNoticeAfter: '如果没有key, 请在<a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>查看',
  1460. noPoints: '点数不够,跳过抽奖',
  1461. getNeedPointsFailed: '获取所需点数失败,跳过抽奖',
  1462. joiningLottery: '正在加入抽奖',
  1463. doingGleamTask: '正在做Gleam任务...',
  1464. gettingGleamLink: '正在获取Gleam任务链接...',
  1465. gleamTaskNotice: '如果此页面长时间未关闭,请完成任一任务后自行关闭!',
  1466. verifiedGleamTasks: '已尝试验证所有任务,验证失败的任务请尝试手动验证或完成!',
  1467. campaign: '检测到人机验证,请完成验证后重新验证任务!',
  1468. gsNotice: '为避免得到"0000-0000-0000"key, 已自动屏蔽"Grab Key"按钮,获取key时请关闭脚本!',
  1469. giveeClubVerifyNotice: '正在验证任务...',
  1470. giveeClubVerifyFinished: '请等待验证完成后自行加入赠Key',
  1471. doingKeyhubTask: '正在做Keyhub任务...',
  1472. SweepWidgetNotice: '正在处理并验证任务,每次验证任务有1~3s间隔防止触发验证过快警告...',
  1473. tasksNotCompleted: '任务未完成',
  1474. notConnect: '社交平台未连接,跳过任务',
  1475. confirmingTask: '正在跳过警告页面...'
  1476. };
  1477. const zh_CN = data;
  1478. const en_US_data = {
  1479. website: 'Website',
  1480. type: 'Type',
  1481. edit: 'Edit',
  1482. whiteList: 'Whitelist',
  1483. skipTask: 'Skip undo task',
  1484. whiteListOptions: 'Whitelist options',
  1485. changeWhiteListOption: 'Whitelist option(%0)',
  1486. whiteListNotFound: 'Cannot find this whitelist: %0',
  1487. changeWhiteListSuccess: 'The whitelist is successfully modified, and the page refresh will take effect!',
  1488. changeWebsiteOptions: 'Website options',
  1489. changeGlobalOptions: 'Global options',
  1490. ok: 'OK',
  1491. save: 'Save',
  1492. close: 'Close',
  1493. return: 'Return',
  1494. option: 'Option',
  1495. value: 'Value',
  1496. websiteOptions: 'Current website settings',
  1497. changeWebsiteOptionsSuccess: 'The current website setting is changed successfully, and the page refresh will take effect!',
  1498. changeGlobalOptionsSuccess: 'The global setting is changed successfully, and the refresh will take effect!',
  1499. needLogin: 'Please log in first!',
  1500. getTasksInfo: 'Obtaining and processing task information...',
  1501. gettingKey: 'Getting Key...',
  1502. verifyingTask: 'Verifying task',
  1503. notice: 'Automatic task script notice',
  1504. noKeysLeft: 'There are no more keys left on this page. Do you want to close it?',
  1505. giveawayEnded: 'This event has ended, do you want to close it?',
  1506. giveawayNotWork: 'This activity is unavailable for some reasons (banned/ended/paused/not started...)' + ' (if it is a script misjudgment, please give us feedback in time), is it closed?',
  1507. confirm: 'Confirm',
  1508. cancel: 'Cancel',
  1509. unKnown: 'Unknown',
  1510. unKnownTaskType: 'Unrecognized task',
  1511. doing: 'Doing a task',
  1512. allTasksComplete: 'All tasks have been completed!',
  1513. getTaskIdFailed: 'Failed to obtain task Id!',
  1514. initSuccess: '%0 was initialized successfully!',
  1515. initFailed: '%0 initialization failed!',
  1516. errorLink: 'Link error: %0',
  1517. needInit: 'Please initialize first',
  1518. verifyingAuth: 'Verifying %0 token...',
  1519. updatingAuth: 'Update %0 token...',
  1520. refreshingToken: 'Refreshing %0 token...',
  1521. settingToken: 'Setting %0 token...',
  1522. steamStoreTab: 'Steam store (new tab)',
  1523. steamCommunityTab: 'Steam community(new tab)',
  1524. initing: 'Initializing...',
  1525. getFailed: 'Failed to get %0!',
  1526. checkLoginFailed: 'Failed to detect login status!',
  1527. checkLeftKeyFailed: 'Failed to detect the remaining keys!',
  1528. userId: 'User Id',
  1529. joiningGiveaway: 'Joining giveaway',
  1530. needJoinGiveaway: 'Need to join the giveaway first',
  1531. cannotUndo: 'This website does not support canceling tasks',
  1532. verifyAuth: 'Verifying %0 token...',
  1533. closePageNotice: 'f this page does not close automatically, please close this page yourself.',
  1534. errorReport: 'A script error is detected, do you want to report the BUG?',
  1535. visitingLink: 'Visiting link: ',
  1536. doTask: 'DoTask',
  1537. undoTask: 'UndoTask',
  1538. verifyTask: 'Verify',
  1539. getKey: 'GetKey',
  1540. selectAll: 'SelectAll',
  1541. selectNone: 'SelectNone',
  1542. invertSelect: 'InvertSelect',
  1543. doFreeTask: 'FreeTask',
  1544. doPointTask: 'PointTask',
  1545. skipTaskOption: 'Skip task has been configured in the settings',
  1546. other: 'Other',
  1547. globalOptions: 'Global Options',
  1548. checkLogin: 'Login detection</br>Need to log in to the website automatically log in, part of this website supports.',
  1549. checkLeftKey: 'Key remaining detection</br>The end of the giveaway event prompts whether to close or not, part of this website supports.',
  1550. twitterVerifyId: 'Verify Twitter token by trying to follow the account.</br>The default is the official Twitter account 783214.</br>' + 'If you don\'t want to follow the official account, you can change it to your own account.',
  1551. youtubeVerifyChannel: 'Verify YouTube token by trying to subscribe to the channel.</br>' + 'The default is the official YouTube channel UCrXUsMBcfTVqwAS7DKg9C0Q.</br>' + 'If you don\'t want to follow the official channel, you can change it to your own channel.',
  1552. autoUpdateSource: 'The source to update</br>github: Fast update.</br>jsdelivr: Update is delayed.</br>' + 'standby: Standby source.</br>auto: Try to update using github, jsdelivr, standby sources in turn.',
  1553. saveGlobalOptions: 'SaveSettings',
  1554. settingPage: 'Setting Page',
  1555. name: 'Name',
  1556. version: 'Version',
  1557. scriptManager: 'Script Manager',
  1558. script: 'Script',
  1559. environment: 'Environment',
  1560. os: 'OS',
  1561. browser: 'Browser',
  1562. getId: 'Get %0 id',
  1563. getTwitterUserId: 'Get Twitter user id (Get id function is only available on the settings page).',
  1564. getYoutubeChannelId: 'Get Youtube channel id (Get id function is only available on the settings page).',
  1565. showButton: 'ShowButton',
  1566. hideButton: 'HideButton',
  1567. showLog: 'ShowLog',
  1568. hideLog: 'HideLog',
  1569. defaultShowButton: 'Default display button',
  1570. defaultShowLog: 'Display log by default',
  1571. debug: 'Output debug log, do not enable this option!',
  1572. receivePreview: 'Receive preview updates',
  1573. position: 'Component position',
  1574. buttonSideX: 'Horizontal positioning of the button area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1575. buttonSideY: 'The button area is positioned in the vertical direction (real-time preview function is only available on the settings page).' + '</br>top: top | bottom: bottom',
  1576. buttonDistance: 'The distance between the button area and the edge (the real-time preview function is only available on the setting page).' + '</br> Format: X distance, Y distance',
  1577. showButtonSideX: 'ShowButton horizontal positioning (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1578. showButtonSideY: 'ShowButton vertical positioning (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  1579. showButtonDistance: 'The distance between the ShowButton and the edge (real-time preview function is only available on the setting page).' + '</br> Format: X distance, Y distance',
  1580. logSideX: 'Horizontal positioning of the log area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1581. logSideY: 'Vertical positioning of the log area (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  1582. logDistance: 'The distance between the log area and the edge (the real-time preview function is only available on the setting page).' + '</br> Format: X distance, Y distance',
  1583. hotKey: 'Shortcut key',
  1584. doTaskKey: 'DoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  1585. undoTaskKey: 'UndoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  1586. toggleLogKey: 'ShowLog/HideLog shortcut keys</br> (real-time preview function is only available on the settings page).',
  1587. tasksHistory: 'TasksHistory',
  1588. clearHistory: 'Clear history',
  1589. clearHistoryFinished: 'The mission history has been cleared!',
  1590. deleteTask: 'Delete task',
  1591. lastChangeTime: 'Last Change Time',
  1592. clearTaskFinished: 'Delete the following tasks completed!',
  1593. clearTaskFailed: 'Failed to delete the task, the task name was not found!',
  1594. syncData: 'DataSync',
  1595. settingData: 'Uploading data...',
  1596. gettingData: 'Getting data...',
  1597. help: 'Help',
  1598. fileName: 'Filename',
  1599. upload2gist: 'Sync to Gist',
  1600. downloadFromGist: 'Sync from Gist',
  1601. saveAndTest: 'Save configuration and test',
  1602. testSuccess: 'Test success!',
  1603. testFailed: 'Test failed!',
  1604. saveAndTestNotice: 'Please save the configuration and test first!',
  1605. processingData: 'Processing data...',
  1606. updatingData: 'Uploading data...',
  1607. syncDataSuccess: 'Synchronized data successfully!',
  1608. syncDataFailed: 'Failed to synchronize data, please check the error message on the console!',
  1609. downloadingData: 'Downloading data...',
  1610. checkedNoData: 'No remote data is detected, please confirm whether the configuration is correct!',
  1611. savingData: 'Saving data...',
  1612. syncHistory: 'Synchronize tasks history',
  1613. checkUpdateFailed: 'Check update failed',
  1614. newVersionNotice: 'Checked a new version V%0, <a class="high-light" href="%1" target="_blank">click to update</a>',
  1615. language: 'Language</br> Currently only supports zh: Chinese, en: English',
  1616. gistOptions: 'Gist Settings',
  1617. swalNotice: 'It is detected that you are installing the V4 version script for the first time' + ', please go to read the READ ME FIRST content before use!',
  1618. echoNotice: 'It is detected that you are installing the V4 version script for the first time' + ', please <a class="high-light" href="%0" target="_blank">click here</a> to read the READ ME FIRST content before use!',
  1619. noticeLink: 'https://auto-task-doc.js.org/en/guide/#read-me-first',
  1620. toGithub: 'Feedback(Github)',
  1621. toKeylol: 'Feedback(Keylol)',
  1622. copySuccess: 'The error message has been copied to the clipboard. Do you want to go to the Keylol forum to give feedback?',
  1623. copyFailed: 'Please copy the error information below and report back to the Keylol forum!',
  1624. updateText: 'Updates in version %0:',
  1625. Active: 'Active',
  1626. Ended: 'Ended',
  1627. Banned: 'Banned',
  1628. Paused: 'Paused',
  1629. notStart: 'notStart',
  1630. noRemoteData: 'No data remotely',
  1631. errorRemoteDataFormat: 'Remote data has wrong format',
  1632. updateHistory: '<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">Click here</a>' + ' to view the historical update record.',
  1633. AsfEnabled: 'Use ASF to do Steam related tasks (requires <a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a> plugin)',
  1634. AsfIpcUrl: 'ASF IPC URL',
  1635. AsfIpcPassword: 'ASF IPC Password',
  1636. groups: 'Group',
  1637. officialGroups: 'Official Group',
  1638. wishlists: 'Wishlist',
  1639. follows: 'Follow Game',
  1640. forums: 'Forum',
  1641. workshops: 'Favorite Workshop',
  1642. curators: 'Curator',
  1643. workshopVotes: 'Voteup Workshop',
  1644. announcements: 'Announcement',
  1645. steamCommunity: 'Steam Community',
  1646. steamStore: 'Steam Store',
  1647. licenses: 'Add License',
  1648. playtests: 'Playtest Access',
  1649. needLoginSteamStore: 'Please <a href="https://store.steampowered.com/login/" target="_blank">log in to the Steam Store</a>',
  1650. needLoginSteamCommunity: 'Please <a href="https://steamcommunity.com/login/home/" target="_blank">log in to the Steam Community</a>',
  1651. joiningSteamGroup: 'Joining Steam Group',
  1652. leavingSteamGroup: 'Leaving Steam Group',
  1653. gettingSteamGroupId: 'Getting Steam Group Id',
  1654. joiningSteamOfficialGroup: 'Joining Steam Official Group',
  1655. leavingSteamOfficialGroup: 'Leaving Steam Official Group',
  1656. gettingSteamOfficialGroupId: 'Getting Steam Official Group Id',
  1657. subscribingForum: 'Subscribing the Steam Forum',
  1658. unsubscribingForum: 'Unsubscribing the Steam Forum',
  1659. gettingForumId: 'Getting Steam Forum Id',
  1660. followingCurator: 'Following Steam Curator',
  1661. unfollowingCurator: 'Unfollowing Steam Curator',
  1662. gettingCuratorId: 'Getting Steam Curator Id',
  1663. addingToWishlist: 'Adding the game to the Steam wishlist',
  1664. removingFromWishlist: 'Removing the game from the Steam wishlist',
  1665. followingGame: 'Following Steam games',
  1666. unfollowingGame: 'Unfollowing Steam games',
  1667. favoritingWorkshop: 'Favouring Steam Workshop Items',
  1668. unfavoritingWorkshop: 'Unfavoriting Steam Workshop Items',
  1669. gettingWorkshopAppId: 'Getting Steam Workshop Item Id',
  1670. votingUpWorkshop: 'Liking Steam workshop items',
  1671. gettingAnnouncementParams: 'Getting Steam announcement information',
  1672. likingAnnouncement: 'Liking Steam announcement',
  1673. changingArea: 'Changing Steam area: %0...',
  1674. notNeededChangeArea: 'The current area does not need to be changed',
  1675. noAnotherArea: 'Please check whether the proxy is turned on correctly',
  1676. gettingAreaInfo: 'Getting Steam area information...',
  1677. changeAreaNotice: 'Suspected of a locked zone game, try to change the zone to execute',
  1678. steamFinishNotice: 'Steam task completed, try to change the shopping cart area back to ',
  1679. gettingSubid: 'Getting subid',
  1680. addingFreeLicense: 'Adding free license',
  1681. missParams: 'Missing parameters',
  1682. gettingLicenses: 'Getting licenses...',
  1683. requestingPlayTestAccess: 'Requesting play test access',
  1684. tryChangeAreaNotice: 'This function cannot detect whether the game is limited, so it will try to change the area before entering the library' + '. Failure to change the area will not affect the subsequent storage.',
  1685. versionNotMatched: 'The script manager version is too low, requiring TamperMonkey >= 5.2.0 or TamperMonkey Beta >= 5.2.6196',
  1686. gettingUserLink: 'Getting steam user community link...',
  1687. retry: 'Retry',
  1688. owned: 'Owned',
  1689. redirect: 'Redirect',
  1690. noSubid: 'skip due to unrecognized',
  1691. initingASF: 'Initing ASF...',
  1692. servers: 'Server',
  1693. joiningDiscordServer: 'Joining Discord Server',
  1694. leavingDiscordServer: 'Leaving Discord Server',
  1695. gettingDiscordGuild: 'Getting Discord server Id',
  1696. getDiscordAuthFailed: 'Failed to get Discord token, please check whether the Discord account is logged in',
  1697. discordImportantNotice: 'Important Reminder! ! !',
  1698. discordImportantNoticeText: 'Due to the background update of the Discord website, currently using this script to join a group may cause the Discord account to be forcibly logged out, and two-step verification is required to log in normally, please use it with caution! ! !',
  1699. continue: 'Continue',
  1700. skipDiscordTask: 'Skip',
  1701. continueAndDontRemindAgain: 'Continue without Reminders',
  1702. users: 'User',
  1703. loginIns: 'Please <a href="https://www.instagram.com/accounts/login/" target="_blank">log in to Instagram</a>',
  1704. insBanned: 'Your Instagram account has been banned',
  1705. verifyingInsAuth: 'Verifying Instagram token...',
  1706. gettingInsUserId: 'Getting Instagram user Id',
  1707. followingIns: 'Following Instagram user',
  1708. unfollowingIns: 'Unfollowing Instagram user',
  1709. reddits: 'Reddit/User',
  1710. loginReddit: 'Please <a href="https://www.reddit.com/login/" target="_blank">log in to Reddit</a>',
  1711. changingRedditVersion: 'Switching Reddit to a new version page...',
  1712. joiningReddit: 'Joining the Reddit',
  1713. leavingReddit: 'Leaving the Reddit',
  1714. followingRedditUser: 'Following Reddit User',
  1715. unfollowingRedditUser: 'Unfollowing Reddit User',
  1716. channels: 'Channel',
  1717. followingTwitchChannel: 'Following Twitch Channel',
  1718. unfollowingTwitchChannel: 'Unfollowing Twitch Channel',
  1719. gettingTwitchChannelId: 'Getting Twitch Channel Id',
  1720. checkingTwitchIntegrity: 'Checking Twitch integrity...',
  1721. twitterUser: 'Twitter User',
  1722. retweets: 'Retweet',
  1723. gettingTwitterUserId: 'Getting Twitter User Id',
  1724. followingTwitterUser: 'Following Twitter User',
  1725. unfollowingTwitterUser: 'Unfollowing Twitter User',
  1726. retweetting: 'Retweetting',
  1727. unretweetting: 'Unretweetting',
  1728. names: 'Group/Public/Wall',
  1729. loginVk: 'Please <a href="https://vk.com/login/" target="_blank">log in to Vk</a>',
  1730. gettingVkId: 'Getting Vk task Id',
  1731. joiningVkGroup: 'Joining Vk Group',
  1732. leavingVkGroup: 'Leaving Vk Group',
  1733. joiningVkPublic: 'Joining Vk Public',
  1734. leavingVkPublic: 'Leaving Vk Public',
  1735. sendingVkWall: 'Sending Vk Wall',
  1736. deletingVkWall: 'Deleting Vk Wall',
  1737. youtubeChannel: 'YouTube Channel',
  1738. likes: 'Like',
  1739. loginYtb: 'Please <a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">log in to YouTube</a>',
  1740. tryUpdateYtbAuth: 'Please try to <a href="https://www.youtube.com/#auth" target="_blank">update YouTube token</a>',
  1741. gettingYtbToken: 'Getting YouTube Token...',
  1742. followingYtbChannel: 'Subscribing to YouTube channel',
  1743. unfollowingYtbChannel: 'Unsubscribing to YouTube channel',
  1744. likingYtbVideo: 'Liking YouTube video',
  1745. unlikingYtbVideo: 'Unliking YouTube video',
  1746. giveKeyNoticeBefore: 'Each verification interval is 15s',
  1747. giveKeyNoticeAfter: 'If there is no key, please check at <a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>',
  1748. noPoints: 'Not enough points, skip the lottery',
  1749. getNeedPointsFailed: 'ailed to obtain the required points, skip the lottery',
  1750. joiningLottery: 'Joining the lottery',
  1751. doingGleamTask: 'Doing Gleam Task...',
  1752. gettingGleamLink: 'Getting Gleam task link...',
  1753. gleamTaskNotice: 'If this page has not been closed for a long time, please close it yourself after completing any task!',
  1754. verifiedGleamTasks: 'Attempted to verify all tasks. If the verification fails, please try to verify manually or complete it!',
  1755. campaign: 'ReCAPTCHA detected, please complete it and re-verify the tasks!',
  1756. gsNotice: 'In order to avoid getting the "0000-0000-0000" key, the "Grab Key" button has been hidden,' + ' please close the script when obtaining the key!',
  1757. giveeClubVerifyNotice: 'Verifying task...',
  1758. giveeClubVerifyFinished: 'Wait for the verification to complete and join it by yourself',
  1759. doingKeyhubTask: 'Doing Keyhub Task...',
  1760. SweepWidgetNotice: 'The task is being processed and verified. ' + 'There is an interval of 1~3s for each verification task to prevent the triggering of too fast verification warning...',
  1761. tasksNotCompleted: 'Tasks Not Completed',
  1762. notConnect: 'Social platform is not connectted, skip',
  1763. confirmingTask: 'Confirming task...'
  1764. };
  1765. const en_US = en_US_data;
  1766. const languages = {
  1767. zh: zh_CN,
  1768. en: en_US
  1769. };
  1770. const language = [ 'zh', 'en' ].includes(globalOptions.other.language) ? globalOptions.other.language : 'en';
  1771. const I18n = (key, ...argvs) => {
  1772. if (!languages[language]?.[key]) {
  1773. return key;
  1774. }
  1775. return languages[language][key].replace(/%([\d]+)/g, (match, index) => argvs[parseInt(index, 10)]);
  1776. };
  1777. const i18n = I18n;
  1778. function throwError(error, name) {
  1779. if (window.TRACE) {
  1780. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  1781. }
  1782. external_Swal_default().fire({
  1783. title: i18n('errorReport'),
  1784. icon: 'error',
  1785. showCancelButton: true,
  1786. confirmButtonText: i18n('toGithub'),
  1787. showDenyButton: true,
  1788. denyButtonText: i18n('toKeylol'),
  1789. cancelButtonText: i18n('close')
  1790. }).then(({
  1791. isDenied,
  1792. isConfirmed
  1793. }) => {
  1794. if (isConfirmed) {
  1795. GM_openInTab(`https://github.com/HCLonely/auto-task-v4/issues/new?title=${encodeURIComponent(`[BUG] 脚本报错: ${name}`)}&labels=bug&template=bug_report.yml&website=${encodeURIComponent(window.location.href)}&browser=${encodeURIComponent(JSON.stringify((0,
  1796. javascript_utils_umd_min.ua)(), null, 4))}&manager=${encodeURIComponent(`${GM_info.scriptHandler} ${GM_info.version}`)}&user-script=${encodeURIComponent(GM_info.script.version)}&logs=${encodeURIComponent(error.stack || 'null')}&run-logs=${encodeURIComponent($.makeArray($('#auto-task-info>li')).map(element => element.innerText).join('\n'))}`, {
  1797. active: true
  1798. });
  1799. } else if (isDenied) {
  1800. const text = `错误链接: [url=${window.location.href}]${window.location.href}[/url]
  1801.  
  1802. 环境:
  1803.  
  1804. [code]${JSON.stringify((0, javascript_utils_umd_min.ua)(), null, 4)}[/code]
  1805.  
  1806. 脚本管理器: ${GM_info.scriptHandler} ${GM_info.version}
  1807. 脚本版本: ${GM_info.script.version}
  1808.  
  1809. 报错信息:
  1810. [code]${error.stack}[/code]
  1811.  
  1812. 执行日志:
  1813. [code]${$.makeArray($('#auto-task-info>li')).map(element => element.innerText).join('\n')}[/code]`;
  1814. GM_setClipboard(text);
  1815. external_Swal_default().fire({
  1816. title: i18n('copySuccess'),
  1817. icon: 'success',
  1818. confirmButtonText: i18n('ok')
  1819. }).then(() => {
  1820. GM_openInTab('https://keylol.com/forum.php?mod=post&action=reply&fid=319&tid=777450', {
  1821. active: true
  1822. });
  1823. });
  1824. }
  1825. });
  1826. console.log('%c%s', 'color:white;background:red', `Auto-Task[Error]: ${name}\n${error.stack}`);
  1827. }
  1828. class Social {
  1829. tasks;
  1830. getRealParams(name, links, doTask, link2param) {
  1831. try {
  1832. let realParams = [];
  1833. if (links.length > 0) {
  1834. realParams = [ ...realParams, ...links.map(link => link2param(link)).filter(link => link) ];
  1835. }
  1836. if (!doTask && this.tasks[name].length > 0) {
  1837. realParams = [ ...realParams, ...this.tasks[name] ];
  1838. }
  1839. return unique(realParams);
  1840. } catch (error) {
  1841. throwError(error, 'Social.getRealParams');
  1842. return [];
  1843. }
  1844. }
  1845. }
  1846. const social_Social = Social;
  1847. class Discord extends social_Social {
  1848. tasks;
  1849. whiteList;
  1850. #auth = GM_getValue('discordAuth') || {};
  1851. #cache = GM_getValue('discordCache') || {};
  1852. #initialized = false;
  1853. constructor() {
  1854. super();
  1855. const defaultTasksTemplate = {
  1856. servers: []
  1857. };
  1858. this.tasks = defaultTasksTemplate;
  1859. this.whiteList = {
  1860. ...defaultTasksTemplate,
  1861. ...GM_getValue('whiteList')?.discord || {}
  1862. };
  1863. }
  1864. async init(action) {
  1865. try {
  1866. if (!GM_getValue('dontRemindDiscordAgain')) {
  1867. const result = await external_Swal_default().fire({
  1868. title: i18n('discordImportantNotice'),
  1869. text: i18n('discordImportantNoticeText'),
  1870. showCancelButton: true,
  1871. showDenyButton: true,
  1872. confirmButtonText: i18n('continue'),
  1873. cancelButtonText: i18n('skipDiscordTask'),
  1874. denyButtonText: i18n('continueAndDontRemindAgain')
  1875. }).then(({
  1876. isConfirmed,
  1877. isDenied
  1878. }) => {
  1879. if (isConfirmed) {
  1880. return true;
  1881. }
  1882. if (isDenied) {
  1883. GM_setValue('dontRemindDiscordAgain', true);
  1884. return true;
  1885. }
  1886. return false;
  1887. });
  1888. if (!result) {
  1889. this.#initialized = false;
  1890. return 'skip';
  1891. }
  1892. }
  1893. if (GM_getValue('dontRemindDiscordAgain') || action === 'do' && !globalOptions.doTask.discord.servers || action === 'undo' && !globalOptions.undoTask.discord.servers) {
  1894. this.#initialized = false;
  1895. return 'skip';
  1896. }
  1897. if (this.#initialized) {
  1898. return true;
  1899. }
  1900. if (!this.#auth.auth) {
  1901. if (await this.#updateAuth()) {
  1902. this.#initialized = true;
  1903. return true;
  1904. }
  1905. return false;
  1906. }
  1907. const isVerified = await this.#verifyAuth();
  1908. if (isVerified) {
  1909. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  1910. this.#initialized = true;
  1911. return true;
  1912. }
  1913. GM_setValue('discordAuth', {
  1914. auth: null
  1915. });
  1916. if (await this.#updateAuth()) {
  1917. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  1918. this.#initialized = true;
  1919. return true;
  1920. }
  1921. scripts_echoLog({}).error(i18n('initFailed', 'Discord'));
  1922. return false;
  1923. } catch (error) {
  1924. throwError(error, 'Discord.init');
  1925. return false;
  1926. }
  1927. }
  1928. async #verifyAuth() {
  1929. try {
  1930. const logStatus = scripts_echoLog({
  1931. text: i18n('verifyingAuth', 'Discord')
  1932. });
  1933. const {
  1934. result,
  1935. statusText,
  1936. status,
  1937. data
  1938. } = await tools_httpRequest({
  1939. url: 'https://discord.com/api/v6/users/@me',
  1940. method: 'HEAD',
  1941. headers: {
  1942. authorization: this.#auth.auth
  1943. }
  1944. });
  1945. if (result === 'Success') {
  1946. if (data?.status === 200) {
  1947. logStatus.success();
  1948. return true;
  1949. }
  1950. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  1951. return false;
  1952. }
  1953. logStatus.error(`${result}:${statusText}(${status})`);
  1954. return false;
  1955. } catch (error) {
  1956. throwError(error, 'Discord.verifyAuth');
  1957. return false;
  1958. }
  1959. }
  1960. async #updateAuth() {
  1961. try {
  1962. const logStatus = scripts_echoLog({
  1963. text: i18n('updatingAuth', 'Discord')
  1964. });
  1965. return await new Promise(resolve => {
  1966. const newTab = GM_openInTab('https://discord.com/channels/@me', {
  1967. active: true,
  1968. insert: true,
  1969. setParent: true
  1970. });
  1971. newTab.name = 'ATv4_discordAuth';
  1972. newTab.onclose = async () => {
  1973. const auth = GM_getValue('discordAuth')?.auth;
  1974. if (auth) {
  1975. this.#auth = {
  1976. auth: auth
  1977. };
  1978. logStatus.success();
  1979. resolve(await this.#verifyAuth());
  1980. } else {
  1981. logStatus.error('Error: Update discord auth failed!');
  1982. resolve(false);
  1983. }
  1984. };
  1985. });
  1986. } catch (error) {
  1987. throwError(error, 'Discord.updateAuth');
  1988. return false;
  1989. }
  1990. }
  1991. async #joinServer(inviteId) {
  1992. try {
  1993. const logStatus = scripts_echoLog({
  1994. type: 'joiningDiscordServer',
  1995. text: inviteId
  1996. });
  1997. const {
  1998. result,
  1999. statusText,
  2000. status,
  2001. data
  2002. } = await tools_httpRequest({
  2003. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2004. method: 'POST',
  2005. dataType: 'json',
  2006. headers: {
  2007. authorization: this.#auth.auth,
  2008. origin: 'https://discord.com',
  2009. referer: `https://discord.com/invite/${inviteId}`
  2010. }
  2011. });
  2012. if (result === 'Success' && data?.status === 200) {
  2013. logStatus.success();
  2014. const guild = String(data.response?.guild?.id);
  2015. if (guild) {
  2016. this.#setCache(inviteId, guild);
  2017. this.tasks.servers = unique([ ...this.tasks.servers, inviteId ]);
  2018. }
  2019. return true;
  2020. }
  2021. logStatus.error(`${result}:${statusText}(${status})`);
  2022. return false;
  2023. } catch (error) {
  2024. throwError(error, 'Discord.joinServer');
  2025. return false;
  2026. }
  2027. }
  2028. async #leaveServer(inviteId) {
  2029. try {
  2030. if (this.whiteList.servers.includes(inviteId)) {
  2031. scripts_echoLog({
  2032. type: 'whiteList',
  2033. text: 'Discord.leaveServer',
  2034. id: inviteId
  2035. });
  2036. return true;
  2037. }
  2038. const guild = await this.#getGuild(inviteId);
  2039. if (!guild) {
  2040. return false;
  2041. }
  2042. const logStatus = scripts_echoLog({
  2043. type: 'leavingDiscordServer',
  2044. text: guild
  2045. });
  2046. const {
  2047. result,
  2048. statusText,
  2049. status,
  2050. data
  2051. } = await tools_httpRequest({
  2052. url: `https://discord.com/api/v9/users/@me/guilds/${guild}`,
  2053. method: 'DELETE',
  2054. headers: {
  2055. authorization: this.#auth.auth
  2056. }
  2057. });
  2058. if (result === 'Success' && data?.status === 204) {
  2059. logStatus.success();
  2060. return true;
  2061. }
  2062. logStatus.error(`${result}:${statusText}(${status})`);
  2063. return false;
  2064. } catch (error) {
  2065. throwError(error, 'Discord.leaveServer');
  2066. return false;
  2067. }
  2068. }
  2069. async #getGuild(inviteId) {
  2070. try {
  2071. const logStatus = scripts_echoLog({
  2072. type: 'gettingDiscordGuild',
  2073. text: inviteId
  2074. });
  2075. const guild = this.#cache[inviteId];
  2076. if (guild) {
  2077. logStatus.success();
  2078. return guild;
  2079. }
  2080. const {
  2081. result,
  2082. statusText,
  2083. status,
  2084. data
  2085. } = await tools_httpRequest({
  2086. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2087. responseType: 'json',
  2088. method: 'GET'
  2089. });
  2090. if (result === 'Success' && data?.status === 200) {
  2091. const guild = data.response?.guild?.id;
  2092. if (guild) {
  2093. logStatus.success();
  2094. this.#setCache(inviteId, guild);
  2095. return guild;
  2096. }
  2097. logStatus.error(`${result}:${statusText}(${status})`);
  2098. return false;
  2099. }
  2100. logStatus.error(`${result}:${statusText}(${status})`);
  2101. return false;
  2102. } catch (error) {
  2103. throwError(error, 'Discord.getGuild');
  2104. return false;
  2105. }
  2106. }
  2107. async toggle({
  2108. doTask = true,
  2109. serverLinks = []
  2110. }) {
  2111. try {
  2112. if (!this.#initialized) {
  2113. scripts_echoLog({
  2114. text: i18n('needInit')
  2115. });
  2116. return false;
  2117. }
  2118. const prom = [];
  2119. if (doTask && !globalOptions.doTask.discord.servers || !doTask && !globalOptions.undoTask.discord.servers) {
  2120. scripts_echoLog({
  2121. type: 'globalOptionsSkip',
  2122. text: 'discord.servers'
  2123. });
  2124. } else {
  2125. const realServers = this.getRealParams('servers', serverLinks, doTask, link => link.match(/invite\/(.+)/)?.[1]);
  2126. if (realServers.length > 0) {
  2127. for (const server of realServers) {
  2128. if (doTask) {
  2129. prom.push(this.#joinServer(server));
  2130. } else {
  2131. prom.push(this.#leaveServer(server));
  2132. }
  2133. await delay(1e3);
  2134. }
  2135. }
  2136. }
  2137. return await Promise.all(prom).then(() => true);
  2138. } catch (error) {
  2139. throwError(error, 'Discord.toggleServers');
  2140. return false;
  2141. }
  2142. }
  2143. #setCache(inviteId, guild) {
  2144. try {
  2145. this.#cache[inviteId] = guild;
  2146. GM_setValue('discordCache', this.#cache);
  2147. } catch (error) {
  2148. throwError(error, 'Discord.setCache');
  2149. }
  2150. }
  2151. }
  2152. const social_Discord = Discord;
  2153. class Instagram extends social_Social {
  2154. tasks;
  2155. whiteList;
  2156. #cache = GM_getValue('instagramCache') || {};
  2157. #auth = {};
  2158. #initialized = false;
  2159. constructor() {
  2160. super();
  2161. const defaultTasksTemplate = {
  2162. users: []
  2163. };
  2164. this.tasks = defaultTasksTemplate;
  2165. this.whiteList = {
  2166. ...defaultTasksTemplate,
  2167. ...GM_getValue('whiteList')?.instagram || {}
  2168. };
  2169. }
  2170. async init() {
  2171. try {
  2172. if (this.#initialized) {
  2173. return true;
  2174. }
  2175. const isVerified = await this.#getUserInfo();
  2176. if (isVerified) {
  2177. scripts_echoLog({}).success(i18n('initSuccess', 'Instagram'));
  2178. this.#initialized = true;
  2179. return true;
  2180. }
  2181. scripts_echoLog({}).error(i18n('initFailed', 'Instagram'));
  2182. return false;
  2183. } catch (error) {
  2184. throwError(error, 'Instagram.init');
  2185. return false;
  2186. }
  2187. }
  2188. async #getUserInfo(name = 'instagram') {
  2189. try {
  2190. const logStatus = scripts_echoLog({
  2191. type: name === 'instagram' ? 'verifyingInsAuth' : 'gettingInsUserId',
  2192. text: name
  2193. });
  2194. const userId = this.#cache[name];
  2195. if (userId && name !== 'instagram') {
  2196. logStatus.success();
  2197. return userId;
  2198. }
  2199. const {
  2200. result,
  2201. statusText,
  2202. status,
  2203. data
  2204. } = await tools_httpRequest({
  2205. url: `https://www.instagram.com/${name}/`,
  2206. method: 'GET'
  2207. });
  2208. if (result === 'Success') {
  2209. if (data?.finalUrl.includes('accounts/login')) {
  2210. logStatus.error(`Error:${i18n('loginIns')}`, true);
  2211. return false;
  2212. } else if (data?.finalUrl.includes('www.instagram.com/challenge')) {
  2213. logStatus.error(`Error:${i18n('insBanned')}`);
  2214. return false;
  2215. }
  2216. if (data?.status === 200) {
  2217. const csrftoken = data.responseText.match(/"csrf_token":"(.+?)"/)?.[1];
  2218. const hash = data.responseText.match(/"rollout_hash":"(.+?)"/)?.[1];
  2219. if (name === 'instagram') {
  2220. if (csrftoken && hash) {
  2221. this.#auth = {
  2222. csrftoken: csrftoken,
  2223. hash: hash
  2224. };
  2225. return true;
  2226. }
  2227. return false;
  2228. }
  2229. const id = data.responseText.match(/"profilePage_([\d]+?)"/)?.[1];
  2230. if (id) {
  2231. this.#setCache(name, id);
  2232. logStatus.success();
  2233. return id;
  2234. }
  2235. logStatus.error('Error: Get ins data error!');
  2236. return false;
  2237. }
  2238. logStatus.error(`${result}:${statusText}(${status})`);
  2239. return false;
  2240. }
  2241. return false;
  2242. } catch (error) {
  2243. throwError(error, 'Instagram.getUserInfo');
  2244. return false;
  2245. }
  2246. }
  2247. async #followUser(name) {
  2248. try {
  2249. const id = await this.#getUserInfo(name);
  2250. if (!id) {
  2251. return false;
  2252. }
  2253. const logStatus = scripts_echoLog({
  2254. type: 'followingIns',
  2255. text: name
  2256. });
  2257. const {
  2258. result,
  2259. statusText,
  2260. status,
  2261. data
  2262. } = await tools_httpRequest({
  2263. url: `https://www.instagram.com/web/friendships/${id}/follow/`,
  2264. method: 'POST',
  2265. dataType: 'json',
  2266. headers: {
  2267. 'x-csrftoken': this.#auth.csrftoken,
  2268. origin: 'https://www.instagram.com',
  2269. referer: `https://www.instagram.com/${name}/`,
  2270. 'content-type': 'application/x-www-form-urlencoded',
  2271. 'sec-fetch-site': 'same-origin',
  2272. 'x-instagram-ajax': this.#auth.hash
  2273. }
  2274. });
  2275. if (result === 'Success') {
  2276. if (data?.status === 200 && data.response?.result === 'following') {
  2277. logStatus.success();
  2278. this.tasks.users = unique([ ...this.tasks.users, name ]);
  2279. return true;
  2280. }
  2281. logStatus.error(`Error:${data?.response?.feedback_message || `${data?.statusText}(${data?.status})`}`);
  2282. return false;
  2283. }
  2284. logStatus.error(`${result}:${statusText}(${status})`);
  2285. return false;
  2286. } catch (error) {
  2287. throwError(error, 'Instagram.followUser');
  2288. return false;
  2289. }
  2290. }
  2291. async #unfollowUser(name) {
  2292. try {
  2293. if (this.whiteList.users.includes(name)) {
  2294. scripts_echoLog({
  2295. type: 'whiteList',
  2296. text: 'Instagram.unfollowUser',
  2297. id: name
  2298. });
  2299. return true;
  2300. }
  2301. const id = await this.#getUserInfo(name);
  2302. if (!id) {
  2303. return false;
  2304. }
  2305. const logStatus = scripts_echoLog({
  2306. type: 'unfollowingIns',
  2307. text: name
  2308. });
  2309. const {
  2310. result,
  2311. statusText,
  2312. status,
  2313. data
  2314. } = await tools_httpRequest({
  2315. url: `https://www.instagram.com/web/friendships/${id}/unfollow/`,
  2316. method: 'POST',
  2317. dataType: 'json',
  2318. headers: {
  2319. 'x-csrftoken': this.#auth.csrftoken,
  2320. origin: 'https://www.instagram.com',
  2321. referer: `https://www.instagram.com/${name}/`,
  2322. 'content-type': 'application/x-www-form-urlencoded',
  2323. 'sec-fetch-site': 'same-origin',
  2324. 'x-instagram-ajax': this.#auth.hash
  2325. }
  2326. });
  2327. if (result === 'Success') {
  2328. if (data?.status === 200 && data.response?.status === 'ok') {
  2329. logStatus.success();
  2330. return true;
  2331. }
  2332. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2333. return false;
  2334. }
  2335. logStatus.error(`${result}:${statusText}(${status})`);
  2336. return false;
  2337. } catch (error) {
  2338. throwError(error, 'Instagram.unfollowUser');
  2339. return false;
  2340. }
  2341. }
  2342. async toggle({
  2343. doTask = true,
  2344. userLinks = []
  2345. }) {
  2346. try {
  2347. if (!this.#initialized) {
  2348. scripts_echoLog({
  2349. text: i18n('needInit')
  2350. });
  2351. return false;
  2352. }
  2353. const prom = [];
  2354. if (doTask && !globalOptions.doTask.instagram.users || !doTask && !globalOptions.undoTask.instagram.users) {
  2355. scripts_echoLog({
  2356. type: 'globalOptionsSkip',
  2357. text: 'instagram.users'
  2358. });
  2359. } else {
  2360. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1]);
  2361. if (realUsers.length > 0) {
  2362. for (const username of realUsers) {
  2363. if (doTask) {
  2364. prom.push(this.#followUser(username));
  2365. } else {
  2366. prom.push(this.#unfollowUser(username));
  2367. }
  2368. await delay(1e3);
  2369. }
  2370. }
  2371. }
  2372. return await Promise.all(prom).then(() => true);
  2373. } catch (error) {
  2374. throwError(error, 'Instagram.toggleUsers');
  2375. return false;
  2376. }
  2377. }
  2378. #setCache(name, id) {
  2379. try {
  2380. this.#cache[name] = id;
  2381. GM_setValue('instagramCache', this.#cache);
  2382. } catch (error) {
  2383. throwError(error, 'Instagram.setCache');
  2384. }
  2385. }
  2386. }
  2387. const social_Instagram = Instagram;
  2388. class Reddit extends social_Social {
  2389. tasks;
  2390. whiteList;
  2391. #auth;
  2392. #initialized = false;
  2393. constructor() {
  2394. super();
  2395. const defaultTasksTemplate = {
  2396. reddits: []
  2397. };
  2398. this.tasks = defaultTasksTemplate;
  2399. this.whiteList = {
  2400. ...defaultTasksTemplate,
  2401. ...GM_getValue('whiteList')?.reddit || {}
  2402. };
  2403. }
  2404. async init() {
  2405. try {
  2406. if (this.#initialized) {
  2407. return true;
  2408. }
  2409. const isVerified = await this.#updateAuth();
  2410. if (isVerified) {
  2411. scripts_echoLog({}).success(i18n('initSuccess', 'Reddit'));
  2412. this.#initialized = true;
  2413. return true;
  2414. }
  2415. scripts_echoLog({}).error(i18n('initFailed', 'Reddit'));
  2416. return false;
  2417. } catch (error) {
  2418. throwError(error, 'Reddit.init');
  2419. return false;
  2420. }
  2421. }
  2422. async #useBeta() {
  2423. try {
  2424. const logStatus = scripts_echoLog({
  2425. text: i18n('changingRedditVersion')
  2426. });
  2427. return await new Promise(resolve => {
  2428. const newTab = GM_openInTab('https://www.reddit.com/', {
  2429. active: true,
  2430. insert: true,
  2431. setParent: true
  2432. });
  2433. newTab.name = 'ATv4_redditAuth';
  2434. newTab.onclose = async () => {
  2435. logStatus.success();
  2436. resolve(await this.#updateAuth(true));
  2437. };
  2438. });
  2439. } catch (error) {
  2440. throwError(error, 'Reddit.useBeta');
  2441. return false;
  2442. }
  2443. }
  2444. async #updateAuth(beta = false) {
  2445. try {
  2446. const logStatus = scripts_echoLog({
  2447. text: i18n('updatingAuth', 'Reddit')
  2448. });
  2449. const {
  2450. result,
  2451. statusText,
  2452. status,
  2453. data
  2454. } = await tools_httpRequest({
  2455. url: 'https://www.reddit.com/',
  2456. method: 'GET',
  2457. nochche: true,
  2458. headers: {
  2459. 'Cache-Control': 'no-cache'
  2460. }
  2461. });
  2462. if (result === 'Success') {
  2463. if (data?.responseText.includes('www.reddit.com/login/')) {
  2464. logStatus.error(`Error:${i18n('loginReddit')}`, true);
  2465. return false;
  2466. }
  2467. if (data?.status === 200) {
  2468. if (data.responseText.includes('redesign-beta-optin-btn') && !beta) {
  2469. return await this.#useBeta();
  2470. }
  2471. const accessToken = data.responseText.match(/"accessToken":"(.*?)","expires":"(.*?)"/)?.[1];
  2472. if (accessToken) {
  2473. this.#auth = {
  2474. token: accessToken
  2475. };
  2476. logStatus.success();
  2477. return true;
  2478. }
  2479. logStatus.error('Error: Parameter "accessToken" not found!');
  2480. return false;
  2481. }
  2482. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2483. return false;
  2484. }
  2485. logStatus.error(`${result}:${statusText}(${status})`);
  2486. return false;
  2487. } catch (error) {
  2488. throwError(error, 'Reddit.updateAuth');
  2489. return false;
  2490. }
  2491. }
  2492. async #toggleTask({
  2493. name,
  2494. doTask = true
  2495. }) {
  2496. try {
  2497. if (!doTask && this.whiteList.reddits.includes(name)) {
  2498. scripts_echoLog({
  2499. type: 'whiteList',
  2500. text: 'Reddit.undoTask',
  2501. id: name
  2502. });
  2503. return true;
  2504. }
  2505. let type = doTask ? 'joiningReddit' : 'leavingReddit';
  2506. if (/^u_/.test(name)) {
  2507. type = doTask ? 'followingRedditUser' : 'unfollowingRedditUser';
  2508. }
  2509. const logStatus = scripts_echoLog({
  2510. type: type,
  2511. text: name
  2512. });
  2513. const {
  2514. result,
  2515. statusText,
  2516. status,
  2517. data
  2518. } = await tools_httpRequest({
  2519. url: 'https://oauth.reddit.com/api/subscribe?redditWebClient=desktop2x&app=desktop2x-client-production&raw_json=1&gilding_detail=1',
  2520. method: 'POST',
  2521. headers: {
  2522. authorization: `Bearer ${this.#auth.token}`,
  2523. 'content-type': 'application/x-www-form-urlencoded'
  2524. },
  2525. data: $.param({
  2526. action: doTask ? 'sub' : 'unsub',
  2527. sr_name: name,
  2528. api_type: 'json'
  2529. })
  2530. });
  2531. if (result === 'Success') {
  2532. if (data?.status === 200) {
  2533. logStatus.success();
  2534. if (doTask) {
  2535. this.tasks.reddits = unique([ ...this.tasks.reddits, name ]);
  2536. }
  2537. return true;
  2538. }
  2539. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2540. return false;
  2541. }
  2542. logStatus.error(`${result}:${statusText}(${status})`);
  2543. return false;
  2544. } catch (error) {
  2545. throwError(error, 'Reddit.toggleTask');
  2546. return false;
  2547. }
  2548. }
  2549. async toggle({
  2550. doTask = true,
  2551. redditLinks = []
  2552. }) {
  2553. try {
  2554. if (!this.#initialized) {
  2555. scripts_echoLog({
  2556. text: i18n('needInit')
  2557. });
  2558. return false;
  2559. }
  2560. const prom = [];
  2561. if (doTask && !globalOptions.doTask.reddit.reddits || !doTask && !globalOptions.undoTask.reddit.reddits) {
  2562. scripts_echoLog({
  2563. type: 'globalOptionsSkip',
  2564. text: 'reddit.reddits'
  2565. });
  2566. } else {
  2567. const realReddits = this.getRealParams('reddits', redditLinks, doTask, link => {
  2568. const name = link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1];
  2569. const userName = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1];
  2570. if (userName) {
  2571. return name || userName;
  2572. }
  2573. return name;
  2574. });
  2575. if (realReddits.length > 0) {
  2576. for (const name of realReddits) {
  2577. prom.push(this.#toggleTask({
  2578. name: name,
  2579. doTask: doTask
  2580. }));
  2581. await delay(1e3);
  2582. }
  2583. }
  2584. }
  2585. return await Promise.all(prom).then(() => true);
  2586. } catch (error) {
  2587. throwError(error, 'Reddit.toggle');
  2588. return false;
  2589. }
  2590. }
  2591. }
  2592. const social_Reddit = Reddit;
  2593. class Twitch extends social_Social {
  2594. tasks;
  2595. whiteList;
  2596. #auth = GM_getValue('twitchAuth') || {};
  2597. #cache = GM_getValue('twitchCache') || {};
  2598. #initialized = false;
  2599. #integrityToken;
  2600. constructor() {
  2601. super();
  2602. const defaultTasksTemplate = {
  2603. channels: []
  2604. };
  2605. this.tasks = defaultTasksTemplate;
  2606. this.whiteList = {
  2607. ...defaultTasksTemplate,
  2608. ...GM_getValue('whiteList')?.twitch || {}
  2609. };
  2610. }
  2611. async init() {
  2612. try {
  2613. if (this.#initialized) {
  2614. return true;
  2615. }
  2616. if (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId) {
  2617. if (await this.#updateAuth()) {
  2618. this.#initialized = true;
  2619. return true;
  2620. }
  2621. return false;
  2622. }
  2623. const isVerified = await this.#verifyAuth(true);
  2624. if (isVerified) {
  2625. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  2626. this.#initialized = true;
  2627. return true;
  2628. }
  2629. GM_setValue('twitchAuth', null);
  2630. if (await this.#updateAuth()) {
  2631. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  2632. this.#initialized = true;
  2633. return true;
  2634. }
  2635. scripts_echoLog({}).error(i18n('initFailed', 'Twitch'));
  2636. return false;
  2637. } catch (error) {
  2638. throwError(error, 'Twitch.init');
  2639. return false;
  2640. }
  2641. }
  2642. async #verifyAuth(isFirst) {
  2643. try {
  2644. const logStatus = scripts_echoLog({
  2645. text: i18n('verifyingAuth', 'Twitch')
  2646. });
  2647. const {
  2648. result,
  2649. statusText,
  2650. status,
  2651. data
  2652. } = await tools_httpRequest({
  2653. url: 'https://gql.twitch.tv/gql',
  2654. method: 'POST',
  2655. dataType: 'json',
  2656. headers: {
  2657. Authorization: `OAuth ${this.#auth.authToken}`,
  2658. 'Client-Id': this.#auth.clientId
  2659. },
  2660. data: '[{"operationName":"FrontPageNew_User","variables":{"limit":1},"extensions":{"persistedQuery":{"version":1,' + '"sha256Hash":"64bd07a2cbaca80699d62636d966cf6395a5d14a1f0a14282067dcb28b13eb11"}}}]'
  2661. });
  2662. if (result === 'Success') {
  2663. if (data?.status === 200 && data.response?.[0]?.data?.currentUser) {
  2664. await this.#integrity(isFirst);
  2665. logStatus.success();
  2666. return true;
  2667. }
  2668. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2669. return false;
  2670. }
  2671. logStatus.error(`${result}:${statusText}(${status})`);
  2672. return false;
  2673. } catch (error) {
  2674. throwError(error, 'Twitch.verifyAuth');
  2675. return false;
  2676. }
  2677. }
  2678. async #integrity(isFirst = true, ct = '') {
  2679. try {
  2680. const logStatus = scripts_echoLog({
  2681. text: i18n('checkingTwitchIntegrity')
  2682. });
  2683. if (isFirst && (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId)) {
  2684. return await this.#updateAuth(false);
  2685. }
  2686. const {
  2687. result,
  2688. statusText,
  2689. status,
  2690. data
  2691. } = await tools_httpRequest({
  2692. url: 'https://gql.twitch.tv/integrity',
  2693. method: 'POST',
  2694. dataType: 'json',
  2695. anonymous: true,
  2696. headers: {
  2697. Origin: 'https://www.twitch.tv',
  2698. Referer: 'https://www.twitch.tv/',
  2699. Authorization: `OAuth ${this.#auth.authToken}`,
  2700. 'Client-Id': this.#auth.clientId,
  2701. 'Client-Version': this.#auth.clientVersion,
  2702. 'X-Device-Id': this.#auth.deviceId,
  2703. 'Client-Session-Id': this.#auth.clientSessionId,
  2704. 'x-kpsdk-ct': ct
  2705. }
  2706. });
  2707. if (result === 'Success') {
  2708. if (!ct && data?.responseHeaders?.['x-kpsdk-ct']) {
  2709. return await this.#integrity(isFirst, data.responseHeaders['x-kpsdk-ct']);
  2710. }
  2711. if (data?.status === 200 && data.response?.token) {
  2712. this.#integrityToken = data.response.token;
  2713. logStatus.success();
  2714. return true;
  2715. }
  2716. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2717. return false;
  2718. }
  2719. logStatus.error(`${result}:${statusText}(${status})`);
  2720. return false;
  2721. } catch (error) {
  2722. throwError(error, 'Twitch.integrity');
  2723. return false;
  2724. }
  2725. }
  2726. async #updateAuth(isFirst = true) {
  2727. try {
  2728. const logStatus = scripts_echoLog({
  2729. text: i18n('updatingAuth', 'Twitch')
  2730. });
  2731. return await new Promise(resolve => {
  2732. const newTab = GM_openInTab('https://www.twitch.tv/', {
  2733. active: true,
  2734. insert: true,
  2735. setParent: true
  2736. });
  2737. newTab.name = 'ATv4_twitchAuth';
  2738. newTab.onclose = async () => {
  2739. const auth = GM_getValue('twitchAuth');
  2740. if (auth) {
  2741. this.#auth = auth;
  2742. logStatus.success();
  2743. resolve(await this.#verifyAuth(isFirst));
  2744. } else {
  2745. logStatus.error('Error: Update twitch auth failed!');
  2746. resolve(false);
  2747. }
  2748. };
  2749. });
  2750. } catch (error) {
  2751. throwError(error, 'Twitch.updateAuth');
  2752. return false;
  2753. }
  2754. }
  2755. async #toggleChannel({
  2756. name,
  2757. doTask = true
  2758. }) {
  2759. try {
  2760. if (!doTask && this.whiteList.channels.includes(name)) {
  2761. scripts_echoLog({
  2762. type: 'whiteList',
  2763. text: 'Twitch.unfollowChannel',
  2764. id: name
  2765. });
  2766. return true;
  2767. }
  2768. const channelId = await this.#getChannelId(name);
  2769. if (!channelId) {
  2770. return false;
  2771. }
  2772. const logStatus = scripts_echoLog({
  2773. type: `${doTask ? '' : 'un'}followingTwitchChannel`,
  2774. text: name
  2775. });
  2776. const followData = `[{"operationName":"FollowButton_FollowUser","variables":{"input":{"disableNotifications":false,"targetID":"${channelId}` + '"}},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"800e7346bdf7e5278a3c1d3f21b2b56e2639928f86815677a7126b093b2fdd08"}}}]';
  2777. const unfollowData = `[{"operationName":"FollowButton_UnfollowUser","variables":{"input":{"targetID":"${channelId}"}},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"f7dae976ebf41c755ae2d758546bfd176b4eeb856656098bb40e0a672ca0d880"}}}]';
  2778. const {
  2779. result,
  2780. statusText,
  2781. status,
  2782. data
  2783. } = await tools_httpRequest({
  2784. url: 'https://gql.twitch.tv/gql',
  2785. method: 'POST',
  2786. dataType: 'json',
  2787. anonymous: true,
  2788. headers: {
  2789. Origin: 'https://www.twitch.tv',
  2790. Referer: 'https://www.twitch.tv/',
  2791. Authorization: `OAuth ${this.#auth.authToken}`,
  2792. 'Client-Id': this.#auth.clientId,
  2793. 'Client-Version': this.#auth.clientVersion,
  2794. 'X-Device-Id': this.#auth.deviceId,
  2795. 'Client-Session-Id': this.#auth.clientSessionId,
  2796. 'Client-Integrity': this.#integrityToken
  2797. },
  2798. data: doTask ? followData : unfollowData
  2799. });
  2800. if (result === 'Success') {
  2801. if (data?.status === 200 && data.response?.[0] && !data.response[0].errors) {
  2802. logStatus.success();
  2803. if (doTask) {
  2804. this.tasks.channels = unique([ ...this.tasks.channels, name ]);
  2805. }
  2806. return true;
  2807. }
  2808. logStatus.error(`Error:${data?.response?.[0].errors?.[0]?.message || `${data?.statusText}(${data?.status})`}`);
  2809. return false;
  2810. }
  2811. logStatus.error(`${result}:${statusText}(${status})`);
  2812. return false;
  2813. } catch (error) {
  2814. throwError(error, 'Twitch.toggleChannel');
  2815. return false;
  2816. }
  2817. }
  2818. async #getChannelId(name) {
  2819. try {
  2820. const logStatus = scripts_echoLog({
  2821. type: 'gettingTwitchChannelId',
  2822. text: name
  2823. });
  2824. const channelId = this.#cache[name];
  2825. if (channelId) {
  2826. logStatus.success();
  2827. return channelId;
  2828. }
  2829. const {
  2830. result,
  2831. statusText,
  2832. status,
  2833. data
  2834. } = await tools_httpRequest({
  2835. url: 'https://gql.twitch.tv/gql',
  2836. method: 'POST',
  2837. headers: {
  2838. Authorization: `OAuth ${this.#auth.authToken}`,
  2839. 'Client-Id': this.#auth.clientId
  2840. },
  2841. responseType: 'json',
  2842. data: `[{"operationName":"ActiveWatchParty","variables":{"channelLogin":"${name}"},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"4a8156c97b19e3a36e081cf6d6ddb5dbf9f9b02ae60e4d2ff26ed70aebc80a30"}}}]'
  2843. });
  2844. if (result === 'Success') {
  2845. if (data?.status === 200) {
  2846. const channelId = data.response?.[0]?.data?.user?.id;
  2847. if (channelId) {
  2848. this.#setCache(name, String(channelId));
  2849. logStatus.success();
  2850. return channelId;
  2851. }
  2852. logStatus.error(`Error:${data.statusText}(${data.status})`);
  2853. return false;
  2854. }
  2855. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2856. return false;
  2857. }
  2858. logStatus.error(`${result}:${statusText}(${status})`);
  2859. return false;
  2860. } catch (error) {
  2861. throwError(error, 'Twitch.getChannelId');
  2862. return false;
  2863. }
  2864. }
  2865. async toggle({
  2866. doTask = true,
  2867. channelLinks = []
  2868. }) {
  2869. try {
  2870. if (!this.#initialized) {
  2871. scripts_echoLog({
  2872. text: i18n('needInit')
  2873. });
  2874. return false;
  2875. }
  2876. const prom = [];
  2877. if (doTask && !globalOptions.doTask.twitch.channels || !doTask && !globalOptions.undoTask.twitch.channels) {
  2878. scripts_echoLog({
  2879. type: 'globalOptionsSkip',
  2880. text: 'twitch.channels'
  2881. });
  2882. } else {
  2883. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2]);
  2884. if (realChannels.length > 0) {
  2885. for (const channel of realChannels) {
  2886. prom.push(this.#toggleChannel({
  2887. name: channel,
  2888. doTask: doTask
  2889. }));
  2890. await delay(1e3);
  2891. }
  2892. }
  2893. }
  2894. return Promise.all(prom).then(() => true);
  2895. } catch (error) {
  2896. throwError(error, 'Twitch.toggle');
  2897. return false;
  2898. }
  2899. }
  2900. #setCache(name, id) {
  2901. try {
  2902. this.#cache[name] = id;
  2903. GM_setValue('twitchCache', this.#cache);
  2904. } catch (error) {
  2905. throwError(error, 'Twitch.setCache');
  2906. }
  2907. }
  2908. }
  2909. const social_Twitch = Twitch;
  2910. class Twitter extends social_Social {
  2911. tasks;
  2912. whiteList;
  2913. #verifyId = globalOptions.other.twitterVerifyId;
  2914. #auth = GM_getValue('twitterAuth') || {};
  2915. #cache = GM_getValue('twitterCache') || {};
  2916. #initialized = false;
  2917. constructor() {
  2918. super();
  2919. const defaultTasksTemplate = {
  2920. users: [],
  2921. retweets: [],
  2922. likes: []
  2923. };
  2924. this.tasks = defaultTasksTemplate;
  2925. this.whiteList = {
  2926. ...defaultTasksTemplate,
  2927. ...GM_getValue('whiteList')?.twitter || {}
  2928. };
  2929. }
  2930. async init() {
  2931. try {
  2932. if (this.#initialized) {
  2933. return true;
  2934. }
  2935. if (!this.#auth.ct0) {
  2936. if (await this.#updateAuth()) {
  2937. this.#initialized = true;
  2938. return true;
  2939. }
  2940. return false;
  2941. }
  2942. const isVerified = await this.#verifyAuth();
  2943. if (isVerified) {
  2944. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  2945. this.#initialized = true;
  2946. return true;
  2947. }
  2948. GM_setValue('twitterAuth', null);
  2949. if (await this.#updateAuth()) {
  2950. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  2951. this.#initialized = true;
  2952. return true;
  2953. }
  2954. scripts_echoLog({}).error(i18n('initFailed', 'Twitter'));
  2955. return false;
  2956. } catch (error) {
  2957. throwError(error, 'Twitter.init');
  2958. return false;
  2959. }
  2960. }
  2961. async #verifyAuth() {
  2962. try {
  2963. return await this.#toggleUser({
  2964. name: 'verify',
  2965. doTask: true,
  2966. verify: true
  2967. });
  2968. } catch (error) {
  2969. throwError(error, 'Twitter.verifyAuth');
  2970. return false;
  2971. }
  2972. }
  2973. async #updateAuth() {
  2974. try {
  2975. const logStatus = scripts_echoLog({
  2976. text: i18n('updatingAuth', 'Twitter')
  2977. });
  2978. return await new Promise(resolve => {
  2979. GM_cookie.list({
  2980. url: 'https://x.com/settings/account'
  2981. }, async (cookies, error) => {
  2982. if (!error) {
  2983. const [ ct0, isLogin ] = cookies.map(cookie => [ 'ct0', 'twid' ].includes(cookie.name) ? cookie.value : null).filter(cookie => cookie);
  2984. if (isLogin && ct0) {
  2985. GM_setValue('twitterAuth', {
  2986. ct0: ct0
  2987. });
  2988. this.#auth = {
  2989. ct0: ct0
  2990. };
  2991. logStatus.success();
  2992. resolve(await this.#verifyAuth());
  2993. } else {
  2994. logStatus.error(i18n('needLogin'));
  2995. resolve(false);
  2996. }
  2997. } else {
  2998. logStatus.error('Error: Update twitter auth failed!');
  2999. resolve(false);
  3000. }
  3001. });
  3002. });
  3003. } catch (error) {
  3004. throwError(error, 'Twitter.updateToken');
  3005. return false;
  3006. }
  3007. }
  3008. async #toggleUser({
  3009. name,
  3010. doTask = true,
  3011. verify = false,
  3012. retry = false
  3013. }) {
  3014. try {
  3015. if (!doTask && !verify && this.whiteList.users.includes(name)) {
  3016. scripts_echoLog({
  3017. type: 'whiteList',
  3018. text: 'Twitter.unfollowUser',
  3019. id: name
  3020. });
  3021. return true;
  3022. }
  3023. const userId = verify ? this.#verifyId : await this.userName2id(name);
  3024. if (!userId) {
  3025. return false;
  3026. }
  3027. const logStatus = verify ? scripts_echoLog({
  3028. text: i18n('verifyingAuth', 'Twitter')
  3029. }) : scripts_echoLog({
  3030. type: `${doTask ? '' : 'un'}followingTwitterUser`,
  3031. text: name
  3032. });
  3033. const {
  3034. result,
  3035. statusText,
  3036. status,
  3037. data
  3038. } = await tools_httpRequest({
  3039. url: `https://x.com/i/api/1.1/friendships/${doTask ? 'create' : 'destroy'}.json`,
  3040. method: 'POST',
  3041. headers: {
  3042. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3043. 'Content-Type': 'application/x-www-form-urlencoded',
  3044. 'x-csrf-token': this.#auth.ct0,
  3045. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3046. 'X-Twitter-Active-User': 'yes'
  3047. },
  3048. responseType: 'json',
  3049. data: $.param({
  3050. include_profile_interstitial_type: 1,
  3051. include_blocking: 1,
  3052. include_blocked_by: 1,
  3053. include_followed_by: 1,
  3054. include_want_retweets: 1,
  3055. include_mute_edge: 1,
  3056. include_can_dm: 1,
  3057. include_can_media_tag: 1,
  3058. skip_status: 1,
  3059. id: userId
  3060. })
  3061. });
  3062. if (result === 'Success') {
  3063. if (data?.status === 200) {
  3064. logStatus.success();
  3065. if (doTask && !verify) {
  3066. this.tasks.users = unique([ ...this.tasks.users, name ]);
  3067. }
  3068. return true;
  3069. }
  3070. if (verify && data?.status === 403) {
  3071. if (data.response?.errors?.[0]?.code === 158) {
  3072. logStatus.success();
  3073. return true;
  3074. }
  3075. if (data.response?.errors?.[0]?.code === 353 && !retry && data.responseHeaders?.['set-cookie']) {
  3076. this.#auth.ct0 = data.responseHeaders['set-cookie']?.find(cookie => cookie.includes('ct0='))?.split(';')?.at(0)?.split('=')?.at(-1) || this.#auth.ct0;
  3077. logStatus.warning(i18n('retry'));
  3078. return this.#toggleUser({
  3079. name: name,
  3080. doTask: doTask,
  3081. verify: verify,
  3082. retry: true
  3083. });
  3084. }
  3085. }
  3086. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3087. return false;
  3088. }
  3089. logStatus.error(`${result}:${statusText}(${status})`);
  3090. return false;
  3091. } catch (error) {
  3092. throwError(error, 'Twitter.toggleUser');
  3093. return false;
  3094. }
  3095. }
  3096. async userName2id(name) {
  3097. try {
  3098. const logStatus = scripts_echoLog({
  3099. type: 'gettingTwitterUserId',
  3100. text: name
  3101. });
  3102. const userId = this.#cache[name];
  3103. if (userId) {
  3104. logStatus.success();
  3105. return userId;
  3106. }
  3107. const {
  3108. result,
  3109. statusText,
  3110. status,
  3111. data
  3112. } = await tools_httpRequest({
  3113. url: 'https://x.com/i/api/graphql/mCbpQvZAw6zu_4PvuAUVVQ/UserByScreenName' + `?variables=%7B%22screen_name%22%3A%22${name}%22%2C%22withSafetyModeUserFields%22%3Atrue%2C%22withSuperFollowsUserFields%22%3Atrue%7D`,
  3114. method: 'GET',
  3115. headers: {
  3116. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3117. 'content-type': 'application/json',
  3118. referer: `https://x.com/${name}`,
  3119. 'x-csrf-token': this.#auth.ct0,
  3120. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3121. 'X-Twitter-Active-User': 'yes'
  3122. },
  3123. responseType: 'json'
  3124. });
  3125. if (result === 'Success') {
  3126. if (data?.status === 200) {
  3127. let response = data.response || (typeof data.responseText === 'object' ? data.responseText : null);
  3128. if (!response) {
  3129. try {
  3130. response = JSON.parse(data.responseText);
  3131. } catch (error) {
  3132. response = null;
  3133. }
  3134. }
  3135. const userId = String(response?.data?.user?.result?.rest_id);
  3136. if (userId) {
  3137. this.#setCache(name, userId);
  3138. logStatus.success();
  3139. return userId;
  3140. }
  3141. logStatus.error(`Error:${data.statusText}(${data.status})`);
  3142. return false;
  3143. }
  3144. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3145. return false;
  3146. }
  3147. logStatus.error(`${result}:${statusText}(${status})`);
  3148. return false;
  3149. } catch (error) {
  3150. throwError(error, 'Twitter.getUserId');
  3151. return false;
  3152. }
  3153. }
  3154. async #toggleRetweet({
  3155. retweetId,
  3156. doTask = true
  3157. }) {
  3158. try {
  3159. if (!doTask && this.whiteList.retweets.includes(retweetId)) {
  3160. scripts_echoLog({
  3161. type: 'whiteList',
  3162. text: 'Twitter.unretweet',
  3163. id: retweetId
  3164. });
  3165. return true;
  3166. }
  3167. const logStatus = scripts_echoLog({
  3168. type: `${doTask ? '' : 'un'}retweetting`,
  3169. text: retweetId
  3170. });
  3171. const {
  3172. result,
  3173. statusText,
  3174. status,
  3175. data
  3176. } = await tools_httpRequest({
  3177. url: `https://x.com/i/api/graphql/${doTask ? 'ojPdsZsimiJrUGLR1sjUtA/CreateRetweet' : 'iQtK4dl5hBmXewYZuEOKVw/DeleteRetweet'}`,
  3178. method: 'POST',
  3179. headers: {
  3180. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3181. 'Content-Type': 'application/json',
  3182. 'x-csrf-token': this.#auth.ct0,
  3183. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3184. 'X-Twitter-Active-User': 'yes'
  3185. },
  3186. data: `{"variables":{"tweet_id":"${retweetId}","dark_request":false},"queryId":"${doTask ? 'ojPdsZsimiJrUGLR1sjUtA' : 'iQtK4dl5hBmXewYZuEOKVw'}"}`,
  3187. responseType: 'json'
  3188. });
  3189. if (result === 'Success') {
  3190. if (data?.status === 200 || data?.status === 403 && data.response?.errors?.[0]?.code === 327) {
  3191. logStatus.success();
  3192. if (doTask) {
  3193. this.tasks.retweets = unique([ ...this.tasks.retweets, retweetId ]);
  3194. }
  3195. return true;
  3196. }
  3197. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3198. return false;
  3199. }
  3200. logStatus.error(`${result}:${statusText}(${status})`);
  3201. return false;
  3202. } catch (error) {
  3203. throwError(error, 'Twitter.toggleRetweet');
  3204. return false;
  3205. }
  3206. }
  3207. async toggle({
  3208. doTask = true,
  3209. userLinks = [],
  3210. retweetLinks = []
  3211. }) {
  3212. try {
  3213. if (!this.#initialized) {
  3214. scripts_echoLog({
  3215. text: i18n('needInit')
  3216. });
  3217. return false;
  3218. }
  3219. const prom = [];
  3220. if (doTask && !globalOptions.doTask.twitter.users || !doTask && !globalOptions.undoTask.twitter.users) {
  3221. scripts_echoLog({
  3222. type: 'globalOptionsSkip',
  3223. text: 'twitter.users'
  3224. });
  3225. } else {
  3226. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/x\.com\/(.+)/)?.[1] || link.match(/https:\/\/twitter\.com\/(.+)/)?.[1]);
  3227. if (realUsers.length > 0) {
  3228. for (const user of realUsers) {
  3229. prom.push(this.#toggleUser({
  3230. name: user,
  3231. doTask: doTask
  3232. }));
  3233. await delay(1e3);
  3234. }
  3235. }
  3236. }
  3237. if (doTask && !globalOptions.doTask.twitter.retweets || !doTask && !globalOptions.undoTask.twitter.retweets) {
  3238. scripts_echoLog({
  3239. type: 'globalOptionsSkip',
  3240. text: 'twitter.retweets'
  3241. });
  3242. } else {
  3243. const realRetweets = this.getRealParams('retweets', retweetLinks, doTask, link => link.match(/https:\/\/x\.com\/.*?\/status\/([\d]+)/)?.[1] || link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1]);
  3244. if (realRetweets.length > 0) {
  3245. for (const retweet of realRetweets) {
  3246. prom.push(this.#toggleRetweet({
  3247. retweetId: retweet,
  3248. doTask: doTask
  3249. }));
  3250. await delay(1e3);
  3251. }
  3252. }
  3253. }
  3254. return Promise.all(prom).then(() => true);
  3255. } catch (error) {
  3256. throwError(error, 'Twitter.toggle');
  3257. return false;
  3258. }
  3259. }
  3260. #setCache(name, id) {
  3261. try {
  3262. this.#cache[name] = id;
  3263. GM_setValue('twitterCache', this.#cache);
  3264. } catch (error) {
  3265. throwError(error, 'Twitter.setCache');
  3266. }
  3267. }
  3268. }
  3269. const social_Twitter = Twitter;
  3270. class Vk extends social_Social {
  3271. tasks;
  3272. whiteList;
  3273. #username = '';
  3274. #cache = GM_getValue('vkCache') || {};
  3275. #initialized = false;
  3276. constructor() {
  3277. super();
  3278. const defaultTasksTemplate = {
  3279. names: []
  3280. };
  3281. this.tasks = defaultTasksTemplate;
  3282. this.whiteList = {
  3283. ...defaultTasksTemplate,
  3284. ...GM_getValue('whiteList')?.vk || {}
  3285. };
  3286. }
  3287. async init() {
  3288. try {
  3289. if (this.#initialized) {
  3290. return true;
  3291. }
  3292. const isVerified = await this.#verifyAuth();
  3293. if (isVerified) {
  3294. scripts_echoLog({}).success(i18n('initSuccess', 'Vk'));
  3295. this.#initialized = true;
  3296. return true;
  3297. }
  3298. scripts_echoLog({}).error(i18n('initFailed', 'Vk'));
  3299. return false;
  3300. } catch (error) {
  3301. throwError(error, 'Vk.init');
  3302. return false;
  3303. }
  3304. }
  3305. async #verifyAuth() {
  3306. try {
  3307. const logStatus = scripts_echoLog({
  3308. text: i18n('verifyAuth', 'Vk')
  3309. });
  3310. const {
  3311. result,
  3312. statusText,
  3313. status,
  3314. data
  3315. } = await tools_httpRequest({
  3316. url: 'https://vk.com/im',
  3317. method: 'GET'
  3318. });
  3319. if (result === 'Success') {
  3320. if (data?.finalUrl.includes('vk.com/login')) {
  3321. logStatus.error(`Error:${i18n('loginVk')}`, true);
  3322. return false;
  3323. }
  3324. if (data?.status === 200) {
  3325. this.#username = data.responseText.match(/TopNavBtn__profileLink" href="\/(.*?)"/)?.[1] || '';
  3326. logStatus.success();
  3327. return true;
  3328. }
  3329. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3330. return false;
  3331. }
  3332. logStatus.error(`${result}:${statusText}(${status})`);
  3333. return false;
  3334. } catch (error) {
  3335. throwError(error, 'Vk.verifyAuth');
  3336. return false;
  3337. }
  3338. }
  3339. async #toggleGroup(name, dataParam, doTask = true) {
  3340. try {
  3341. const logStatus = scripts_echoLog({
  3342. type: doTask ? 'joiningVkGroup' : 'leavingVkGroup',
  3343. text: name
  3344. });
  3345. if (dataParam.groupAct === 'enter' && !doTask || dataParam.groupAct === 'leave' && doTask) {
  3346. logStatus.success();
  3347. return true;
  3348. }
  3349. const reqData = {
  3350. act: doTask ? 'enter' : 'leave',
  3351. al: 1,
  3352. gid: dataParam.groupId,
  3353. hash: dataParam.groupHash
  3354. };
  3355. if (doTask) {
  3356. reqData.context = '_';
  3357. }
  3358. const {
  3359. result,
  3360. statusText,
  3361. status,
  3362. data
  3363. } = await tools_httpRequest({
  3364. url: 'https://vk.com/al_groups.php',
  3365. method: 'POST',
  3366. headers: {
  3367. origin: 'https://vk.com',
  3368. referer: `https://vk.com/${name}`,
  3369. 'content-type': 'application/x-www-form-urlencoded'
  3370. },
  3371. data: $.param(reqData)
  3372. });
  3373. if (result === 'Success') {
  3374. if (data?.status === 200) {
  3375. logStatus.success();
  3376. if (doTask) {
  3377. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3378. }
  3379. return true;
  3380. }
  3381. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3382. return false;
  3383. }
  3384. logStatus.error(`${result}:${statusText}(${status})`);
  3385. return false;
  3386. } catch (error) {
  3387. throwError(error, 'Vk.toggleGroup');
  3388. return false;
  3389. }
  3390. }
  3391. async #togglePublic(name, dataParam, doTask = true) {
  3392. try {
  3393. const logStatus = scripts_echoLog({
  3394. type: doTask ? 'joiningVkPublic' : 'leavingVkPublic',
  3395. text: name
  3396. });
  3397. if (dataParam.publicJoined && doTask || !dataParam.publicJoined && !doTask) {
  3398. logStatus.success();
  3399. return true;
  3400. }
  3401. const {
  3402. result,
  3403. statusText,
  3404. status,
  3405. data
  3406. } = await tools_httpRequest({
  3407. url: 'https://vk.com/al_public.php',
  3408. method: 'POST',
  3409. headers: {
  3410. origin: 'https://vk.com',
  3411. referer: `https://vk.com/${name}`,
  3412. 'content-type': 'application/x-www-form-urlencoded'
  3413. },
  3414. data: $.param({
  3415. act: doTask ? 'a_enter' : 'a_leave',
  3416. al: 1,
  3417. pid: dataParam.publicPid,
  3418. hash: dataParam.publicHash
  3419. })
  3420. });
  3421. if (result === 'Success') {
  3422. if (data?.status === 200) {
  3423. logStatus.success();
  3424. if (doTask) {
  3425. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3426. }
  3427. return true;
  3428. }
  3429. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3430. return false;
  3431. }
  3432. logStatus.error(`${result}:${statusText}(${status})`);
  3433. return false;
  3434. } catch (error) {
  3435. throwError(error, 'Vk.togglePublic');
  3436. return false;
  3437. }
  3438. }
  3439. async #sendWall(name) {
  3440. try {
  3441. const logStatus = scripts_echoLog({
  3442. type: 'sendingVkWall',
  3443. text: name
  3444. });
  3445. const {
  3446. result,
  3447. statusText,
  3448. status,
  3449. data
  3450. } = await tools_httpRequest({
  3451. url: 'https://vk.com/like.php',
  3452. method: 'POST',
  3453. headers: {
  3454. origin: 'https://vk.com',
  3455. referer: `https://vk.com/${name}`,
  3456. 'content-type': 'application/x-www-form-urlencoded'
  3457. },
  3458. data: $.param({
  3459. act: 'publish_box',
  3460. al: 1,
  3461. object: name
  3462. })
  3463. });
  3464. if (result === 'Success') {
  3465. if (data?.status === 200) {
  3466. const hash = data.responseText.match(/shHash:[\s]*'(.*?)'/)?.[1];
  3467. if (hash) {
  3468. const {
  3469. result: resultR,
  3470. statusText: statusTextR,
  3471. status: statusR,
  3472. data: dataR
  3473. } = await tools_httpRequest({
  3474. url: 'https://vk.com/like.php',
  3475. method: 'POST',
  3476. headers: {
  3477. origin: 'https://vk.com',
  3478. referer: `https://vk.com/${name}`,
  3479. 'content-type': 'application/x-www-form-urlencoded'
  3480. },
  3481. data: $.param({
  3482. Message: '',
  3483. act: 'a_do_publish',
  3484. al: 1,
  3485. close_comments: 0,
  3486. friends_only: 0,
  3487. from: 'box',
  3488. hash: hash,
  3489. list: '',
  3490. mark_as_ads: 0,
  3491. mute_notifications: 0,
  3492. object: name,
  3493. ret_data: 1,
  3494. to: 0
  3495. })
  3496. });
  3497. if (resultR === 'Success') {
  3498. if (dataR?.status === 200) {
  3499. const jsonData = JSON.parse(dataR.responseText?.replace('\x3c!--', '') || '{}');
  3500. if (jsonData?.payload?.[1]?.[1]?.share_my === true) {
  3501. logStatus.success();
  3502. const postId = String(jsonData?.payload?.[1]?.[1]?.post_id);
  3503. const ownerId = String(jsonData?.payload?.[1]?.[1]?.owner_id);
  3504. if (postId && ownerId) {
  3505. this.#setCache(name, `${ownerId}_${postId}`);
  3506. }
  3507. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3508. return true;
  3509. }
  3510. }
  3511. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  3512. return false;
  3513. }
  3514. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  3515. return false;
  3516. }
  3517. logStatus.error('Error: Get "hash" failed');
  3518. return false;
  3519. }
  3520. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3521. return false;
  3522. }
  3523. logStatus.error(`${result}:${statusText}(${status})`);
  3524. return false;
  3525. } catch (error) {
  3526. throwError(error, 'Vk.sendWall');
  3527. return false;
  3528. }
  3529. }
  3530. async #deleteWall(name, dataParams) {
  3531. try {
  3532. const logStatus = scripts_echoLog({
  3533. type: 'deletingVkWall',
  3534. text: name
  3535. });
  3536. const {
  3537. result,
  3538. statusText,
  3539. status,
  3540. data
  3541. } = await tools_httpRequest({
  3542. url: 'https://vk.com/al_wall.php?act=delete',
  3543. method: 'POST',
  3544. headers: {
  3545. origin: 'https://vk.com',
  3546. referer: `https://vk.com/${this.#username}?w=wall${this.#cache[name]}%2Fall`,
  3547. 'content-type': 'application/x-www-form-urlencoded'
  3548. },
  3549. data: $.param({
  3550. act: 'delete',
  3551. al: 1,
  3552. confirm: 0,
  3553. from: 'wkview',
  3554. hash: dataParams.wallHash,
  3555. post: this.#cache[name]
  3556. })
  3557. });
  3558. if (result === 'Success') {
  3559. if (data?.status === 200) {
  3560. const jsonData = JSON.parse(data.responseText?.replace('\x3c!--', '') || '{}');
  3561. if (jsonData?.payload?.[1]?.[1]) {
  3562. logStatus.success();
  3563. return true;
  3564. }
  3565. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3566. return false;
  3567. }
  3568. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3569. return false;
  3570. }
  3571. logStatus.error(`${result}:${statusText}(${status})`);
  3572. return false;
  3573. } catch (error) {
  3574. throwError(error, 'Vk.deleteWall');
  3575. return false;
  3576. }
  3577. }
  3578. async #getId(name, doTask) {
  3579. try {
  3580. let url = `https://vk.com/${name}`;
  3581. if (/^wall-/.test(name)) {
  3582. if (doTask) {
  3583. return {
  3584. type: 'sendWall'
  3585. };
  3586. }
  3587. if (!this.#cache[name]) {
  3588. return {
  3589. type: 'unSupport'
  3590. };
  3591. }
  3592. url = `https://vk.com/${this.#username}?w=wall${this.#cache[name]}`;
  3593. }
  3594. const logStatus = scripts_echoLog({
  3595. type: 'gettingVkId',
  3596. text: name
  3597. });
  3598. const {
  3599. result,
  3600. statusText,
  3601. status,
  3602. data
  3603. } = await tools_httpRequest({
  3604. url: url,
  3605. method: 'GET'
  3606. });
  3607. if (result === 'Success') {
  3608. if (data?.status === 200) {
  3609. const [ , groupAct, groupId, , groupHash ] = data.responseText.match(/Groups.(enter|leave)\(.*?,.*?([\d]+?), (&#39;|')(.*?)(&#39;|')/) || [];
  3610. const publicHash = data.responseText.match(/"enterHash":"(.*?)"/)?.[1];
  3611. const publicPid = data.responseText.match(/"public_id":([\d]+?),/)?.[1];
  3612. const publicJoined = !data.responseText.includes('Public.subscribe');
  3613. if (groupAct && groupId && groupHash) {
  3614. logStatus.success();
  3615. return {
  3616. groupAct: groupAct,
  3617. groupId: groupId,
  3618. groupHash: groupHash,
  3619. type: 'group'
  3620. };
  3621. } else if (publicHash && publicPid) {
  3622. logStatus.success();
  3623. return {
  3624. publicHash: publicHash,
  3625. publicPid: publicPid,
  3626. publicJoined: publicJoined,
  3627. type: 'public'
  3628. };
  3629. } else if (data.responseText.includes('wall.deletePost') && !doTask) {
  3630. const wallHash = data.responseText.match(/wall\.deletePost\(this, '.*?', '(.*?)'\)/)?.[1];
  3631. if (wallHash) {
  3632. logStatus.success();
  3633. return {
  3634. type: 'deleteWall',
  3635. wallHash: wallHash
  3636. };
  3637. }
  3638. } else if (name.includes('wall') && doTask) {
  3639. logStatus.success();
  3640. return {
  3641. type: 'sendWall'
  3642. };
  3643. }
  3644. logStatus.error('Error: Parameters not found!');
  3645. return false;
  3646. }
  3647. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3648. return false;
  3649. }
  3650. logStatus.error(`${result}:${statusText}(${status})`);
  3651. return false;
  3652. } catch (error) {
  3653. throwError(error, 'Vk.getId');
  3654. return false;
  3655. }
  3656. }
  3657. async #toggleVk({
  3658. name,
  3659. doTask = true
  3660. }) {
  3661. try {
  3662. if (!doTask && this.whiteList.names.includes(name)) {
  3663. scripts_echoLog({
  3664. type: 'whiteList',
  3665. text: 'Vk.undoTask',
  3666. id: name
  3667. });
  3668. return true;
  3669. }
  3670. const formatName = name.replace(/\/$/, '');
  3671. const data = await this.#getId(formatName, doTask);
  3672. if (!data) {
  3673. return false;
  3674. }
  3675. switch (data.type) {
  3676. case 'group':
  3677. return await this.#toggleGroup(formatName, data, doTask);
  3678.  
  3679. case 'public':
  3680. return await this.#togglePublic(formatName, data, doTask);
  3681.  
  3682. case 'sendWall':
  3683. return doTask ? await this.#sendWall(formatName) : true;
  3684.  
  3685. case 'deleteWall':
  3686. return doTask ? true : await this.#deleteWall(formatName, data);
  3687.  
  3688. default:
  3689. return false;
  3690. }
  3691. } catch (error) {
  3692. throwError(error, 'Vk.toggleVk');
  3693. return false;
  3694. }
  3695. }
  3696. async toggle({
  3697. doTask = true,
  3698. nameLinks = []
  3699. }) {
  3700. try {
  3701. if (!this.#initialized) {
  3702. scripts_echoLog({
  3703. text: i18n('needInit')
  3704. });
  3705. return false;
  3706. }
  3707. const prom = [];
  3708. if (doTask && !globalOptions.doTask.vk.names || !doTask && !globalOptions.undoTask.vk.names) {
  3709. scripts_echoLog({
  3710. type: 'globalOptionsSkip',
  3711. text: 'vk.names'
  3712. });
  3713. } else {
  3714. const realNames = this.getRealParams('names', nameLinks, doTask, link => link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1]);
  3715. if (realNames.length > 0) {
  3716. for (const name of realNames) {
  3717. prom.push(this.#toggleVk({
  3718. name: name,
  3719. doTask: doTask
  3720. }));
  3721. await delay(1e3);
  3722. }
  3723. }
  3724. }
  3725. return Promise.all(prom).then(() => true);
  3726. } catch (error) {
  3727. throwError(error, 'Vk.toggle');
  3728. return false;
  3729. }
  3730. }
  3731. #setCache(name, postId) {
  3732. try {
  3733. this.#cache[name] = postId;
  3734. GM_setValue('vkCache', this.#cache);
  3735. } catch (error) {
  3736. throwError(error, 'Vk.setCache');
  3737. }
  3738. }
  3739. }
  3740. const social_Vk = Vk;
  3741. const getInfo = async function(link, type) {
  3742. try {
  3743. const logStatus = scripts_echoLog({
  3744. text: i18n('gettingYtbToken')
  3745. });
  3746. const {
  3747. result,
  3748. statusText,
  3749. status,
  3750. data
  3751. } = await tools_httpRequest({
  3752. url: link,
  3753. method: 'GET'
  3754. });
  3755. if (result === 'Success') {
  3756. if (data?.status === 200) {
  3757. if (data.responseText.includes('accounts.google.com/ServiceLogin?service=youtube')) {
  3758. logStatus.error(`Error:${i18n('loginYtb')}`, true);
  3759. return {
  3760. needLogin: true
  3761. };
  3762. }
  3763. const apiKey = data.responseText.match(/"INNERTUBE_API_KEY":"(.*?)"/)?.[1];
  3764. const context = (data.responseText.match(/\(\{"INNERTUBE_CONTEXT":([\w\W]*?)\}\)/) || data.responseText.match(/"INNERTUBE_CONTEXT":([\w\W]*?\}),"INNERTUBE/))?.[1] || '{}';
  3765. const {
  3766. client,
  3767. request
  3768. } = JSON.parse(context);
  3769. if (apiKey && client && request) {
  3770. client.hl = 'en';
  3771. if (type === 'channel') {
  3772. const channelId = data.responseText.match(/"channelId":"(.+?)"/)?.[1];
  3773. if (channelId) {
  3774. logStatus.success();
  3775. return {
  3776. params: {
  3777. apiKey: apiKey,
  3778. client: client,
  3779. request: request,
  3780. channelId: channelId
  3781. }
  3782. };
  3783. }
  3784. logStatus.error('Error: Get "channelId" failed!');
  3785. return {};
  3786. } else if (type === 'likeVideo') {
  3787. const videoId = data.responseText.match(/<link rel="shortlinkUrl" href="https:\/\/youtu\.be\/(.*?)">/)?.[1];
  3788. const likeParams = data.responseText.match(/"likeParams":"(.*?)"/)?.[1];
  3789. if (videoId) {
  3790. logStatus.success();
  3791. return {
  3792. params: {
  3793. apiKey: apiKey,
  3794. client: client,
  3795. request: request,
  3796. videoId: videoId,
  3797. likeParams: likeParams
  3798. }
  3799. };
  3800. }
  3801. logStatus.error('Error: Get "videoId" failed!');
  3802. return {};
  3803. }
  3804. logStatus.error('Error: Unknown type');
  3805. return {};
  3806. }
  3807. logStatus.error('Error: Parameter "apiKey" not found!');
  3808. return {};
  3809. }
  3810. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3811. return {};
  3812. }
  3813. logStatus.error(`${result}:${statusText}(${status})`);
  3814. return {};
  3815. } catch (error) {
  3816. throwError(error, 'Youtube.getInfo');
  3817. return {};
  3818. }
  3819. };
  3820. class Youtube extends social_Social {
  3821. tasks;
  3822. whiteList;
  3823. #auth = GM_getValue('youtubeAuth') || {};
  3824. #initialized = false;
  3825. #verifyChannel = `https://www.youtube.com/channel/${globalOptions.other.youtubeVerifyChannel}`;
  3826. constructor() {
  3827. super();
  3828. const defaultTasksTemplate = {
  3829. channels: [],
  3830. likes: []
  3831. };
  3832. this.tasks = defaultTasksTemplate;
  3833. this.whiteList = {
  3834. ...defaultTasksTemplate,
  3835. ...GM_getValue('whiteList')?.youtube || {}
  3836. };
  3837. }
  3838. async init() {
  3839. try {
  3840. if (this.#initialized) {
  3841. return true;
  3842. }
  3843. if (!this.#auth.PAPISID) {
  3844. if (await this.#updateAuth()) {
  3845. this.#initialized = true;
  3846. return true;
  3847. }
  3848. return false;
  3849. }
  3850. const isVerified = await this.#verifyAuth();
  3851. if (isVerified) {
  3852. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  3853. this.#initialized = true;
  3854. return true;
  3855. }
  3856. GM_setValue('youtubeAuth', null);
  3857. if (await this.#updateAuth()) {
  3858. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  3859. this.#initialized = true;
  3860. return true;
  3861. }
  3862. scripts_echoLog({}).error(i18n('initFailed', 'Youtube'));
  3863. return false;
  3864. } catch (error) {
  3865. throwError(error, 'Youtube.init');
  3866. return false;
  3867. }
  3868. }
  3869. async #verifyAuth() {
  3870. try {
  3871. return await this.#toggleChannel({
  3872. link: this.#verifyChannel,
  3873. doTask: true,
  3874. verify: true
  3875. });
  3876. } catch (error) {
  3877. throwError(error, 'Youtube.verifyAuth');
  3878. return false;
  3879. }
  3880. }
  3881. async #updateAuth() {
  3882. try {
  3883. const logStatus = scripts_echoLog({
  3884. text: i18n('updatingAuth', 'Youtube')
  3885. });
  3886. return await new Promise(resolve => {
  3887. GM_cookie.list({
  3888. url: 'https://www.youtube.com/@YouTube'
  3889. }, async (cookies, error) => {
  3890. if (!error) {
  3891. const PAPISID = cookies.find(cookie => cookie.name === '__Secure-3PAPISID')?.value;
  3892. if (PAPISID) {
  3893. GM_setValue('youtubeAuth', {
  3894. PAPISID: PAPISID
  3895. });
  3896. this.#auth = {
  3897. PAPISID: PAPISID
  3898. };
  3899. logStatus.success();
  3900. resolve(await this.#verifyAuth());
  3901. } else {
  3902. logStatus.error(i18n('needLogin'));
  3903. resolve(false);
  3904. }
  3905. } else {
  3906. logStatus.error('Error: Update youtube auth failed!');
  3907. resolve(false);
  3908. }
  3909. });
  3910. });
  3911. } catch (error) {
  3912. throwError(error, 'Youtube.updateAuth');
  3913. return false;
  3914. }
  3915. }
  3916. #getInfo(link, type) {
  3917. return getInfo(link, type);
  3918. }
  3919. async #toggleChannel({
  3920. link,
  3921. doTask = true,
  3922. verify = false
  3923. }) {
  3924. try {
  3925. const {
  3926. params,
  3927. needLogin
  3928. } = await this.#getInfo(link, 'channel');
  3929. const {
  3930. apiKey,
  3931. client,
  3932. request,
  3933. channelId
  3934. } = params || {};
  3935. if (needLogin) {
  3936. scripts_echoLog({
  3937. html: i18n('loginYtb')
  3938. });
  3939. return false;
  3940. }
  3941. if (!(apiKey && client && request && channelId)) {
  3942. scripts_echoLog({
  3943. text: '"getYtbToken" failed'
  3944. });
  3945. return false;
  3946. }
  3947. if (!doTask && !verify && this.whiteList.channels.includes(channelId)) {
  3948. scripts_echoLog({
  3949. type: 'whiteList',
  3950. text: 'Youtube.unfollowChannel',
  3951. id: channelId
  3952. });
  3953. return true;
  3954. }
  3955. const logStatus = verify ? scripts_echoLog({
  3956. text: i18n('verifyingAuth', 'Youtube')
  3957. }) : scripts_echoLog({
  3958. type: doTask ? 'followingYtbChannel' : 'unfollowingYtbChannel',
  3959. text: channelId
  3960. });
  3961. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  3962. const {
  3963. result,
  3964. statusText,
  3965. status,
  3966. data
  3967. } = await tools_httpRequest({
  3968. url: `https://www.youtube.com/youtubei/v1/subscription/${doTask ? '' : 'un'}subscribe?key=${apiKey}&prettyPrint=false`,
  3969. method: 'POST',
  3970. headers: {
  3971. origin: 'https://www.youtube.com',
  3972. referer: `https://www.youtube.com/channel/${channelId}`,
  3973. 'content-type': 'application/json',
  3974. 'x-goog-authuser': '0',
  3975. 'x-goog-visitor-id': client?.visitorData,
  3976. 'x-origin': 'https://www.youtube.com',
  3977. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  3978. },
  3979. data: JSON.stringify({
  3980. context: {
  3981. client: client,
  3982. request: {
  3983. sessionId: request?.sessionId,
  3984. internalExperimentFlags: [],
  3985. consistencyTokenJars: []
  3986. },
  3987. user: {}
  3988. },
  3989. channelIds: [ channelId ],
  3990. params: doTask ? 'EgIIAhgA' : 'CgIIAhgA'
  3991. })
  3992. });
  3993. if (result === 'Success') {
  3994. if (data?.status === 200) {
  3995. if (doTask && (/"subscribed":true/.test(data.responseText) || data.responseText.includes('The subscription already exists')) || !doTask && /"subscribed":false/.test(data.responseText)) {
  3996. logStatus.success();
  3997. if (doTask && !verify) {
  3998. this.tasks.channels = unique([ ...this.tasks.channels, link ]);
  3999. }
  4000. return true;
  4001. }
  4002. if (verify && data.responseText.includes('You may not subscribe to yourself')) {
  4003. logStatus.success();
  4004. return true;
  4005. }
  4006. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4007. return false;
  4008. }
  4009. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4010. return false;
  4011. }
  4012. logStatus.error(`${result}:${statusText}(${status})`);
  4013. return false;
  4014. } catch (error) {
  4015. throwError(error, 'Youtube.toggleChannel');
  4016. return false;
  4017. }
  4018. }
  4019. async #toggleLikeVideo({
  4020. link,
  4021. doTask = true
  4022. }) {
  4023. try {
  4024. const {
  4025. params,
  4026. needLogin
  4027. } = await this.#getInfo(link, 'likeVideo');
  4028. const {
  4029. apiKey,
  4030. client,
  4031. request,
  4032. videoId,
  4033. likeParams
  4034. } = params || {};
  4035. if (needLogin) {
  4036. scripts_echoLog({
  4037. html: `${i18n('loginYtb')}`
  4038. });
  4039. return false;
  4040. }
  4041. if (!(apiKey && client && request && videoId && likeParams)) {
  4042. scripts_echoLog({
  4043. text: '"getYtbToken" failed'
  4044. });
  4045. return false;
  4046. }
  4047. if (!doTask && this.whiteList.likes.includes(videoId)) {
  4048. scripts_echoLog({
  4049. type: 'whiteList',
  4050. text: 'Youtube.unlikeVideo',
  4051. id: videoId
  4052. });
  4053. return true;
  4054. }
  4055. const logStatus = scripts_echoLog({
  4056. type: doTask ? 'likingYtbVideo' : 'unlikingYtbVideo',
  4057. text: videoId
  4058. });
  4059. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  4060. const likeVideoData = {
  4061. context: {
  4062. client: client,
  4063. request: {
  4064. sessionId: request.sessionId,
  4065. internalExperimentFlags: [],
  4066. consistencyTokenJars: []
  4067. },
  4068. user: {}
  4069. },
  4070. target: {
  4071. videoId: videoId
  4072. }
  4073. };
  4074. if (doTask) {
  4075. if (likeParams) {
  4076. likeVideoData.params = likeParams;
  4077. } else {
  4078. logStatus.error('Empty likeParams');
  4079. return false;
  4080. }
  4081. }
  4082. const {
  4083. result,
  4084. statusText,
  4085. status,
  4086. data
  4087. } = await tools_httpRequest({
  4088. url: `https://www.youtube.com/youtubei/v1/like/${doTask ? '' : 'remove'}like?key=${apiKey}`,
  4089. method: 'POST',
  4090. headers: {
  4091. origin: 'https://www.youtube.com',
  4092. referer: `https://www.youtube.com/watch?v=${videoId}`,
  4093. 'content-type': 'application/json',
  4094. 'x-goog-authuser': '0',
  4095. 'x-goog-visitor-id': client.visitorData,
  4096. 'x-origin': 'https://www.youtube.com',
  4097. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  4098. },
  4099. data: JSON.stringify(likeVideoData)
  4100. });
  4101. if (result === 'Success') {
  4102. if (data?.status === 200) {
  4103. if (doTask && data.responseText.includes('Added to Liked videos') || !doTask && (data.responseText.includes('Removed from Liked videos') || data.responseText.includes('Dislike removed'))) {
  4104. logStatus.success();
  4105. if (doTask) {
  4106. this.tasks.likes = unique([ ...this.tasks.likes, link ]);
  4107. }
  4108. return true;
  4109. }
  4110. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4111. return false;
  4112. }
  4113. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4114. return false;
  4115. }
  4116. logStatus.error(`${result}:${statusText}(${status})`);
  4117. return false;
  4118. } catch (error) {
  4119. throwError(error, 'Youtube.toggleLikeVideo');
  4120. return false;
  4121. }
  4122. }
  4123. async toggle({
  4124. doTask = true,
  4125. channelLinks = [],
  4126. videoLinks = []
  4127. }) {
  4128. try {
  4129. if (!this.#initialized) {
  4130. scripts_echoLog({
  4131. text: i18n('needInit')
  4132. });
  4133. return false;
  4134. }
  4135. const prom = [];
  4136. if (doTask && !globalOptions.doTask.youtube.channels || !doTask && !globalOptions.undoTask.youtube.channels) {
  4137. scripts_echoLog({
  4138. type: 'globalOptionsSkip',
  4139. text: 'youtube.channels'
  4140. });
  4141. } else {
  4142. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => {
  4143. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4144. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4145. }
  4146. return link;
  4147. });
  4148. if (realChannels.length > 0) {
  4149. for (const channel of realChannels) {
  4150. prom.push(this.#toggleChannel({
  4151. link: channel,
  4152. doTask: doTask
  4153. }));
  4154. await delay(1e3);
  4155. }
  4156. }
  4157. }
  4158. if (doTask && !globalOptions.doTask.youtube.likes || !doTask && !globalOptions.undoTask.youtube.likes) {
  4159. scripts_echoLog({
  4160. type: 'globalOptionsSkip',
  4161. text: 'youtube.likes'
  4162. });
  4163. } else {
  4164. const realLikes = this.getRealParams('likes', videoLinks, doTask, link => {
  4165. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4166. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4167. }
  4168. return link;
  4169. });
  4170. if (realLikes.length > 0) {
  4171. for (const video of realLikes) {
  4172. prom.push(this.#toggleLikeVideo({
  4173. link: video,
  4174. doTask: doTask
  4175. }));
  4176. await delay(1e3);
  4177. }
  4178. }
  4179. }
  4180. return Promise.all(prom).then(() => true);
  4181. } catch (error) {
  4182. throwError(error, 'Youtube.toggle');
  4183. return false;
  4184. }
  4185. }
  4186. }
  4187. class SteamASF {
  4188. #asfOptions;
  4189. #botName = 'asf';
  4190. #groupInfo;
  4191. async init() {
  4192. try {
  4193. const asfCommandsUrl = new URL('/Api/Command/', globalOptions.ASF.AsfIpcUrl);
  4194. this.#asfOptions = {
  4195. url: asfCommandsUrl.href,
  4196. method: 'POST',
  4197. responseType: 'json',
  4198. headers: {
  4199. accept: 'application/json',
  4200. 'Content-Type': 'application/json',
  4201. Host: asfCommandsUrl.host,
  4202. Origin: asfCommandsUrl.origin,
  4203. Referer: asfCommandsUrl.href,
  4204. Authentication: globalOptions.ASF.AsfIpcPassword
  4205. }
  4206. };
  4207. if (globalOptions.ASF.AsfBotname) {
  4208. this.#botName = globalOptions.ASF.AsfBotname;
  4209. }
  4210. const logStatus = scripts_echoLog({
  4211. text: i18n('initingASF')
  4212. });
  4213. const {
  4214. result,
  4215. statusText,
  4216. status,
  4217. data
  4218. } = await tools_httpRequest({
  4219. ...this.#asfOptions,
  4220. data: '{"Command":"!stats"}'
  4221. });
  4222. if (result === 'Success') {
  4223. if (data?.response?.Success === true && data.response.Message === 'OK' && data.response.Result) {
  4224. logStatus.success();
  4225. return true;
  4226. }
  4227. if (data?.response?.Result || data?.response?.Message) {
  4228. logStatus.error(data?.response?.Result || data.response.Message);
  4229. return false;
  4230. }
  4231. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4232. return false;
  4233. }
  4234. logStatus.error(`${result}:${statusText}(${status})`);
  4235. return false;
  4236. } catch (error) {
  4237. throwError(error, 'SteamASF.init');
  4238. return false;
  4239. }
  4240. }
  4241. async joinGroup(groupName) {
  4242. try {
  4243. const logStatus = scripts_echoLog({
  4244. type: 'joiningSteamGroup',
  4245. text: groupName
  4246. });
  4247. const {
  4248. result,
  4249. statusText,
  4250. status,
  4251. data
  4252. } = await tools_httpRequest({
  4253. ...this.#asfOptions,
  4254. data: JSON.stringify({
  4255. Command: `!JOINGROUP ${this.#botName} ${groupName}`
  4256. })
  4257. });
  4258. if (result === 'Success') {
  4259. if (data?.status === 200 && [ '已加入', '已申请', 'Joined', 'Applied', 'Присоединился', 'costs' ].find(text => data.response?.Result?.includes(text))) {
  4260. logStatus.success();
  4261. return true;
  4262. }
  4263. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4264. return false;
  4265. }
  4266. logStatus.error(`${result}:${statusText}(${status})`);
  4267. return false;
  4268. } catch (error) {
  4269. throwError(error, 'SteamASF.joinGroup');
  4270. return false;
  4271. }
  4272. }
  4273. async leaveGroup(groupName) {
  4274. try {
  4275. if (!this.#groupInfo) {
  4276. if (!await this.#getGroupId()) {
  4277. return false;
  4278. }
  4279. }
  4280. const groupId = await this.#groupInfo[groupName];
  4281. if (!groupId) {
  4282. return false;
  4283. }
  4284. const logStatus = scripts_echoLog({
  4285. type: 'leavingSteamGroup',
  4286. text: groupName
  4287. });
  4288. const {
  4289. result,
  4290. statusText,
  4291. status,
  4292. data
  4293. } = await tools_httpRequest({
  4294. ...this.#asfOptions,
  4295. data: JSON.stringify({
  4296. Command: `!LEAVEGROUP ${this.#botName} ${groupId}`
  4297. })
  4298. });
  4299. if (result === 'Success') {
  4300. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4301. logStatus.success();
  4302. return true;
  4303. }
  4304. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4305. return false;
  4306. }
  4307. logStatus.error(`${result}:${statusText}(${status})`);
  4308. return false;
  4309. } catch (error) {
  4310. throwError(error, 'SteamASF.leaveGroup');
  4311. return false;
  4312. }
  4313. }
  4314. async #getGroupId() {
  4315. try {
  4316. const logStatus = scripts_echoLog({
  4317. type: 'gettingSteamGroupId',
  4318. text: 'All'
  4319. });
  4320. const {
  4321. result,
  4322. statusText,
  4323. status,
  4324. data
  4325. } = await tools_httpRequest({
  4326. ...this.#asfOptions,
  4327. data: JSON.stringify({
  4328. Command: `!GROUPLIST ${this.#botName}`
  4329. })
  4330. });
  4331. if (result === 'Success') {
  4332. if (data?.status === 200 && data.response?.Result?.includes('|')) {
  4333. this.#groupInfo = Object.fromEntries(data.response.Result.split('\n').map(line => {
  4334. const [ , name, id ] = line.trim().split('|');
  4335. if (name && id) {
  4336. return [ name, id ];
  4337. }
  4338. return null;
  4339. }).filter(ele => ele));
  4340. logStatus.success();
  4341. return true;
  4342. }
  4343. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4344. return false;
  4345. }
  4346. logStatus.error(`${result}:${statusText}(${status})`);
  4347. return false;
  4348. } catch (error) {
  4349. throwError(error, 'SteamASF.getGroupID');
  4350. return false;
  4351. }
  4352. }
  4353. async addToWishlist(gameId) {
  4354. try {
  4355. const logStatus = scripts_echoLog({
  4356. type: 'addingToWishlist',
  4357. text: gameId
  4358. });
  4359. if ((await this.#checkGame(gameId)).wishlist === true) {
  4360. logStatus.success();
  4361. return true;
  4362. }
  4363. const {
  4364. result,
  4365. statusText,
  4366. status,
  4367. data
  4368. } = await tools_httpRequest({
  4369. ...this.#asfOptions,
  4370. data: JSON.stringify({
  4371. Command: `!ADDWISHLIST ${this.#botName} ${gameId}`
  4372. })
  4373. });
  4374. if (result === 'Success') {
  4375. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4376. logStatus.success();
  4377. return true;
  4378. }
  4379. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4380. return false;
  4381. }
  4382. logStatus.error(`${result}:${statusText}(${status})`);
  4383. return false;
  4384. } catch (error) {
  4385. throwError(error, 'SteamASF.addToWishlist');
  4386. return false;
  4387. }
  4388. }
  4389. async removeFromWishlist(gameId) {
  4390. try {
  4391. const logStatus = scripts_echoLog({
  4392. type: 'removingFromWishlist',
  4393. text: gameId
  4394. });
  4395. if ((await this.#checkGame(gameId)).wishlist === false) {
  4396. logStatus.success();
  4397. return true;
  4398. }
  4399. const {
  4400. result,
  4401. statusText,
  4402. status,
  4403. data
  4404. } = await tools_httpRequest({
  4405. ...this.#asfOptions,
  4406. data: JSON.stringify({
  4407. Command: `!REMOVEWISHLIST ${this.#botName} ${gameId}`
  4408. })
  4409. });
  4410. if (result === 'Success') {
  4411. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4412. logStatus.success();
  4413. return true;
  4414. }
  4415. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4416. return false;
  4417. }
  4418. logStatus.error(`${result}:${statusText}(${status})`);
  4419. return false;
  4420. } catch (error) {
  4421. throwError(error, 'SteamASF.removeFromWishlist');
  4422. return false;
  4423. }
  4424. }
  4425. async toggleFollowGame(gameId, doTask) {
  4426. try {
  4427. const logStatus = scripts_echoLog({
  4428. type: `${doTask ? '' : 'un'}followingGame`,
  4429. text: gameId
  4430. });
  4431. if (doTask && (await this.#checkGame(gameId)).followed === true || !doTask && (await this.#checkGame(gameId)).followed === false) {
  4432. logStatus.success();
  4433. return true;
  4434. }
  4435. const {
  4436. result,
  4437. statusText,
  4438. status,
  4439. data
  4440. } = await tools_httpRequest({
  4441. ...this.#asfOptions,
  4442. data: JSON.stringify({
  4443. Command: `!${doTask ? '' : 'UN'}FOLLOWGAME ${this.#botName} ${gameId}`
  4444. })
  4445. });
  4446. if (result === 'Success') {
  4447. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4448. logStatus.success();
  4449. return true;
  4450. }
  4451. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4452. return false;
  4453. }
  4454. logStatus.error(`${result}:${statusText}(${status})`);
  4455. return false;
  4456. } catch (error) {
  4457. throwError(error, 'SteamASF.toggleFollowGame');
  4458. return false;
  4459. }
  4460. }
  4461. async #checkGame(gameId) {
  4462. try {
  4463. const {
  4464. result,
  4465. data
  4466. } = await tools_httpRequest({
  4467. ...this.#asfOptions,
  4468. data: JSON.stringify({
  4469. Command: `!CHECK ${this.#botName} ${gameId}`
  4470. })
  4471. });
  4472. if (result === 'Success') {
  4473. if (data?.status === 200 && data.response?.Result?.includes(gameId)) {
  4474. const matchedResult = data.response.Result.split('\n').find(result => result.includes(gameId))?.split('|');
  4475. if (matchedResult?.length > 3) {
  4476. return {
  4477. wishlist: matchedResult.at(-3).trim() === '√' || matchedResult.at(-2).trim() === '√',
  4478. followed: matchedResult.at(-1).trim() === '√'
  4479. };
  4480. }
  4481. return {};
  4482. }
  4483. return {};
  4484. }
  4485. return {};
  4486. } catch (error) {
  4487. throwError(error, 'SteamASF.checkGame');
  4488. return {};
  4489. }
  4490. }
  4491. async toggleCurator(curatorId, doTask = true) {
  4492. try {
  4493. const logStatus = scripts_echoLog({
  4494. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  4495. text: curatorId
  4496. });
  4497. const {
  4498. result,
  4499. statusText,
  4500. status,
  4501. data
  4502. } = await tools_httpRequest({
  4503. ...this.#asfOptions,
  4504. data: JSON.stringify({
  4505. Command: `!${doTask ? '' : 'UN'}FOLLOWCURATOR ${this.#botName} ${curatorId}`
  4506. })
  4507. });
  4508. if (result === 'Success') {
  4509. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4510. logStatus.success();
  4511. return true;
  4512. }
  4513. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4514. return false;
  4515. }
  4516. logStatus.error(`${result}:${statusText}(${status})`);
  4517. return false;
  4518. } catch (error) {
  4519. throwError(error, 'Steam.toggleCurator');
  4520. return false;
  4521. }
  4522. }
  4523. async addLicense(id) {
  4524. try {
  4525. const [ type, ids ] = id.split('-');
  4526. if (type === 'appid') {
  4527. const logStatus = scripts_echoLog({
  4528. type: 'addingFreeLicense',
  4529. text: ids
  4530. });
  4531. const {
  4532. result,
  4533. statusText,
  4534. status,
  4535. data
  4536. } = await tools_httpRequest({
  4537. ...this.#asfOptions,
  4538. data: JSON.stringify({
  4539. Command: `!addlicense ${this.#botName} app/${ids}`
  4540. })
  4541. });
  4542. if (result === 'Success') {
  4543. if (data?.status === 200 && [ 'AlreadyPurchased', 'OK' ].find(text => data.response?.Result?.includes(text))) {
  4544. logStatus.success();
  4545. return true;
  4546. }
  4547. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4548. return false;
  4549. }
  4550. logStatus.error(`${result}:${statusText}(${status})`);
  4551. return false;
  4552. } else if (type === 'subid') {
  4553. const idsArr = ids.split(',');
  4554. const logStatus = scripts_echoLog({
  4555. type: 'addingFreeLicenseSubid',
  4556. text: ids
  4557. });
  4558. const {
  4559. result,
  4560. statusText,
  4561. status,
  4562. data
  4563. } = await tools_httpRequest({
  4564. ...this.#asfOptions,
  4565. data: JSON.stringify({
  4566. Command: `!addlicense ${this.#botName} ${idsArr.map(id => `sub/${id}`).join(',')}`
  4567. })
  4568. });
  4569. if (result === 'Success') {
  4570. if (data?.status === 200 && data.response?.Result) {
  4571. const resultLines = data.response.Result.split('\n');
  4572. idsArr.forEach(subid => {
  4573. const targetLine = resultLines.find(text => text.includes(subid));
  4574. if (targetLine && [ '成功', 'Success', 'Успех' ].find(text => targetLine.includes(text))) {
  4575. scripts_echoLog({}).success(targetLine);
  4576. } else {
  4577. scripts_echoLog({}).error(targetLine);
  4578. }
  4579. });
  4580. return true;
  4581. }
  4582. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4583. return false;
  4584. }
  4585. logStatus.error(`${result}:${statusText}(${status})`);
  4586. return false;
  4587. }
  4588. return false;
  4589. } catch (error) {
  4590. throwError(error, 'SteamASF.addLicense');
  4591. return false;
  4592. }
  4593. }
  4594. async requestPlayTestAccess(id) {
  4595. try {
  4596. const logStatus = scripts_echoLog({
  4597. type: 'requestingPlayTestAccess',
  4598. text: id
  4599. });
  4600. const {
  4601. result,
  4602. statusText,
  4603. status,
  4604. data
  4605. } = await tools_httpRequest({
  4606. ...this.#asfOptions,
  4607. data: JSON.stringify({
  4608. Command: `!REQUESTACCESS ${this.#botName} ${id}`
  4609. })
  4610. });
  4611. if (result === 'Success') {
  4612. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4613. logStatus.success();
  4614. return true;
  4615. }
  4616. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4617. return false;
  4618. }
  4619. logStatus.error(`${result}:${statusText}(${status})`);
  4620. return false;
  4621. } catch (error) {
  4622. throwError(error, 'Steam.requestPlayTestAccess');
  4623. return false;
  4624. }
  4625. }
  4626. }
  4627. const social_SteamASF = SteamASF;
  4628. class Steam extends social_Social {
  4629. tasks;
  4630. whiteList;
  4631. #cache = {
  4632. ...{
  4633. group: {},
  4634. officialGroup: {},
  4635. forum: {},
  4636. workshop: {},
  4637. curator: {}
  4638. },
  4639. ...GM_getValue('steamCache')
  4640. };
  4641. #auth = {};
  4642. #storeInitialized = false;
  4643. #communityInitialized = false;
  4644. #area = 'CN';
  4645. #oldArea;
  4646. #areaStatus = 'end';
  4647. #ASF;
  4648. constructor() {
  4649. super();
  4650. const defaultTasksTemplate = {
  4651. groups: [],
  4652. officialGroups: [],
  4653. wishlists: [],
  4654. follows: [],
  4655. forums: [],
  4656. workshops: [],
  4657. workshopVotes: [],
  4658. curators: [],
  4659. curatorLikes: [],
  4660. announcements: [],
  4661. licenses: [],
  4662. playtests: []
  4663. };
  4664. this.tasks = defaultTasksTemplate;
  4665. this.whiteList = {
  4666. ...defaultTasksTemplate,
  4667. ...GM_getValue('whiteList')?.steam || {}
  4668. };
  4669. }
  4670. async init(type = 'all') {
  4671. try {
  4672. if (globalOptions.ASF.AsfEnabled && globalOptions.ASF.AsfIpcUrl && globalOptions.ASF.AsfIpcPassword) {
  4673. this.#ASF = new social_SteamASF();
  4674. if (await this.#ASF.init()) {
  4675. this.#storeInitialized = true;
  4676. this.#communityInitialized = true;
  4677. return true;
  4678. }
  4679. return false;
  4680. }
  4681. if (type === 'store') {
  4682. if (this.#storeInitialized) {
  4683. return true;
  4684. }
  4685. let storeInitialized = await this.#updateStoreAuth();
  4686. if (!storeInitialized) {
  4687. storeInitialized = await this.#updateStoreAuthTab();
  4688. }
  4689. this.#storeInitialized = storeInitialized;
  4690. if (!this.#storeInitialized) {
  4691. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4692. return false;
  4693. }
  4694. scripts_echoLog({}).success(i18n('initSuccess', 'SteamStore'));
  4695. return true;
  4696. }
  4697. if (type === 'community') {
  4698. if (this.#communityInitialized) {
  4699. return true;
  4700. }
  4701. let communityInitialized = await this.#updateCommunityAuth();
  4702. if (!communityInitialized) {
  4703. communityInitialized = await this.#updateCommunityAuthTab();
  4704. GM_setValue('steamCommunityAuth', null);
  4705. }
  4706. this.#communityInitialized = communityInitialized;
  4707. if (!this.#communityInitialized) {
  4708. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4709. return false;
  4710. }
  4711. scripts_echoLog({}).success(i18n('initSuccess', 'SteamCommunity'));
  4712. return true;
  4713. }
  4714. if (this.#storeInitialized && this.#communityInitialized) {
  4715. scripts_echoLog({}).success(i18n('initSuccess', 'Steam'));
  4716. return true;
  4717. }
  4718. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4719. return false;
  4720. } catch (error) {
  4721. throwError(error, 'Steam.init');
  4722. return false;
  4723. }
  4724. }
  4725. async #refreshToken(type = 'steamStore') {
  4726. try {
  4727. const host = {
  4728. steamStore: 'store.steampowered.com',
  4729. steamCommunity: 'steamcommunity.com'
  4730. };
  4731. const logStatus = scripts_echoLog({
  4732. text: i18n('refreshingToken', i18n(type))
  4733. });
  4734. const formData = new FormData();
  4735. formData.append('redir', `https://${host[type]}/`);
  4736. const {
  4737. result,
  4738. statusText,
  4739. status,
  4740. data
  4741. } = await tools_httpRequest({
  4742. url: 'https://login.steampowered.com/jwt/ajaxrefresh',
  4743. method: 'POST',
  4744. responseType: 'json',
  4745. headers: {
  4746. Host: 'login.steampowered.com',
  4747. Origin: `https://${host[type]}`,
  4748. Referer: `https://${host[type]}/`
  4749. },
  4750. data: formData
  4751. });
  4752. if (result === 'Success') {
  4753. if (data?.response?.success) {
  4754. if (await this.#setStoreToken(data.response, type)) {
  4755. logStatus.success();
  4756. return true;
  4757. }
  4758. logStatus.error('Error');
  4759. return false;
  4760. }
  4761. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4762. return false;
  4763. }
  4764. logStatus.error(`${result}:${statusText}(${status})`);
  4765. return false;
  4766. } catch (error) {
  4767. throwError(error, 'Steam.refreshToken');
  4768. return false;
  4769. }
  4770. }
  4771. async #setStoreToken(param, type) {
  4772. try {
  4773. const host = {
  4774. steamStore: 'store.steampowered.com',
  4775. steamCommunity: 'steamcommunity.com'
  4776. };
  4777. const logStatus = scripts_echoLog({
  4778. text: i18n('settingToken', i18n(type))
  4779. });
  4780. const formData = new FormData();
  4781. formData.append('steamID', param.steamID);
  4782. formData.append('nonce', param.nonce);
  4783. formData.append('redir', param.redir);
  4784. formData.append('auth', param.auth);
  4785. const {
  4786. result,
  4787. statusText,
  4788. status,
  4789. data
  4790. } = await tools_httpRequest({
  4791. url: `https://${host[type]}/login/settoken`,
  4792. method: 'POST',
  4793. headers: {
  4794. Accept: 'application/json, text/plain, */*',
  4795. Host: host[type],
  4796. Origin: `https://${host[type]}`
  4797. },
  4798. data: formData
  4799. });
  4800. if (result === 'Success') {
  4801. if (data?.status === 200) {
  4802. logStatus.success();
  4803. return true;
  4804. }
  4805. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4806. return false;
  4807. }
  4808. logStatus.error(`${result}:${statusText}(${status})`);
  4809. return false;
  4810. } catch (error) {
  4811. throwError(error, 'Steam.setStoreToken');
  4812. return false;
  4813. }
  4814. }
  4815. async #updateStoreAuth(retry = false) {
  4816. try {
  4817. const logStatus = scripts_echoLog({
  4818. text: i18n('updatingAuth', i18n('steamStore'))
  4819. });
  4820. const {
  4821. result,
  4822. statusText,
  4823. status,
  4824. data
  4825. } = await tools_httpRequest({
  4826. url: 'https://store.steampowered.com/',
  4827. method: 'GET',
  4828. headers: {
  4829. 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',
  4830. 'Sec-Fetch-Dest': 'document',
  4831. 'Sec-Fetch-Mode': 'navigate',
  4832. 'Upgrade-Insecure-Requests': '1'
  4833. },
  4834. fetch: false,
  4835. redirect: 'manual'
  4836. });
  4837. if (data?.status === 200) {
  4838. if (!data.responseText.includes('data-miniprofile=')) {
  4839. if (await this.#refreshToken('steamStore')) {
  4840. logStatus.warning(i18n('retry'));
  4841. if (retry) {
  4842. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4843. return false;
  4844. }
  4845. return this.#updateStoreAuth(true);
  4846. }
  4847. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4848. return false;
  4849. }
  4850. const storeSessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  4851. if (storeSessionID) {
  4852. this.#auth.storeSessionID = storeSessionID;
  4853. logStatus.success();
  4854. return true;
  4855. }
  4856. logStatus.error('Error: Get "sessionID" failed');
  4857. return false;
  4858. }
  4859. if ([ 301, 302 ].includes(data?.status)) {
  4860. if (await this.#refreshToken('steamStore')) {
  4861. logStatus.warning(i18n('retry'));
  4862. if (retry) {
  4863. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4864. return false;
  4865. }
  4866. return this.#updateStoreAuth(true);
  4867. }
  4868. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4869. return false;
  4870. }
  4871. logStatus.error(`${result}:${statusText}(${status})`);
  4872. return false;
  4873. } catch (error) {
  4874. throwError(error, 'Steam.updateStoreAuth');
  4875. return false;
  4876. }
  4877. }
  4878. async #updateStoreAuthTab() {
  4879. try {
  4880. const logStatus = scripts_echoLog({
  4881. text: i18n('updatingAuth', i18n('steamStoreTab'))
  4882. });
  4883. return await new Promise(resolve => {
  4884. GM_deleteValue('steamStoreAuth');
  4885. GM_setValue('ATv4_updateStoreAuth', true);
  4886. const newTab = GM_openInTab('https://store.steampowered.com/', {
  4887. active: true,
  4888. setParent: true
  4889. });
  4890. newTab.name = 'ATv4_updateStoreAuth';
  4891. const listenerId = GM_addValueChangeListener('steamStoreAuth', (key, oldValue, newValue) => {
  4892. GM_removeValueChangeListener(listenerId);
  4893. GM_deleteValue('ATv4_updateStoreAuth');
  4894. newTab?.close();
  4895. window.focus();
  4896. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  4897. this.#auth.storeSessionID = newValue.storeSessionID;
  4898. logStatus.success();
  4899. resolve(true);
  4900. return;
  4901. }
  4902. logStatus.error('Failed');
  4903. resolve(false);
  4904. });
  4905. newTab.onclose = () => {
  4906. GM_deleteValue('ATv4_updateStoreAuth');
  4907. };
  4908. });
  4909. } catch (error) {
  4910. throwError(error, 'Steam.updateStoreAuthTab');
  4911. return false;
  4912. }
  4913. }
  4914. async #updateCommunityAuthTab() {
  4915. try {
  4916. const logStatus = scripts_echoLog({
  4917. text: i18n('updatingAuth', i18n('steamCommunityTab'))
  4918. });
  4919. return await new Promise(resolve => {
  4920. GM_deleteValue('steamCommunityAuth');
  4921. GM_setValue('ATv4_updateCommunityAuth', true);
  4922. const newTab = GM_openInTab('https://steamcommunity.com/my', {
  4923. active: true,
  4924. setParent: true
  4925. });
  4926. newTab.name = 'ATv4_updateCommunityAuth';
  4927. const listenerId = GM_addValueChangeListener('steamCommunityAuth', (key, oldValue, newValue) => {
  4928. GM_removeValueChangeListener(listenerId);
  4929. GM_deleteValue('ATv4_updateCommunityAuth');
  4930. newTab?.close();
  4931. window.focus();
  4932. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  4933. this.#auth.steam64Id = newValue.steam64Id;
  4934. this.#auth.communitySessionID = newValue.communitySessionID;
  4935. logStatus.success();
  4936. resolve(true);
  4937. return;
  4938. }
  4939. logStatus.error('Failed');
  4940. resolve(false);
  4941. });
  4942. newTab.onclose = () => {
  4943. GM_deleteValue('ATv4_updateCommunityAuth');
  4944. };
  4945. });
  4946. } catch (error) {
  4947. throwError(error, 'Steam.updateCommunityAuthTab');
  4948. return false;
  4949. }
  4950. }
  4951. async #updateCommunityAuth() {
  4952. try {
  4953. const logStatus = scripts_echoLog({
  4954. text: i18n('gettingUserLink')
  4955. });
  4956. const {
  4957. result,
  4958. statusText,
  4959. status,
  4960. data
  4961. } = await tools_httpRequest({
  4962. url: 'https://steamcommunity.com/my',
  4963. method: 'GET',
  4964. headers: {
  4965. 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',
  4966. Host: 'steamcommunity.com',
  4967. 'Sec-Fetch-Dest': 'document',
  4968. 'Sec-Fetch-Mode': 'navigate'
  4969. },
  4970. fetch: false
  4971. });
  4972. if (data?.status === 200) {
  4973. if (data.finalUrl.includes('https://steamcommunity.com/login/home')) {
  4974. logStatus.error(`Error:${i18n('needLoginSteamCommunity')}`, true);
  4975. return false;
  4976. }
  4977. const steam64Id = data.responseText.match(/g_steamID = "(.+?)";/)?.[1];
  4978. const communitySessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  4979. if (steam64Id && communitySessionID) {
  4980. this.#auth.steam64Id = steam64Id;
  4981. this.#auth.communitySessionID = communitySessionID;
  4982. logStatus.success();
  4983. return true;
  4984. }
  4985. logStatus.error('Error: Get "sessionID" failed');
  4986. return false;
  4987. }
  4988. logStatus.error(`${result}:${statusText}(${status})`);
  4989. return false;
  4990. } catch (error) {
  4991. throwError(error, 'Steam.updateCommunityAuth');
  4992. return false;
  4993. }
  4994. }
  4995. async #getAreaInfo() {
  4996. try {
  4997. const logStatus = scripts_echoLog({
  4998. text: i18n('gettingAreaInfo')
  4999. });
  5000. const {
  5001. result,
  5002. statusText,
  5003. status,
  5004. data
  5005. } = await tools_httpRequest({
  5006. url: 'https://store.steampowered.com/cart/',
  5007. method: 'GET'
  5008. });
  5009. if (result === 'Success') {
  5010. if (data?.status === 200) {
  5011. const cartConfigRaw = data.responseText.match(/data-cart_config="(.*?)"/)?.[1];
  5012. const temp = document.createElement('div');
  5013. temp.innerHTML = cartConfigRaw || '{}';
  5014. const cartConfigStr = temp.textContent || temp.innerText;
  5015. let cartConfig;
  5016. try {
  5017. cartConfig = JSON.parse(cartConfigStr);
  5018. } catch (error) {
  5019. logStatus.error('Error: get country info filed');
  5020. console.error(error);
  5021. return {};
  5022. }
  5023. if (!cartConfig.rgUserCountryOptions) {
  5024. logStatus.warning('Warning: Area cannot be changed');
  5025. return {};
  5026. }
  5027. const userInfoRaw = data.responseText.match(/data-userinfo="(.*?)"/)?.[1];
  5028. const temp1 = document.createElement('div');
  5029. temp1.innerHTML = userInfoRaw || '{}';
  5030. const userInfoStr = temp1.textContent || temp1.innerText;
  5031. let userInfo;
  5032. try {
  5033. userInfo = JSON.parse(userInfoStr);
  5034. } catch (error) {
  5035. logStatus.error('Error: get country info filed');
  5036. console.error(error);
  5037. return {};
  5038. }
  5039. const currentArea = userInfo.country_code;
  5040. const areas = Object.keys(cartConfig.rgUserCountryOptions).filter(area => area !== 'help');
  5041. if (currentArea && areas.length > 0) {
  5042. this.#area = currentArea;
  5043. logStatus.success();
  5044. return {
  5045. currentArea: currentArea,
  5046. areas: areas
  5047. };
  5048. }
  5049. logStatus.error('Error: get country info filed');
  5050. return {};
  5051. }
  5052. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5053. return {};
  5054. }
  5055. logStatus.error(`${result}:${statusText}(${status})`);
  5056. return {};
  5057. } catch (error) {
  5058. throwError(error, 'Steam.getAreaInfo');
  5059. return {};
  5060. }
  5061. }
  5062. async #changeArea(area) {
  5063. try {
  5064. if (this.#areaStatus === 'waiting') {
  5065. await new Promise(resolve => {
  5066. const checker = setInterval(() => {
  5067. if (this.#areaStatus !== 'waiting') {
  5068. clearInterval(checker);
  5069. resolve(true);
  5070. }
  5071. });
  5072. });
  5073. }
  5074. if (this.#area === area || !area && this.#area !== 'CN') {
  5075. return true;
  5076. }
  5077. this.#areaStatus = 'waiting';
  5078. let aimedArea = area;
  5079. if (!aimedArea) {
  5080. const {
  5081. currentArea,
  5082. areas
  5083. } = await this.#getAreaInfo();
  5084. if (!currentArea || !areas) {
  5085. this.#areaStatus = 'error';
  5086. return false;
  5087. }
  5088. if (currentArea !== 'CN') {
  5089. this.#areaStatus = 'skip';
  5090. scripts_echoLog({
  5091. text: 'notNeededChangeArea'
  5092. });
  5093. return 'skip';
  5094. }
  5095. const anotherArea = areas.filter(area => area && area !== 'CN');
  5096. if (!anotherArea || anotherArea.length === 0) {
  5097. this.#areaStatus = 'noAnotherArea';
  5098. scripts_echoLog({
  5099. text: 'noAnotherArea'
  5100. });
  5101. return false;
  5102. }
  5103. [ aimedArea ] = anotherArea;
  5104. }
  5105. const logStatus = scripts_echoLog({
  5106. text: i18n('changingArea', aimedArea)
  5107. });
  5108. const {
  5109. result,
  5110. statusText,
  5111. status,
  5112. data
  5113. } = await tools_httpRequest({
  5114. url: 'https://store.steampowered.com/country/setcountry',
  5115. method: 'POST',
  5116. headers: {
  5117. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5118. },
  5119. data: $.param({
  5120. cc: aimedArea,
  5121. sessionid: this.#auth.storeSessionID
  5122. })
  5123. });
  5124. if (result === 'Success') {
  5125. if (data?.status === 200 && data.responseText === 'true') {
  5126. const {
  5127. currentArea
  5128. } = await this.#getAreaInfo();
  5129. if (currentArea) {
  5130. this.#area = currentArea;
  5131. if (!this.#oldArea) {
  5132. this.#oldArea = currentArea;
  5133. }
  5134. }
  5135. if (currentArea === aimedArea) {
  5136. this.#areaStatus = 'success';
  5137. logStatus.success();
  5138. return currentArea;
  5139. }
  5140. this.#areaStatus = 'error';
  5141. logStatus.error('Error: change country filed');
  5142. return 'CN';
  5143. }
  5144. this.#areaStatus = 'error';
  5145. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5146. return 'CN';
  5147. }
  5148. this.#areaStatus = 'error';
  5149. logStatus.error(`${result}:${statusText}(${status})`);
  5150. return 'CN';
  5151. } catch (error) {
  5152. this.#areaStatus = 'error';
  5153. throwError(error, 'Steam.changeArea');
  5154. return false;
  5155. }
  5156. }
  5157. async #joinGroup(groupName) {
  5158. try {
  5159. if (this.#ASF) {
  5160. if (await this.#ASF.joinGroup(groupName)) {
  5161. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5162. return true;
  5163. }
  5164. return false;
  5165. }
  5166. const logStatus = scripts_echoLog({
  5167. type: 'joiningSteamGroup',
  5168. text: groupName
  5169. });
  5170. const {
  5171. result,
  5172. statusText,
  5173. status,
  5174. data
  5175. } = await tools_httpRequest({
  5176. url: `https://steamcommunity.com/groups/${groupName}`,
  5177. method: 'POST',
  5178. headers: {
  5179. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5180. },
  5181. data: $.param({
  5182. action: 'join',
  5183. sessionID: this.#auth.communitySessionID
  5184. })
  5185. });
  5186. if (result === 'Success') {
  5187. if (data?.status === 200 && !data.responseText.includes('grouppage_join_area')) {
  5188. logStatus.success();
  5189. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5190. return true;
  5191. }
  5192. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5193. return false;
  5194. }
  5195. logStatus.error(`${result}:${statusText}(${status})`);
  5196. return false;
  5197. } catch (error) {
  5198. throwError(error, 'Steam.joinGroup');
  5199. return false;
  5200. }
  5201. }
  5202. async #leaveGroup(groupName) {
  5203. try {
  5204. if (this.whiteList.groups.includes(groupName)) {
  5205. scripts_echoLog({
  5206. type: 'whiteList',
  5207. text: 'Steam.leaveGroup',
  5208. id: groupName
  5209. });
  5210. return true;
  5211. }
  5212. if (this.#ASF) {
  5213. return await this.#ASF.leaveGroup(groupName);
  5214. }
  5215. const groupId = await this.#getGroupId(groupName);
  5216. if (!groupId) {
  5217. return false;
  5218. }
  5219. const logStatus = scripts_echoLog({
  5220. type: 'leavingSteamGroup',
  5221. text: groupName
  5222. });
  5223. const {
  5224. result,
  5225. statusText,
  5226. status,
  5227. data
  5228. } = await tools_httpRequest({
  5229. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5230. method: 'POST',
  5231. headers: {
  5232. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5233. },
  5234. data: $.param({
  5235. sessionID: this.#auth.communitySessionID,
  5236. action: 'leaveGroup',
  5237. groupId: groupId
  5238. })
  5239. });
  5240. if (result === 'Success') {
  5241. 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) {
  5242. logStatus.success();
  5243. return true;
  5244. }
  5245. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5246. return false;
  5247. }
  5248. logStatus.error(`${result}:${statusText}(${status})`);
  5249. return false;
  5250. } catch (error) {
  5251. throwError(error, 'Steam.leaveGroup');
  5252. return false;
  5253. }
  5254. }
  5255. async #getGroupId(groupName) {
  5256. try {
  5257. const logStatus = scripts_echoLog({
  5258. type: 'gettingSteamGroupId',
  5259. text: groupName
  5260. });
  5261. const groupId = this.#cache.group[groupName];
  5262. if (groupId) {
  5263. logStatus.success();
  5264. return groupId;
  5265. }
  5266. const {
  5267. result,
  5268. statusText,
  5269. status,
  5270. data
  5271. } = await tools_httpRequest({
  5272. url: `https://steamcommunity.com/groups/${groupName}`,
  5273. method: 'GET',
  5274. headers: {
  5275. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5276. }
  5277. });
  5278. if (result === 'Success') {
  5279. if (data?.status === 200) {
  5280. const groupId = data.responseText.match(/OpenGroupChat\( '([0-9]+)'/)?.[1];
  5281. if (groupId) {
  5282. this.#setCache('group', groupName, groupId);
  5283. logStatus.success();
  5284. return groupId;
  5285. }
  5286. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5287. return false;
  5288. }
  5289. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5290. return false;
  5291. }
  5292. logStatus.error(`${result}:${statusText}(${status})`);
  5293. return false;
  5294. } catch (error) {
  5295. throwError(error, 'Steam.getGroupID');
  5296. return false;
  5297. }
  5298. }
  5299. async #joinOfficialGroup(gameId) {
  5300. try {
  5301. if (this.#ASF) {
  5302. if (await this.#ASF.joinGroup(gameId)) {
  5303. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5304. return true;
  5305. }
  5306. return false;
  5307. }
  5308. const logStatus = scripts_echoLog({
  5309. type: 'joiningSteamOfficialGroup',
  5310. text: gameId
  5311. });
  5312. const {
  5313. result,
  5314. statusText,
  5315. status,
  5316. data
  5317. } = await tools_httpRequest({
  5318. url: `https://steamcommunity.com/games/${gameId}?action=join&sessionID=${this.#auth.communitySessionID}`,
  5319. method: 'GET',
  5320. headers: {
  5321. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5322. }
  5323. });
  5324. if (result === 'Success') {
  5325. if (data?.status === 200 && !data.responseText.includes('id="publicGroupJoin"')) {
  5326. logStatus.success();
  5327. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5328. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5329. if (groupId) {
  5330. this.#setCache('officialGroup', gameId, groupId);
  5331. }
  5332. return true;
  5333. }
  5334. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5335. return false;
  5336. }
  5337. logStatus.error(`${result}:${statusText}(${status})`);
  5338. return false;
  5339. } catch (error) {
  5340. throwError(error, 'Steam.joinOfficialGroup');
  5341. return false;
  5342. }
  5343. }
  5344. async #leaveOfficialGroup(gameId) {
  5345. try {
  5346. if (this.whiteList.officialGroups.includes(gameId)) {
  5347. scripts_echoLog({
  5348. type: 'whiteList',
  5349. text: 'Steam.leaveOfficialGroup',
  5350. id: gameId
  5351. });
  5352. return true;
  5353. }
  5354. if (this.#ASF) {
  5355. return await this.#ASF.leaveGroup(gameId);
  5356. }
  5357. const groupId = await this.#getOfficialGroupId(gameId);
  5358. if (!groupId) {
  5359. return false;
  5360. }
  5361. const logStatus = scripts_echoLog({
  5362. type: 'leavingSteamOfficialGroup',
  5363. text: gameId
  5364. });
  5365. const {
  5366. result,
  5367. statusText,
  5368. status,
  5369. data
  5370. } = await tools_httpRequest({
  5371. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5372. method: 'POST',
  5373. headers: {
  5374. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5375. },
  5376. data: $.param({
  5377. sessionID: this.#auth.communitySessionID,
  5378. action: 'leaveGroup',
  5379. groupId: groupId
  5380. })
  5381. });
  5382. if (result === 'Success') {
  5383. if (data?.status === 200) {
  5384. const {
  5385. result: resultR,
  5386. statusText: statusTextR,
  5387. status: statusR,
  5388. data: dataR
  5389. } = await tools_httpRequest({
  5390. url: `https://steamcommunity.com/games/${gameId}`,
  5391. method: 'GET',
  5392. headers: {
  5393. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5394. }
  5395. });
  5396. if (resultR === 'Success') {
  5397. if (dataR?.status === 200 && dataR.responseText.includes('id="publicGroupJoin"')) {
  5398. logStatus.success();
  5399. return true;
  5400. }
  5401. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5402. return false;
  5403. }
  5404. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5405. return false;
  5406. }
  5407. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5408. return false;
  5409. }
  5410. logStatus.error(`${result}:${statusText}(${status})`);
  5411. return false;
  5412. } catch (error) {
  5413. throwError(error, 'Steam.leaveOfficialGroup');
  5414. return false;
  5415. }
  5416. }
  5417. async #getOfficialGroupId(gameId) {
  5418. try {
  5419. const logStatus = scripts_echoLog({
  5420. type: 'gettingSteamOfficialGroupId',
  5421. text: gameId
  5422. });
  5423. const groupId = this.#cache.officialGroup[gameId];
  5424. if (groupId) {
  5425. logStatus.success();
  5426. return groupId;
  5427. }
  5428. const {
  5429. result,
  5430. statusText,
  5431. status,
  5432. data
  5433. } = await tools_httpRequest({
  5434. url: `https://steamcommunity.com/games/${gameId}`,
  5435. method: 'GET',
  5436. headers: {
  5437. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5438. }
  5439. });
  5440. if (result === 'Success') {
  5441. if (data?.status === 200) {
  5442. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5443. if (groupId) {
  5444. this.#setCache('officialGroup', gameId, groupId);
  5445. logStatus.success();
  5446. return groupId;
  5447. }
  5448. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5449. return false;
  5450. }
  5451. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5452. return false;
  5453. }
  5454. logStatus.error(`${result}:${statusText}(${status})`);
  5455. return false;
  5456. } catch (error) {
  5457. throwError(error, 'Steam.getGroupID');
  5458. return false;
  5459. }
  5460. }
  5461. async #addToWishlist(gameId) {
  5462. try {
  5463. if (this.#ASF) {
  5464. if (await this.#ASF.addToWishlist(gameId)) {
  5465. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5466. return true;
  5467. }
  5468. return false;
  5469. }
  5470. const logStatus = scripts_echoLog({
  5471. type: 'addingToWishlist',
  5472. text: gameId
  5473. });
  5474. const {
  5475. result,
  5476. data
  5477. } = await tools_httpRequest({
  5478. url: 'https://store.steampowered.com/api/addtowishlist',
  5479. method: 'POST',
  5480. headers: {
  5481. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5482. },
  5483. data: $.param({
  5484. sessionid: this.#auth.storeSessionID,
  5485. appid: gameId
  5486. }),
  5487. dataType: 'json'
  5488. });
  5489. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  5490. logStatus.success();
  5491. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5492. return true;
  5493. }
  5494. const {
  5495. result: resultR,
  5496. statusText: statusTextR,
  5497. status: statusR,
  5498. data: dataR
  5499. } = await tools_httpRequest({
  5500. url: `https://store.steampowered.com/app/${gameId}`,
  5501. method: 'GET'
  5502. });
  5503. if (resultR === 'Success') {
  5504. if (dataR?.status === 200) {
  5505. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  5506. logStatus.warning(i18n('changeAreaNotice'));
  5507. if (!await this.#changeArea()) {
  5508. return false;
  5509. }
  5510. return await this.#addToWishlist(gameId);
  5511. }
  5512. if (dataR.responseText.includes('class="queue_actions_ctn"') && dataR.responseText.includes('class="already_in_library"')) {
  5513. logStatus.success();
  5514. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5515. return true;
  5516. } 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"')) {
  5517. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  5518. return false;
  5519. }
  5520. logStatus.success();
  5521. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5522. return true;
  5523. }
  5524. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5525. return false;
  5526. }
  5527. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5528. return false;
  5529. } catch (error) {
  5530. throwError(error, 'Steam.addToWishlist');
  5531. return false;
  5532. }
  5533. }
  5534. async #removeFromWishlist(gameId) {
  5535. try {
  5536. if (this.whiteList.wishlists.includes(gameId)) {
  5537. scripts_echoLog({
  5538. type: 'whiteList',
  5539. text: 'Steam.removeFromWishlist',
  5540. id: gameId
  5541. });
  5542. return true;
  5543. }
  5544. if (this.#ASF) {
  5545. return await this.#ASF.removeFromWishlist(gameId);
  5546. }
  5547. const logStatus = scripts_echoLog({
  5548. type: 'removingFromWishlist',
  5549. text: gameId
  5550. });
  5551. const {
  5552. result,
  5553. data
  5554. } = await tools_httpRequest({
  5555. url: 'https://store.steampowered.com/api/removefromwishlist',
  5556. method: 'POST',
  5557. headers: {
  5558. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5559. },
  5560. data: $.param({
  5561. sessionid: this.#auth.storeSessionID,
  5562. appid: gameId
  5563. }),
  5564. dataType: 'json'
  5565. });
  5566. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  5567. logStatus.success();
  5568. return true;
  5569. }
  5570. const {
  5571. result: resultR,
  5572. statusText: statusTextR,
  5573. status: statusR,
  5574. data: dataR
  5575. } = await tools_httpRequest({
  5576. url: `https://store.steampowered.com/app/${gameId}`,
  5577. method: 'GET'
  5578. });
  5579. if (resultR === 'Success') {
  5580. if (dataR?.status === 200) {
  5581. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  5582. logStatus.warning(i18n('changeAreaNotice'));
  5583. const result = await this.#changeArea();
  5584. if (!result || result === 'CN' || result === 'skip') {
  5585. return false;
  5586. }
  5587. return await this.#removeFromWishlist(gameId);
  5588. }
  5589. if (dataR.responseText.includes('class="queue_actions_ctn"') && (dataR.responseText.includes('ds_owned_flag ds_flag') || dataR.responseText.includes('add_to_wishlist_area'))) {
  5590. logStatus.success();
  5591. return true;
  5592. }
  5593. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  5594. return false;
  5595. }
  5596. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5597. return false;
  5598. }
  5599. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5600. return false;
  5601. } catch (error) {
  5602. throwError(error, 'Steam.removeFromWishlist');
  5603. return false;
  5604. }
  5605. }
  5606. async #toggleFollowGame(gameId, doTask) {
  5607. try {
  5608. if (!doTask && this.whiteList.follows.includes(gameId)) {
  5609. scripts_echoLog({
  5610. type: 'whiteList',
  5611. text: 'Steam.unfollowGame',
  5612. id: gameId
  5613. });
  5614. return true;
  5615. }
  5616. if (this.#ASF) {
  5617. if (await this.#ASF.toggleFollowGame(gameId, doTask)) {
  5618. if (doTask) {
  5619. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  5620. }
  5621. return true;
  5622. }
  5623. return false;
  5624. }
  5625. const logStatus = scripts_echoLog({
  5626. type: `${doTask ? '' : 'un'}followingGame`,
  5627. text: gameId
  5628. });
  5629. const requestData = {
  5630. sessionid: this.#auth.storeSessionID,
  5631. appid: gameId
  5632. };
  5633. if (!doTask) {
  5634. requestData.unfollow = '1';
  5635. }
  5636. const {
  5637. result,
  5638. data
  5639. } = await tools_httpRequest({
  5640. url: 'https://store.steampowered.com/explore/followgame/',
  5641. method: 'POST',
  5642. headers: {
  5643. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5644. },
  5645. data: $.param(requestData)
  5646. });
  5647. if (result === 'Success' && data?.status === 200 && data.responseText === 'true') {
  5648. logStatus.success();
  5649. return true;
  5650. }
  5651. const followed = await this.#isFollowedGame(gameId);
  5652. if (this.#area === 'CN' && followed === 'areaLocked') {
  5653. logStatus.warning(i18n('changeAreaNotice'));
  5654. if (!await this.#changeArea()) {
  5655. return false;
  5656. }
  5657. return await this.#toggleFollowGame(gameId, doTask);
  5658. }
  5659. if (doTask === followed) {
  5660. logStatus.success();
  5661. if (doTask) {
  5662. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  5663. }
  5664. return true;
  5665. }
  5666. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5667. return false;
  5668. } catch (error) {
  5669. throwError(error, 'Steam.toggleFollowGame');
  5670. return false;
  5671. }
  5672. }
  5673. async #isFollowedGame(gameId) {
  5674. try {
  5675. const {
  5676. result,
  5677. data
  5678. } = await tools_httpRequest({
  5679. url: `https://store.steampowered.com/app/${gameId}`,
  5680. method: 'GET'
  5681. });
  5682. if (result === 'Success') {
  5683. if (data?.status === 200) {
  5684. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  5685. return 'areaLocked';
  5686. }
  5687. if ($(data.responseText.replace(/<img.*?>/g, '')).find('.queue_control_button.queue_btn_follow>.btnv6_blue_hoverfade.btn_medium.queue_btn_active').css('display') !== 'none') {
  5688. return true;
  5689. }
  5690. return false;
  5691. }
  5692. return false;
  5693. }
  5694. return false;
  5695. } catch (error) {
  5696. throwError(error, 'Steam.isFollowedGame');
  5697. return false;
  5698. }
  5699. }
  5700. async #toggleForum(gameId, doTask = true) {
  5701. try {
  5702. if (!doTask && this.whiteList.forums.includes(gameId)) {
  5703. scripts_echoLog({
  5704. type: 'whiteList',
  5705. text: 'Steam.unsubscribeForum',
  5706. id: gameId
  5707. });
  5708. return true;
  5709. }
  5710. const forumId = await this.#getForumId(gameId);
  5711. if (!forumId) {
  5712. return false;
  5713. }
  5714. const logStatus = scripts_echoLog({
  5715. type: `${doTask ? '' : 'un'}subscribingForum`,
  5716. text: gameId
  5717. });
  5718. const [ id, feature ] = forumId.split('_');
  5719. const {
  5720. result,
  5721. statusText,
  5722. status,
  5723. data
  5724. } = await tools_httpRequest({
  5725. url: `https://steamcommunity.com/forum/${id}/General/${doTask ? '' : 'un'}subscribe/${feature || '0'}/`,
  5726. method: 'POST',
  5727. responseType: 'json',
  5728. headers: {
  5729. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5730. },
  5731. data: $.param({
  5732. sessionid: this.#auth.communitySessionID
  5733. })
  5734. });
  5735. if (result === 'Success') {
  5736. if (data?.status === 200 && (data.response?.success === 1 || data.response?.success === 29)) {
  5737. if (doTask) {
  5738. this.tasks.forums = unique([ ...this.tasks.forums, gameId ]);
  5739. }
  5740. logStatus.success();
  5741. return true;
  5742. }
  5743. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5744. return true;
  5745. }
  5746. logStatus.error(`${result}:${statusText}(${status})`);
  5747. return true;
  5748. } catch (error) {
  5749. throwError(error, 'Steam.toggleForum');
  5750. return true;
  5751. }
  5752. }
  5753. async #getForumId(gameId) {
  5754. try {
  5755. const logStatus = scripts_echoLog({
  5756. type: 'gettingForumId',
  5757. text: gameId
  5758. });
  5759. const forumId = this.#cache.forum[gameId];
  5760. if (forumId) {
  5761. logStatus.success();
  5762. return forumId;
  5763. }
  5764. const {
  5765. result,
  5766. statusText,
  5767. status,
  5768. data
  5769. } = await tools_httpRequest({
  5770. url: `https://steamcommunity.com/app/${gameId}/discussions/`,
  5771. method: 'GET'
  5772. });
  5773. if (result === 'Success') {
  5774. if (data?.status === 200) {
  5775. const forumId = data.responseText?.match(/General_([\d]+(_[\d]+)?)/)?.[1];
  5776. if (forumId) {
  5777. this.#setCache('forum', gameId, forumId);
  5778. logStatus.success();
  5779. return forumId;
  5780. }
  5781. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5782. return false;
  5783. }
  5784. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5785. return false;
  5786. }
  5787. logStatus.error(`${result}:${statusText}(${status})`);
  5788. return false;
  5789. } catch (error) {
  5790. throwError(error, 'Steam.getForumId');
  5791. return false;
  5792. }
  5793. }
  5794. async #toggleFavoriteWorkshop(id, doTask = true) {
  5795. try {
  5796. if (!doTask && this.whiteList.workshops.includes(id)) {
  5797. scripts_echoLog({
  5798. type: 'whiteList',
  5799. text: 'Steam.unfavoriteWorkshop',
  5800. id: id
  5801. });
  5802. return true;
  5803. }
  5804. const appid = await this.#getWorkshopAppId(id);
  5805. if (!appid) {
  5806. return false;
  5807. }
  5808. const logStatus = scripts_echoLog({
  5809. type: doTask ? 'favoritingWorkshop' : 'unfavoritingWorkshop',
  5810. text: id
  5811. });
  5812. const {
  5813. result,
  5814. statusText,
  5815. status,
  5816. data
  5817. } = await tools_httpRequest({
  5818. url: `https://steamcommunity.com/sharedfiles/${doTask ? '' : 'un'}favorite`,
  5819. method: 'POST',
  5820. headers: {
  5821. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5822. },
  5823. data: $.param({
  5824. id: id,
  5825. appid: appid,
  5826. sessionid: this.#auth.communitySessionID
  5827. })
  5828. });
  5829. if (result === 'Success') {
  5830. if (data?.status === 200 && !data.responseText) {
  5831. if (doTask) {
  5832. this.tasks.workshops = unique([ ...this.tasks.workshops, id ]);
  5833. }
  5834. logStatus.success();
  5835. return true;
  5836. }
  5837. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5838. return false;
  5839. }
  5840. logStatus.error(`${result}:${statusText}(${status})`);
  5841. return false;
  5842. } catch (error) {
  5843. throwError(error, 'Steam.toggleFavoriteWorkshop');
  5844. return false;
  5845. }
  5846. }
  5847. async #getWorkshopAppId(id) {
  5848. try {
  5849. const logStatus = scripts_echoLog({
  5850. type: 'gettingWorkshopAppId',
  5851. text: id
  5852. });
  5853. const appId = this.#cache.workshop[id];
  5854. if (appId) {
  5855. logStatus.success();
  5856. return appId;
  5857. }
  5858. const {
  5859. result,
  5860. statusText,
  5861. status,
  5862. data
  5863. } = await tools_httpRequest({
  5864. url: `https://steamcommunity.com/sharedfiles/filedetails/?id=${id}`,
  5865. method: 'GET'
  5866. });
  5867. if (result === 'Success') {
  5868. if (data?.status === 200) {
  5869. const appId = data.responseText.match(/<input type="hidden" name="appid" value="([\d]+?)" \/>/)?.[1];
  5870. if (appId) {
  5871. this.#setCache('workshop', id, appId);
  5872. logStatus.success();
  5873. return appId;
  5874. }
  5875. logStatus.error('Error: getWorkshopAppId failed');
  5876. return false;
  5877. }
  5878. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5879. return false;
  5880. }
  5881. logStatus.error(`${result}:${statusText}(${status})`);
  5882. return false;
  5883. } catch (error) {
  5884. throwError(error, 'Steam.getWorkshopAppId');
  5885. return false;
  5886. }
  5887. }
  5888. async #voteUpWorkshop(id) {
  5889. try {
  5890. const logStatus = scripts_echoLog({
  5891. type: 'votingUpWorkshop',
  5892. text: id
  5893. });
  5894. const {
  5895. result,
  5896. statusText,
  5897. status,
  5898. data
  5899. } = await tools_httpRequest({
  5900. url: 'https://steamcommunity.com/sharedfiles/voteup',
  5901. method: 'POST',
  5902. responseType: 'json',
  5903. headers: {
  5904. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5905. },
  5906. data: $.param({
  5907. id: id,
  5908. sessionid: this.#auth.communitySessionID
  5909. })
  5910. });
  5911. if (result === 'Success') {
  5912. if (data?.status === 200 && data.response?.success === 1) {
  5913. logStatus.success();
  5914. return true;
  5915. }
  5916. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5917. return true;
  5918. }
  5919. logStatus.error(`${result}:${statusText}(${status})`);
  5920. return true;
  5921. } catch (error) {
  5922. throwError(error, 'Steam.voteupWorkshop');
  5923. return true;
  5924. }
  5925. }
  5926. async #toggleCurator(curatorId, doTask = true) {
  5927. try {
  5928. if (!doTask && this.whiteList.curators.includes(curatorId)) {
  5929. scripts_echoLog({
  5930. type: 'whiteList',
  5931. text: 'Steam.unfollowCurator',
  5932. id: curatorId
  5933. });
  5934. return true;
  5935. }
  5936. if (this.#ASF) {
  5937. return await this.#ASF.toggleCurator(curatorId, doTask);
  5938. }
  5939. const logStatus = scripts_echoLog({
  5940. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  5941. text: curatorId
  5942. });
  5943. const {
  5944. result,
  5945. statusText,
  5946. status,
  5947. data
  5948. } = await tools_httpRequest({
  5949. url: 'https://store.steampowered.com/curators/ajaxfollow',
  5950. method: 'POST',
  5951. headers: {
  5952. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5953. },
  5954. data: $.param({
  5955. clanid: curatorId,
  5956. sessionid: this.#auth.storeSessionID,
  5957. follow: doTask
  5958. }),
  5959. dataType: 'json'
  5960. });
  5961. if (result === 'Success') {
  5962. if (data?.status === 200 && data.response?.success?.success === 1) {
  5963. logStatus.success();
  5964. return true;
  5965. }
  5966. logStatus.error(`Error:${data?.statusText}(${data?.response?.success}` || `${data?.status})`);
  5967. return false;
  5968. }
  5969. logStatus.error(`${result}:${statusText}(${status})`);
  5970. return false;
  5971. } catch (error) {
  5972. throwError(error, 'Steam.toggleCurator');
  5973. return false;
  5974. }
  5975. }
  5976. async getCuratorId(path, name) {
  5977. try {
  5978. const logStatus = scripts_echoLog({
  5979. type: 'gettingCuratorId',
  5980. text: `${path}/${name}`
  5981. });
  5982. const curatorId = this.#cache.curator[`${path}/${name}`];
  5983. if (curatorId) {
  5984. logStatus.success();
  5985. return curatorId;
  5986. }
  5987. const {
  5988. result,
  5989. statusText,
  5990. status,
  5991. data
  5992. } = await tools_httpRequest({
  5993. url: `https://store.steampowered.com/${path}/${name}`,
  5994. method: 'GET',
  5995. headers: {
  5996. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5997. }
  5998. });
  5999. if (result === 'Success') {
  6000. if (data?.status === 200) {
  6001. const curatorId = data.responseText.match(/g_pagingData.*?"clanid":([\d]+)/)?.[1];
  6002. if (curatorId) {
  6003. this.#setCache('curator', `${path}/${name}`, curatorId);
  6004. logStatus.success();
  6005. return curatorId;
  6006. }
  6007. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6008. return false;
  6009. }
  6010. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6011. return false;
  6012. }
  6013. logStatus.error(`${result}:${statusText}(${status})`);
  6014. return false;
  6015. } catch (error) {
  6016. throwError(error, 'Steam.getCuratorID');
  6017. return false;
  6018. }
  6019. }
  6020. async #toggleCuratorLike(link, doTask = true) {
  6021. try {
  6022. const [ path, name ] = link.split('/');
  6023. if (!(path && name)) {
  6024. scripts_echoLog({
  6025. text: i18n('errorLink', link)
  6026. });
  6027. return false;
  6028. }
  6029. const curatorId = await this.getCuratorId(path, name);
  6030. if (curatorId) {
  6031. return await this.#toggleCurator(curatorId, doTask);
  6032. }
  6033. return false;
  6034. } catch (error) {
  6035. throwError(error, 'Steam.toggleCuratorLike');
  6036. return false;
  6037. }
  6038. }
  6039. async #getAnnouncementParams(appId, viewId) {
  6040. try {
  6041. const logStatus = scripts_echoLog({
  6042. type: 'gettingAnnouncementParams',
  6043. text: appId,
  6044. id: viewId
  6045. });
  6046. const {
  6047. result,
  6048. statusText,
  6049. status,
  6050. data
  6051. } = await tools_httpRequest({
  6052. 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`,
  6053. method: 'GET',
  6054. responseType: 'json',
  6055. headers: {
  6056. Host: 'store.steampowered.com',
  6057. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6058. }
  6059. });
  6060. if (result === 'Success') {
  6061. if (data?.status === 200 && data?.response?.success === 1) {
  6062. const {
  6063. clanid,
  6064. gid
  6065. } = data.response.event?.announcement_body || {};
  6066. if (clanid) {
  6067. logStatus.success();
  6068. return {
  6069. clanId: clanid,
  6070. gid: gid
  6071. };
  6072. }
  6073. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6074. return {};
  6075. }
  6076. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6077. return {};
  6078. }
  6079. logStatus.error(`${result}:${statusText}(${status})`);
  6080. return {};
  6081. } catch (error) {
  6082. throwError(error, 'Steam.likeAnnouncement');
  6083. return {};
  6084. }
  6085. }
  6086. async #likeAnnouncement(id) {
  6087. try {
  6088. const [ appId, viewId ] = id.split('/');
  6089. if (!(appId && viewId)) {
  6090. scripts_echoLog({}).error(`${i18n('missParams')}(id)`);
  6091. return false;
  6092. }
  6093. const {
  6094. clanId,
  6095. gid
  6096. } = await this.#getAnnouncementParams(appId, viewId);
  6097. if (!clanId) {
  6098. return false;
  6099. }
  6100. const logStatus = scripts_echoLog({
  6101. type: 'likingAnnouncement',
  6102. text: appId,
  6103. id: viewId
  6104. });
  6105. const {
  6106. result,
  6107. statusText,
  6108. status,
  6109. data
  6110. } = await tools_httpRequest({
  6111. url: `https://store.steampowered.com/updated/ajaxrateupdate/${gid || viewId}`,
  6112. method: 'POST',
  6113. headers: {
  6114. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6115. Host: 'store.steampowered.com',
  6116. Origin: 'https://store.steampowered.com',
  6117. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6118. },
  6119. data: $.param({
  6120. sessionid: this.#auth.storeSessionID,
  6121. voteup: 1,
  6122. clanid: clanId,
  6123. ajax: 1
  6124. }),
  6125. dataType: 'json'
  6126. });
  6127. if (result === 'Success') {
  6128. if (data?.status === 200 && data.response.success === 1) {
  6129. logStatus.success();
  6130. return true;
  6131. }
  6132. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6133. return false;
  6134. }
  6135. logStatus.error(`${result}:${statusText}(${status})`);
  6136. return false;
  6137. } catch (error) {
  6138. throwError(error, 'Steam.likeAnnouncement');
  6139. return false;
  6140. }
  6141. }
  6142. async #appid2subid(id) {
  6143. try {
  6144. const logStatus = scripts_echoLog({
  6145. type: 'gettingSubid',
  6146. text: id
  6147. });
  6148. const {
  6149. result,
  6150. statusText,
  6151. status,
  6152. data
  6153. } = await tools_httpRequest({
  6154. url: `https://store.steampowered.com/app/${id}`,
  6155. method: 'GET',
  6156. headers: {
  6157. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6158. }
  6159. });
  6160. if (result === 'Success') {
  6161. if (data?.status === 200) {
  6162. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6163. logStatus.success(i18n('owned'));
  6164. return false;
  6165. }
  6166. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6167. logStatus.warning(i18n('changeAreaNotice'));
  6168. const result = await this.#changeArea();
  6169. if (!result || result === 'CN' || result === 'skip') {
  6170. return false;
  6171. }
  6172. return await this.#appid2subid(id);
  6173. }
  6174. let subid = data.responseText.match(/name="subid" value="([\d]+?)"/)?.[1];
  6175. if (subid) {
  6176. logStatus.success();
  6177. return subid;
  6178. }
  6179. subid = data.responseText.match(/AddFreeLicense\(\s*(\d+)/)?.[1];
  6180. if (subid) {
  6181. logStatus.success();
  6182. return subid;
  6183. }
  6184. logStatus.error(`Error:${i18n('noSubid')}`);
  6185. return false;
  6186. }
  6187. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6188. return false;
  6189. }
  6190. logStatus.error(`${result}:${statusText}(${status})`);
  6191. return false;
  6192. } catch (error) {
  6193. throwError(error, 'Steam.appid2subid');
  6194. return false;
  6195. }
  6196. }
  6197. async #getLicenses() {
  6198. try {
  6199. const logStatus = scripts_echoLog({
  6200. text: i18n('gettingLicenses')
  6201. });
  6202. const {
  6203. result,
  6204. statusText,
  6205. status,
  6206. data
  6207. } = await tools_httpRequest({
  6208. url: `https://store.steampowered.com/dynamicstore/userdata/?t=${new Date().getTime()}`,
  6209. method: 'GET',
  6210. responseType: 'json'
  6211. });
  6212. if (result === 'Success') {
  6213. if (data?.status === 200) {
  6214. logStatus.success();
  6215. return data.response?.rgOwnedPackages;
  6216. }
  6217. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6218. return false;
  6219. }
  6220. logStatus.error(`${result}:${statusText}(${status})`);
  6221. return false;
  6222. } catch (error) {
  6223. throwError(error, 'Steam.getLicenses');
  6224. return false;
  6225. }
  6226. }
  6227. async #addLicense(id) {
  6228. try {
  6229. if (this.#ASF) {
  6230. return await this.#ASF.addLicense(id);
  6231. }
  6232. const [ type, ids ] = id.split('-');
  6233. if (type === 'appid') {
  6234. const subid = await this.#appid2subid(ids);
  6235. if (!subid) {
  6236. return false;
  6237. }
  6238. const logStatus = scripts_echoLog({
  6239. type: 'addingFreeLicense',
  6240. text: ids
  6241. });
  6242. if (!await this.#addFreeLicense(subid, logStatus)) {
  6243. return false;
  6244. }
  6245. const {
  6246. result,
  6247. statusText,
  6248. status,
  6249. data
  6250. } = await tools_httpRequest({
  6251. url: `https://store.steampowered.com/app/${ids}`,
  6252. method: 'GET'
  6253. });
  6254. if (result === 'Success') {
  6255. if (data?.status === 200) {
  6256. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6257. logStatus.success();
  6258. return true;
  6259. }
  6260. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6261. return false;
  6262. }
  6263. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6264. return false;
  6265. }
  6266. logStatus.error(`${result}:${statusText}(${status})`);
  6267. return false;
  6268. } else if (type === 'subid') {
  6269. if (this.#area === 'CN') {
  6270. scripts_echoLog({}).success(i18n('tryChangeAreaNotice'));
  6271. await this.#changeArea();
  6272. }
  6273. const logStatusArr = {};
  6274. const idsArr = ids.split(',');
  6275. for (const subid of idsArr) {
  6276. const logStatus = scripts_echoLog({
  6277. type: 'addingFreeLicenseSubid',
  6278. text: subid
  6279. });
  6280. if (!await this.#addFreeLicense(subid, logStatus)) {
  6281. return false;
  6282. }
  6283. logStatusArr[subid] = logStatus;
  6284. }
  6285. const licenses = await this.#getLicenses();
  6286. if (!licenses) {
  6287. return false;
  6288. }
  6289. for (const subid of idsArr) {
  6290. if (licenses.includes(parseInt(subid, 10))) {
  6291. logStatusArr[subid].success();
  6292. } else {
  6293. logStatusArr[subid].error();
  6294. }
  6295. }
  6296. return true;
  6297. }
  6298. return false;
  6299. } catch (error) {
  6300. throwError(error, 'Steam.addLicense');
  6301. return false;
  6302. }
  6303. }
  6304. async #addFreeLicense(id, logStatusPre) {
  6305. try {
  6306. const logStatus = logStatusPre || scripts_echoLog({
  6307. type: 'addingFreeLicenseSubid',
  6308. text: id
  6309. });
  6310. const {
  6311. result,
  6312. statusText,
  6313. status,
  6314. data
  6315. } = await tools_httpRequest({
  6316. url: `https://store.steampowered.com/freelicense/addfreelicense/${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/account/licenses/'
  6323. },
  6324. data: $.param({
  6325. ajax: true,
  6326. sessionid: this.#auth.storeSessionID
  6327. }),
  6328. dataType: 'json'
  6329. });
  6330. if (result === 'Success') {
  6331. if (data?.status === 200) {
  6332. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6333. logStatus.warning(i18n('changeAreaNotice'));
  6334. const result = await this.#changeArea();
  6335. if (!result || [ 'CN', 'skip' ].includes(result)) {
  6336. return false;
  6337. }
  6338. return await this.#addFreeLicense(id);
  6339. }
  6340. logStatus.success();
  6341. return true;
  6342. }
  6343. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6344. return false;
  6345. }
  6346. logStatus.error(`${result}:${statusText}(${status})`);
  6347. return false;
  6348. } catch (error) {
  6349. throwError(error, 'Steam.addFreeLicense');
  6350. return false;
  6351. }
  6352. }
  6353. async #requestPlayTestAccess(id) {
  6354. try {
  6355. if (this.#ASF) {
  6356. return await this.#ASF.requestPlayTestAccess(id);
  6357. }
  6358. const logStatus = scripts_echoLog({
  6359. type: 'requestingPlayTestAccess',
  6360. text: id
  6361. });
  6362. const {
  6363. result,
  6364. statusText,
  6365. status,
  6366. data
  6367. } = await tools_httpRequest({
  6368. url: `https://store.steampowered.com/ajaxrequestplaytestaccess/${id}`,
  6369. method: 'POST',
  6370. headers: {
  6371. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6372. Host: 'store.steampowered.com',
  6373. Origin: 'https://store.steampowered.com',
  6374. Referer: `https://store.steampowered.com/app/${id}`
  6375. },
  6376. data: $.param({
  6377. sessionid: this.#auth.storeSessionID
  6378. }),
  6379. dataType: 'json'
  6380. });
  6381. if (result === 'Success') {
  6382. if (data?.status === 200 && data?.response?.success === 1) {
  6383. logStatus.success();
  6384. return true;
  6385. }
  6386. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6387. return false;
  6388. }
  6389. logStatus.error(`${result}:${statusText}(${status})`);
  6390. return false;
  6391. } catch (error) {
  6392. throwError(error, 'Steam.requestPlayTestAccess');
  6393. return false;
  6394. }
  6395. }
  6396. async toggle({
  6397. doTask = true,
  6398. groupLinks = [],
  6399. officialGroupLinks = [],
  6400. wishlistLinks = [],
  6401. followLinks = [],
  6402. forumLinks = [],
  6403. workshopLinks = [],
  6404. workshopVoteLinks = [],
  6405. curatorLinks = [],
  6406. curatorLikeLinks = [],
  6407. announcementLinks = [],
  6408. licenseLinks = [],
  6409. playtestLinks = []
  6410. }) {
  6411. try {
  6412. if ([ ...groupLinks, ...officialGroupLinks, ...forumLinks, ...workshopLinks, ...workshopVoteLinks ].length > 0 && !this.#communityInitialized) {
  6413. scripts_echoLog({
  6414. text: i18n('needInit')
  6415. });
  6416. return false;
  6417. }
  6418. if ([ ...wishlistLinks, ...followLinks, ...curatorLinks, ...curatorLikeLinks, ...announcementLinks, ...licenseLinks, ...playtestLinks ].length > 0 && !this.#storeInitialized) {
  6419. scripts_echoLog({
  6420. text: i18n('needInit')
  6421. });
  6422. return false;
  6423. }
  6424. const prom = [];
  6425. if (doTask && !globalOptions.doTask.steam.groups || !doTask && !globalOptions.undoTask.steam.groups) {
  6426. scripts_echoLog({
  6427. type: 'globalOptionsSkip',
  6428. text: 'steam.groups'
  6429. });
  6430. } else {
  6431. const realGroups = this.getRealParams('groups', groupLinks, doTask, link => link.match(/groups\/(.+)\/?/)?.[1]);
  6432. if (realGroups.length > 0) {
  6433. for (const group of realGroups) {
  6434. if (doTask) {
  6435. prom.push(this.#joinGroup(group));
  6436. } else {
  6437. prom.push(this.#leaveGroup(group));
  6438. }
  6439. await delay(1e3);
  6440. }
  6441. }
  6442. }
  6443. if (doTask && !globalOptions.doTask.steam.officialGroups || !doTask && !globalOptions.undoTask.steam.officialGroups) {
  6444. scripts_echoLog({
  6445. type: 'globalOptionsSkip',
  6446. text: 'steam.officialGroups'
  6447. });
  6448. } else {
  6449. const realOfficialGroups = this.getRealParams('officialGroups', officialGroupLinks, doTask, link => link.match(/games\/(.+)\/?/)?.[1]);
  6450. if (realOfficialGroups.length > 0) {
  6451. for (const officialGroup of realOfficialGroups) {
  6452. if (doTask) {
  6453. prom.push(this.#joinOfficialGroup(officialGroup));
  6454. } else {
  6455. prom.push(this.#leaveOfficialGroup(officialGroup));
  6456. }
  6457. await delay(1e3);
  6458. }
  6459. }
  6460. }
  6461. if (doTask && !globalOptions.doTask.steam.wishlists || !doTask && !globalOptions.undoTask.steam.wishlists) {
  6462. scripts_echoLog({
  6463. type: 'globalOptionsSkip',
  6464. text: 'steam.wishlists'
  6465. });
  6466. } else {
  6467. const realWishlists = this.getRealParams('wishlists', wishlistLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6468. if (realWishlists.length > 0) {
  6469. for (const game of realWishlists) {
  6470. if (doTask) {
  6471. prom.push(this.#addToWishlist(game));
  6472. } else {
  6473. prom.push(this.#removeFromWishlist(game));
  6474. }
  6475. await delay(1e3);
  6476. }
  6477. }
  6478. }
  6479. if (doTask && !globalOptions.doTask.steam.follows || !doTask && !globalOptions.undoTask.steam.follows) {
  6480. scripts_echoLog({
  6481. type: 'globalOptionsSkip',
  6482. text: 'steam.follows'
  6483. });
  6484. } else {
  6485. const realFollows = this.getRealParams('follows', followLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6486. if (realFollows.length > 0) {
  6487. for (const game of realFollows) {
  6488. prom.push(this.#toggleFollowGame(game, doTask));
  6489. await delay(1e3);
  6490. }
  6491. }
  6492. }
  6493. if (doTask && !globalOptions.doTask.steam.forums || !doTask && !globalOptions.undoTask.steam.forums) {
  6494. scripts_echoLog({
  6495. type: 'globalOptionsSkip',
  6496. text: 'steam.forums'
  6497. });
  6498. } else {
  6499. const realForums = this.getRealParams('forums', forumLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6500. if (realForums.length > 0) {
  6501. for (const forum of realForums) {
  6502. prom.push(this.#toggleForum(forum, doTask));
  6503. await delay(1e3);
  6504. }
  6505. }
  6506. }
  6507. if (doTask && !globalOptions.doTask.steam.workshops || !doTask && !globalOptions.undoTask.steam.workshops) {
  6508. scripts_echoLog({
  6509. type: 'globalOptionsSkip',
  6510. text: 'steam.workshops'
  6511. });
  6512. } else {
  6513. const realWorkshops = this.getRealParams('workshops', workshopLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  6514. if (realWorkshops.length > 0) {
  6515. for (const workshop of realWorkshops) {
  6516. prom.push(this.#toggleFavoriteWorkshop(workshop, doTask));
  6517. await delay(1e3);
  6518. }
  6519. }
  6520. }
  6521. if (doTask && !globalOptions.doTask.steam.workshopVotes) {
  6522. scripts_echoLog({
  6523. type: 'globalOptionsSkip',
  6524. text: 'steam.workshopVotes'
  6525. });
  6526. } else {
  6527. const realworkshopVotes = this.getRealParams('workshopVotes', workshopVoteLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  6528. if (doTask && realworkshopVotes.length > 0) {
  6529. for (const workshop of realworkshopVotes) {
  6530. prom.push(this.#voteUpWorkshop(workshop));
  6531. await delay(1e3);
  6532. }
  6533. }
  6534. }
  6535. if (doTask && !globalOptions.doTask.steam.curators || !doTask && !globalOptions.undoTask.steam.curators) {
  6536. scripts_echoLog({
  6537. type: 'globalOptionsSkip',
  6538. text: 'steam.curators'
  6539. });
  6540. } else {
  6541. const realCurators = this.getRealParams('curators', curatorLinks, doTask, link => link.match(/curator\/([\d]+)/)?.[1]);
  6542. const realCuratorLikes = this.getRealParams('curatorLikes', curatorLikeLinks, doTask, link => link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3).join('/'));
  6543. if (realCurators.length > 0) {
  6544. for (const curator of realCurators) {
  6545. prom.push(this.#toggleCurator(curator, doTask));
  6546. await delay(1e3);
  6547. }
  6548. }
  6549. if (realCuratorLikes.length > 0) {
  6550. for (const curatorLike of realCuratorLikes) {
  6551. prom.push(this.#toggleCuratorLike(curatorLike, doTask));
  6552. await delay(1e3);
  6553. }
  6554. }
  6555. }
  6556. if (doTask && !globalOptions.doTask.steam.announcements) {
  6557. scripts_echoLog({
  6558. type: 'globalOptionsSkip',
  6559. text: 'steam.announcements'
  6560. });
  6561. } else {
  6562. const realAnnouncements = this.getRealParams('announcements', announcementLinks, doTask, link => {
  6563. if (link.includes('store.steampowered.com')) {
  6564. return link.match(/store\.steampowered\.com\/news\/app\/([\d]+)\/view\/([\d]+)/)?.slice(1, 3).join('/');
  6565. }
  6566. return link.match(/steamcommunity\.com\/games\/([\d]+)\/announcements\/detail\/([\d]+)/)?.slice(1, 3).join('/');
  6567. });
  6568. if (doTask && realAnnouncements.length > 0) {
  6569. for (const id of realAnnouncements) {
  6570. prom.push(this.#likeAnnouncement(id));
  6571. await delay(1e3);
  6572. }
  6573. }
  6574. }
  6575. if (doTask && !globalOptions.doTask.steam.licenses) {
  6576. scripts_echoLog({
  6577. type: 'globalOptionsSkip',
  6578. text: 'steam.licenses'
  6579. });
  6580. } else if (doTask && globalOptions.doTask.steam.licenses && licenseLinks.length > 0) {
  6581. for (const ids of licenseLinks) {
  6582. const [ type, idsStr ] = ids.split('-');
  6583. const idsArr = idsStr.split(',');
  6584. for (const id of idsArr) {
  6585. prom.push(this.#addLicense(`${type}-${id}`));
  6586. await delay(1e3);
  6587. }
  6588. }
  6589. }
  6590. if (doTask && !globalOptions.doTask.steam.playtests) {
  6591. scripts_echoLog({
  6592. type: 'globalOptionsSkip',
  6593. text: 'steam.playtests'
  6594. });
  6595. } else {
  6596. const realPlaytests = this.getRealParams('playtests', playtestLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6597. if (doTask && globalOptions.doTask.steam.playtests && realPlaytests.length > 0) {
  6598. for (const id of realPlaytests) {
  6599. prom.push(this.#requestPlayTestAccess(id));
  6600. await delay(1e3);
  6601. }
  6602. }
  6603. }
  6604. return Promise.all(prom).then(async () => {
  6605. if (this.#oldArea && this.#area !== this.#oldArea) {
  6606. scripts_echoLog({}).warning(i18n('steamFinishNotice') + this.#oldArea);
  6607. await this.#changeArea(this.#oldArea);
  6608. }
  6609. return true;
  6610. });
  6611. } catch (error) {
  6612. throwError(error, 'Steam.toggle');
  6613. return false;
  6614. }
  6615. }
  6616. #setCache(type, name, id) {
  6617. try {
  6618. this.#cache[type][name] = id;
  6619. GM_setValue('steamCache', this.#cache);
  6620. } catch (error) {
  6621. throwError(error, 'Steam.setCache');
  6622. }
  6623. }
  6624. }
  6625. const social_Steam = Steam;
  6626. class Website {
  6627. undoneTasks;
  6628. socialTasks;
  6629. giveawayId;
  6630. socialInitialized = {
  6631. discord: false,
  6632. instagram: false,
  6633. reddit: false,
  6634. twitch: false,
  6635. twitter: false,
  6636. vk: false,
  6637. youtube: false,
  6638. steamStore: false,
  6639. steamCommunity: false
  6640. };
  6641. initialized = false;
  6642. steamTaskType = {
  6643. steamStore: false,
  6644. steamCommunity: false
  6645. };
  6646. social = {};
  6647. async #bind(name, init) {
  6648. try {
  6649. return {
  6650. name: name,
  6651. result: await init
  6652. };
  6653. } catch (error) {
  6654. throwError(error, 'Website.bind');
  6655. return {
  6656. name: name,
  6657. result: false
  6658. };
  6659. }
  6660. }
  6661. async initSocial(action) {
  6662. try {
  6663. const pro = [];
  6664. const tasks = action === 'do' ? this.undoneTasks : this.socialTasks;
  6665. if (tasks.discord) {
  6666. const hasDiscord = Object.values(tasks.discord).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6667. if (hasDiscord && (!this.socialInitialized.discord || !this.social.discord)) {
  6668. this.social.discord = new social_Discord();
  6669. pro.push(this.#bind('discord', this.social.discord.init(action)));
  6670. }
  6671. }
  6672. if (tasks.instagram) {
  6673. const hasInstagram = Object.values(tasks.instagram).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6674. if (hasInstagram && (!this.socialInitialized.instagram || !this.social.instagram)) {
  6675. this.social.instagram = new social_Instagram();
  6676. pro.push(this.#bind('instagram', this.social.instagram.init()));
  6677. }
  6678. }
  6679. if (tasks.reddit) {
  6680. const hasReddit = Object.values(tasks.reddit).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6681. if (hasReddit && (!this.socialInitialized.reddit || !this.social.reddit)) {
  6682. this.social.reddit = new social_Reddit();
  6683. pro.push(this.#bind('reddit', this.social.reddit.init()));
  6684. }
  6685. }
  6686. if (tasks.twitch) {
  6687. const hasTwitch = Object.values(tasks.twitch).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6688. if (hasTwitch && (!this.socialInitialized.twitch || !this.social.twitch)) {
  6689. this.social.twitch = new social_Twitch();
  6690. pro.push(this.#bind('twitch', this.social.twitch.init()));
  6691. }
  6692. }
  6693. if (tasks.twitter) {
  6694. const hasTwitter = Object.values(tasks.twitter).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6695. if (hasTwitter && (!this.socialInitialized.twitter || !this.social.twitter)) {
  6696. this.social.twitter = new social_Twitter();
  6697. pro.push(this.#bind('twitter', this.social.twitter.init()));
  6698. }
  6699. }
  6700. if (tasks.vk) {
  6701. const hasVk = Object.values(tasks.vk).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6702. if (hasVk && (!this.socialInitialized.vk || !this.social.vk)) {
  6703. this.social.vk = new social_Vk();
  6704. pro.push(this.#bind('vk', this.social.vk.init()));
  6705. }
  6706. }
  6707. if (tasks.youtube) {
  6708. const hasYoutube = Object.values(tasks.youtube).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6709. if (hasYoutube && (!this.socialInitialized.youtube || !this.social.youtube)) {
  6710. this.social.youtube = new Youtube();
  6711. pro.push(this.#bind('youtube', this.social.youtube.init()));
  6712. }
  6713. }
  6714. if (tasks.steam) {
  6715. const steamLength = Object.values(tasks.steam).reduce((total, arr) => [ ...total, ...arr ]).length;
  6716. if (steamLength > 0) {
  6717. if (!this.social.steam) {
  6718. this.social.steam = new social_Steam();
  6719. }
  6720. 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);
  6721. if (steamLength - steamCommunityLength > 0) {
  6722. this.steamTaskType.steamStore = true;
  6723. if (!this.socialInitialized.steamStore) {
  6724. pro.push(this.#bind('steamStore', this.social.steam.init('store')));
  6725. }
  6726. }
  6727. if (steamCommunityLength > 0) {
  6728. if (!this.socialInitialized.steamCommunity) {
  6729. this.steamTaskType.steamCommunity = true;
  6730. pro.push(this.#bind('steamCommunity', this.social.steam.init('community')));
  6731. }
  6732. }
  6733. }
  6734. }
  6735. if (tasks.links && tasks.links.length > 0) {
  6736. this.social.visitLink = visitLink;
  6737. }
  6738. return await Promise.all(pro).then(result => {
  6739. let checked = true;
  6740. for (const data of result) {
  6741. if (data.result) {
  6742. this.socialInitialized[data.name] = data.result;
  6743. } else {
  6744. checked = false;
  6745. }
  6746. }
  6747. return checked;
  6748. });
  6749. } catch (error) {
  6750. throwError(error, 'Website.initSocial');
  6751. return false;
  6752. }
  6753. }
  6754. uniqueTasks(allTasks) {
  6755. try {
  6756. const result = {};
  6757. for (const [ social, types ] of Object.entries(allTasks)) {
  6758. result[social] = {};
  6759. for (const [ type, tasks ] of Object.entries(types)) {
  6760. result[social][type] = unique(tasks);
  6761. }
  6762. }
  6763. return result;
  6764. } catch (error) {
  6765. throwError(error, 'Website.uniqueTasks');
  6766. return allTasks;
  6767. }
  6768. }
  6769. async toggleTask(action) {
  6770. try {
  6771. if (!this.initialized && !this.init()) {
  6772. return false;
  6773. }
  6774. if (!await this.classifyTask(action)) {
  6775. return false;
  6776. }
  6777. await this.initSocial(action);
  6778. const pro = [];
  6779. const doTask = action === 'do';
  6780. const tasks = doTask ? this.undoneTasks : this.socialTasks;
  6781. if (this.socialInitialized.discord === true && this.social.discord) {
  6782. pro.push(this.social.discord.toggle({
  6783. doTask: doTask,
  6784. ...tasks.discord
  6785. }));
  6786. }
  6787. if (this.socialInitialized.instagram === true && this.social.instagram) {
  6788. pro.push(this.social.instagram.toggle({
  6789. doTask: doTask,
  6790. ...tasks.instagram
  6791. }));
  6792. }
  6793. if (this.socialInitialized.reddit === true && this.social.reddit) {
  6794. pro.push(this.social.reddit.toggle({
  6795. doTask: doTask,
  6796. ...tasks.reddit
  6797. }));
  6798. }
  6799. if (this.socialInitialized.twitch === true && this.social.twitch) {
  6800. pro.push(this.social.twitch.toggle({
  6801. doTask: doTask,
  6802. ...tasks.twitch
  6803. }));
  6804. }
  6805. if (this.socialInitialized.twitter === true && this.social.twitter) {
  6806. pro.push(this.social.twitter.toggle({
  6807. doTask: doTask,
  6808. ...tasks.twitter
  6809. }));
  6810. }
  6811. if (this.socialInitialized.vk === true && this.social.vk) {
  6812. pro.push(this.social.vk.toggle({
  6813. doTask: doTask,
  6814. ...tasks.vk
  6815. }));
  6816. }
  6817. if (this.socialInitialized.youtube === true && this.social.youtube) {
  6818. pro.push(this.social.youtube.toggle({
  6819. doTask: doTask,
  6820. ...tasks.youtube
  6821. }));
  6822. }
  6823. if ((this.steamTaskType.steamCommunity ? this.socialInitialized.steamCommunity === true : true) && (this.steamTaskType.steamStore ? this.socialInitialized.steamStore === true : true) && this.social.steam) {
  6824. pro.push(this.social.steam.toggle({
  6825. doTask: doTask,
  6826. ...tasks.steam
  6827. }));
  6828. }
  6829. if (this.social.visitLink && tasks.links && doTask) {
  6830. for (const link of tasks.links) {
  6831. pro.push(this.social.visitLink(link));
  6832. }
  6833. }
  6834. if (doTask && tasks.extra && this.extraDoTask) {
  6835. const hasExtra = Object.values(tasks.extra).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6836. if (hasExtra) {
  6837. pro.push(this.extraDoTask(tasks.extra));
  6838. }
  6839. }
  6840. await Promise.all(pro);
  6841. scripts_echoLog({}).success(i18n('allTasksComplete'));
  6842. return true;
  6843. } catch (error) {
  6844. throwError(error, 'Website.toggleTask');
  6845. return false;
  6846. }
  6847. }
  6848. async doTask() {
  6849. try {
  6850. return await this.toggleTask('do');
  6851. } catch (error) {
  6852. throwError(error, 'Website.doTask');
  6853. return false;
  6854. }
  6855. }
  6856. async undoTask() {
  6857. try {
  6858. return await this.toggleTask('undo');
  6859. } catch (error) {
  6860. throwError(error, 'Website.undoTask');
  6861. return false;
  6862. }
  6863. }
  6864. }
  6865. const website_Website = Website;
  6866. const defaultTasksTemplate = {
  6867. steam: {
  6868. groupLinks: [],
  6869. wishlistLinks: [],
  6870. curatorLinks: [],
  6871. followLinks: []
  6872. },
  6873. discord: {
  6874. serverLinks: []
  6875. },
  6876. vk: {
  6877. nameLinks: []
  6878. },
  6879. extra: {
  6880. website: []
  6881. }
  6882. };
  6883. const defaultTasks = JSON.stringify(defaultTasksTemplate);
  6884. class FreeAnyWhere extends website_Website {
  6885. name = 'FreeAnyWhere';
  6886. tasks = [];
  6887. socialTasks = JSON.parse(defaultTasks);
  6888. undoneTasks = JSON.parse(defaultTasks);
  6889. buttons = [ 'doTask', 'undoTask', 'verifyTask', 'getKey' ];
  6890. static test() {
  6891. return window.location.host === 'freeanywhere.net';
  6892. }
  6893. async init() {
  6894. try {
  6895. const logStatus = scripts_echoLog({
  6896. text: i18n('initing')
  6897. });
  6898. debug('检测登录按钮');
  6899. if ($('div.header__login a[href*=logout]').length === 0) {
  6900. window.open('https://freeanywhere.net/game.php?steam_login', '_self');
  6901. logStatus.warning(i18n('needLogin'));
  6902. return false;
  6903. }
  6904. debug('检测是否为登录页面');
  6905. if (window.location.href.includes('/login')) {
  6906. logStatus.warning(i18n('needLogin'));
  6907. return false;
  6908. }
  6909. this.initialized = true;
  6910. logStatus.success();
  6911. return true;
  6912. } catch (error) {
  6913. throwError(error, 'Freeanywhere.init');
  6914. return false;
  6915. }
  6916. }
  6917. async classifyTask(action) {
  6918. try {
  6919. const logStatus = scripts_echoLog({
  6920. text: i18n('getTasksInfo')
  6921. });
  6922. if (action === 'undo') {
  6923. this.socialTasks = GM_getValue(`fawTasks-${this.giveawayId}`)?.tasks || JSON.parse(defaultTasks);
  6924. }
  6925. const tasks = $('div.game__content-tasks__task').map((index, element) => ({
  6926. id: $(element).attr('data-id'),
  6927. social: $(element).find('div.task-img img').attr('alt'),
  6928. link: $(element).find('div.task-link a').attr('href'),
  6929. title: $(element).find('div.task-link').text().trim(),
  6930. type: $(element).attr('data-type'),
  6931. isSuccess: $(element).hasClass('done')
  6932. })).toArray();
  6933. if (tasks.length === 0) {
  6934. logStatus.success();
  6935. return false;
  6936. }
  6937. if (action === 'verify') {
  6938. this.tasks = [];
  6939. }
  6940. for (const task of tasks) {
  6941. debug('任务分类', task);
  6942. const {
  6943. id,
  6944. social,
  6945. title,
  6946. type,
  6947. link,
  6948. isSuccess
  6949. } = task;
  6950. const taskInfo = {
  6951. id: id,
  6952. title: title,
  6953. social: social,
  6954. type: type
  6955. };
  6956. if (action === 'verify' && !isSuccess) {
  6957. this.tasks.push(taskInfo);
  6958. continue;
  6959. }
  6960. switch (type) {
  6961. case 'steam_account_verify':
  6962. break;
  6963.  
  6964. case 'steam_game_wishlist':
  6965. if (action === 'undo' && link) {
  6966. this.socialTasks.steam.wishlistLinks.push(link);
  6967. }
  6968. if (action === 'do' && !isSuccess && link) {
  6969. this.undoneTasks.steam.wishlistLinks.push(link);
  6970. }
  6971. break;
  6972.  
  6973. case 'steam_group_sub':
  6974. if (action === 'undo' && link) {
  6975. this.socialTasks.steam.groupLinks.push(link);
  6976. }
  6977. if (action === 'do' && !isSuccess && link) {
  6978. this.undoneTasks.steam.groupLinks.push(link);
  6979. }
  6980. break;
  6981.  
  6982. case 'site_visit':
  6983. if (action === 'do' && !isSuccess) {
  6984. this.undoneTasks.extra.website.push(`id=${id}&type=${type}&task=true`);
  6985. }
  6986. break;
  6987.  
  6988. case 'discord_server_sub':
  6989. if (action === 'undo' && link) {
  6990. this.socialTasks.discord.serverLinks.push(link);
  6991. }
  6992. if (action === 'do' && !isSuccess && link) {
  6993. this.undoneTasks.discord.serverLinks.push(link);
  6994. }
  6995. break;
  6996.  
  6997. case 'none':
  6998. scripts_echoLog({}).warning(`${i18n('notConnect')}`);
  6999. break;
  7000.  
  7001. default:
  7002. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${type}`);
  7003. break;
  7004. }
  7005. }
  7006. logStatus.success();
  7007. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7008. this.socialTasks = this.uniqueTasks(this.socialTasks);
  7009. if (window.DEBUG) {
  7010. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7011. }
  7012. GM_setValue(`fawTasks-${this.giveawayId}`, {
  7013. tasks: this.socialTasks,
  7014. time: new Date().getTime()
  7015. });
  7016. return true;
  7017. } catch (error) {
  7018. throwError(error, 'Freeanywhere.classifyTask');
  7019. return false;
  7020. }
  7021. }
  7022. async verifyTask() {
  7023. try {
  7024. if (!this.initialized && !this.init()) {
  7025. debug('未初始化');
  7026. return false;
  7027. }
  7028. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  7029. debug('任务列表为空', this.tasks);
  7030. return false;
  7031. }
  7032. const pro = [];
  7033. for (const task of this.tasks) {
  7034. pro.push(this.#verify(task));
  7035. await delay(1e3);
  7036. }
  7037. await Promise.all(pro);
  7038. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7039. return !!await this.getKey(true);
  7040. } catch (error) {
  7041. throwError(error, 'Freeanywhere.verifyTask');
  7042. return false;
  7043. }
  7044. }
  7045. async extraDoTask({
  7046. website
  7047. }) {
  7048. try {
  7049. const pro = [];
  7050. for (const link of website) {
  7051. pro.push(this.#doVisitWebsite(link));
  7052. }
  7053. return Promise.all(pro).then(() => true);
  7054. } catch (error) {
  7055. throwError(error, 'FreeAnyWhere.extraDoTask');
  7056. return false;
  7057. }
  7058. }
  7059. async #doVisitWebsite(link) {
  7060. try {
  7061. const logStatus = scripts_echoLog({
  7062. text: i18n('visitingLink')
  7063. });
  7064. const {
  7065. result,
  7066. statusText,
  7067. status,
  7068. data
  7069. } = await tools_httpRequest({
  7070. url: 'https://freeanywhere.net/php/task_site_visit_done.php',
  7071. method: 'POST',
  7072. headers: {
  7073. 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  7074. },
  7075. data: link
  7076. });
  7077. if (result === 'Success') {
  7078. logStatus.success();
  7079. return true;
  7080. }
  7081. logStatus.error(`${result}:${statusText}(${status})`);
  7082. return false;
  7083. } catch (error) {
  7084. throwError(error, 'FreeAnyWhere.doVisitWebsite');
  7085. return false;
  7086. }
  7087. }
  7088. async getKey(initialized) {
  7089. try {
  7090. if (!initialized && !this.initialized && !this.init()) {
  7091. debug('未初始化');
  7092. return false;
  7093. }
  7094. const logStatus = scripts_echoLog({
  7095. text: i18n('gettingKey')
  7096. });
  7097. const {
  7098. result,
  7099. statusText,
  7100. status,
  7101. data
  7102. } = await tools_httpRequest({
  7103. url: 'https://freeanywhere.net/php/user_get_key.php',
  7104. method: 'POST'
  7105. });
  7106. if (result === 'Success') {
  7107. if (data?.responseText.indexOf('bad') !== -1 || data?.responseText.length > 50) {
  7108. logStatus.error(data?.responseText);
  7109. return false;
  7110. }
  7111. logStatus.success();
  7112. scripts_echoLog({}).success(data.responseText);
  7113. return data.responseText;
  7114. }
  7115. logStatus.error(`${result}:${statusText}(${status})`);
  7116. return false;
  7117. } catch (error) {
  7118. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7119. return false;
  7120. }
  7121. }
  7122. #getGiveawayId() {
  7123. try {
  7124. const giveawayId = new URLSearchParams(window.location.search).get('n');
  7125. if (giveawayId) {
  7126. this.giveawayId = giveawayId;
  7127. return true;
  7128. }
  7129. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  7130. return false;
  7131. } catch (error) {
  7132. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7133. return false;
  7134. }
  7135. }
  7136. async #verify(task) {
  7137. try {
  7138. const logStatus = scripts_echoLog({
  7139. html: `<li>${i18n('verifyingTask')}${task.title.trim()}...<font></font></li>`
  7140. });
  7141. const {
  7142. result,
  7143. statusText,
  7144. status,
  7145. data
  7146. } = await tools_httpRequest({
  7147. url: 'https://freeanywhere.net/php/user_task_update.php',
  7148. method: 'POST',
  7149. headers: {
  7150. 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  7151. },
  7152. data: `id=${task.id}&type=${task.type}`
  7153. });
  7154. if (result === 'Success') {
  7155. if (data?.responseText.trim() === 'good') {
  7156. logStatus.success();
  7157. return true;
  7158. }
  7159. debug('任务验证结果', data?.response);
  7160. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7161. return false;
  7162. }
  7163. logStatus.error(`${result}:${statusText}(${status})`);
  7164. return false;
  7165. } catch (error) {
  7166. throwError(error, 'Freeanywhere.verify');
  7167. return false;
  7168. }
  7169. }
  7170. async #checkLeftKey() {
  7171. try {
  7172. if (!globalOptions.other.checkLeftKey) {
  7173. return true;
  7174. }
  7175. debug('检测剩余Key');
  7176. const {
  7177. data
  7178. } = await tools_httpRequest({
  7179. url: 'https://freeanywhere.net/api/v1/widget/?format=json',
  7180. method: 'GET',
  7181. dataType: 'json',
  7182. headers: {
  7183. authorization: `Token ${window.localStorage.getItem('token')}`
  7184. }
  7185. });
  7186. if (data?.response?.giveaways.find(giveaway => `${giveaway?.id}` === this.giveawayId)) {
  7187. return true;
  7188. }
  7189. await external_Swal_default().fire({
  7190. icon: 'warning',
  7191. title: i18n('notice'),
  7192. text: i18n('noKeysLeft'),
  7193. confirmButtonText: i18n('confirm'),
  7194. cancelButtonText: i18n('cancel'),
  7195. showCancelButton: true
  7196. }).then(({
  7197. value
  7198. }) => {
  7199. if (value) {
  7200. window.close();
  7201. }
  7202. });
  7203. return true;
  7204. } catch (error) {
  7205. throwError(error, 'Giveawaysu.checkLeftKey');
  7206. return false;
  7207. }
  7208. }
  7209. }
  7210. const Freeanywhere = FreeAnyWhere;
  7211. const Giveawaysu_defaultTasks = {
  7212. steam: {
  7213. groupLinks: [],
  7214. wishlistLinks: [],
  7215. curatorLinks: [],
  7216. curatorLikeLinks: [],
  7217. followLinks: [],
  7218. forumLinks: [],
  7219. announcementLinks: [],
  7220. workshopVoteLinks: [],
  7221. playtestLinks: []
  7222. },
  7223. discord: {
  7224. serverLinks: []
  7225. },
  7226. instagram: {
  7227. userLinks: []
  7228. },
  7229. vk: {
  7230. nameLinks: []
  7231. },
  7232. twitch: {
  7233. channelLinks: []
  7234. },
  7235. reddit: {
  7236. redditLinks: []
  7237. },
  7238. youtube: {
  7239. channelLinks: [],
  7240. likeLinks: []
  7241. },
  7242. twitter: {
  7243. userLinks: [],
  7244. retweetLinks: []
  7245. }
  7246. };
  7247. class GiveawaySu extends website_Website {
  7248. name = 'GiveawaySu';
  7249. socialTasks = Giveawaysu_defaultTasks;
  7250. undoneTasks = Giveawaysu_defaultTasks;
  7251. buttons = [ 'doTask', 'undoTask' ];
  7252. static test() {
  7253. return /^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(window.location.href);
  7254. }
  7255. async after() {
  7256. try {
  7257. if (!this.#checkLogin()) {
  7258. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7259. }
  7260. if (!await this.#checkLeftKey()) {
  7261. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7262. }
  7263. scripts_echoLog({}).warning(i18n('gsNotice'));
  7264. } catch (error) {
  7265. throwError(error, 'Giveawaysu.after');
  7266. }
  7267. }
  7268. init() {
  7269. try {
  7270. const logStatus = scripts_echoLog({
  7271. text: i18n('initing')
  7272. });
  7273. if ($('a.steam-login').length > 0) {
  7274. window.open('/steam/redirect', '_self');
  7275. logStatus.warning(i18n('needLogin'));
  7276. return false;
  7277. }
  7278. if (!this.#getGiveawayId()) {
  7279. return false;
  7280. }
  7281. this.initialized = true;
  7282. logStatus.success();
  7283. return true;
  7284. } catch (error) {
  7285. throwError(error, 'Giveawaysu.init');
  7286. return false;
  7287. }
  7288. }
  7289. async classifyTask(action) {
  7290. try {
  7291. const logStatus = scripts_echoLog({
  7292. text: i18n('getTasksInfo')
  7293. });
  7294. if (action === 'undo') {
  7295. this.socialTasks = GM_getValue(`gasTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  7296. return true;
  7297. }
  7298. const pro = [];
  7299. const tasks = $('#actions tr');
  7300. if ($('div.bind-discord').is(':visible')) {
  7301. $('div.bind-discord a')[0].click();
  7302. }
  7303. if ($('div.bind-twitch').is(':visible')) {
  7304. $('div.bind-twitch a')[0].click();
  7305. }
  7306. for (const task of tasks) {
  7307. pro.push(new Promise(resolve => {
  7308. const td = $(task).find('td:not(".hidden")');
  7309. const colorfulTask = td.eq(1).find('a:not([data-trigger="link"])');
  7310. const colorlessTask = td.eq(2).find('a:not([data-trigger="link"])');
  7311. const taskDes = colorfulTask.length > 0 ? colorfulTask : colorlessTask;
  7312. const taskIcon = td.eq(0).find('i').attr('class') || '';
  7313. const taskName = taskDes.text().trim();
  7314. if (taskIcon.includes('ban') || /disable adblock/gi.test(taskName)) {
  7315. return resolve(true);
  7316. }
  7317. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  7318. if (!taskLink) {
  7319. return resolve(false);
  7320. }
  7321. if (taskIcon.includes('steam') && /join/gi.test(taskName)) {
  7322. this.undoneTasks.steam.groupLinks.push(taskLink);
  7323. } else if (/like.*announcement/gi.test(taskName)) {
  7324. this.undoneTasks.steam.announcementLinks.push(taskLink);
  7325. } else if (/(follow|subscribe).*curator/gim.test(taskName) && /^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  7326. this.undoneTasks.steam.curatorLinks.push(taskLink);
  7327. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  7328. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  7329. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  7330. this.undoneTasks.steam.forumLinks.push(taskLink);
  7331. } else if (taskIcon.includes('thumbs-up') && /^https?:\/\/steamcommunity\.com\/sharedfiles\/filedetails\/\?id=[\d]+/.test(taskLink)) {
  7332. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7333. } else if (taskIcon.includes('plus') && /request.*playtest/gim.test(taskName)) {
  7334. this.undoneTasks.steam.playtestLinks.push(taskLink);
  7335. } else if (taskIcon.includes('discord') || /join.*discord/gim.test(taskName)) {
  7336. this.undoneTasks.discord.serverLinks.push(taskLink);
  7337. } else if (taskIcon.includes('instagram') || /follow.*instagram/gim.test(taskName)) {
  7338. this.undoneTasks.instagram.userLinks.push(taskLink);
  7339. } else if (taskIcon.includes('twitch') || /follow.*twitch.*channel/gim.test(taskName)) {
  7340. this.undoneTasks.twitch.channelLinks.push(taskLink);
  7341. } else if (taskIcon.includes('reddit') || /subscribe.*subreddit/gim.test(taskName) || /follow.*reddit/gim.test(taskName)) {
  7342. this.undoneTasks.reddit.redditLinks.push(taskLink);
  7343. } else if (/watch.*art/gim.test(taskName)) {
  7344. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7345. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  7346. this.undoneTasks.youtube.channelLinks.push(taskLink);
  7347. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  7348. this.undoneTasks.youtube.likeLinks.push(taskLink);
  7349. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  7350. this.undoneTasks.vk.nameLinks.push(taskLink);
  7351. } else {
  7352. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  7353. if (/wishlist.*game|add.*wishlist/gim.test(taskName)) {
  7354. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  7355. }
  7356. if (/follow.*button/gim.test(taskName)) {
  7357. this.undoneTasks.steam.followLinks.push(taskLink);
  7358. }
  7359. }
  7360. }
  7361. resolve(true);
  7362. }).catch(error => {
  7363. throwError(error, 'Giveawaysu.classifyTask->getRedirectLink');
  7364. return false;
  7365. });
  7366. }));
  7367. }
  7368. await Promise.all(pro);
  7369. logStatus.success();
  7370. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7371. this.socialTasks = this.undoneTasks;
  7372. if (window.DEBUG) {
  7373. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7374. }
  7375. GM_setValue(`gasTasks-${this.giveawayId}`, {
  7376. tasks: this.socialTasks,
  7377. time: new Date().getTime()
  7378. });
  7379. return true;
  7380. } catch (error) {
  7381. throwError(error, 'Giveawaysu.classifyTask');
  7382. return false;
  7383. }
  7384. }
  7385. #checkLogin() {
  7386. try {
  7387. if (!globalOptions.other.checkLogin) {
  7388. return true;
  7389. }
  7390. if ($('a.steam-login').length > 0) {
  7391. window.open('/steam/redirect', '_self');
  7392. }
  7393. return true;
  7394. } catch (error) {
  7395. throwError(error, 'Giveawaysu.checkLogin');
  7396. return false;
  7397. }
  7398. }
  7399. async #checkLeftKey() {
  7400. try {
  7401. if (!globalOptions.other.checkLeftKey) {
  7402. return true;
  7403. }
  7404. if ($('.giveaway-ended').length > 0 && $('.giveaway-key').length === 0) {
  7405. await external_Swal_default().fire({
  7406. icon: 'warning',
  7407. title: i18n('notice'),
  7408. text: i18n('noKeysLeft'),
  7409. confirmButtonText: i18n('confirm'),
  7410. cancelButtonText: i18n('cancel'),
  7411. showCancelButton: true
  7412. }).then(({
  7413. value
  7414. }) => {
  7415. if (value) {
  7416. window.close();
  7417. }
  7418. });
  7419. }
  7420. return true;
  7421. } catch (error) {
  7422. throwError(error, 'Giveawaysu.checkLeftKey');
  7423. return false;
  7424. }
  7425. }
  7426. #getGiveawayId() {
  7427. try {
  7428. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  7429. if (giveawayId) {
  7430. this.giveawayId = giveawayId;
  7431. return true;
  7432. }
  7433. scripts_echoLog({
  7434. text: i18n('getFailed', 'GiveawayId')
  7435. });
  7436. return false;
  7437. } catch (error) {
  7438. throwError(error, 'Giveawaysu.getGiveawayId');
  7439. return false;
  7440. }
  7441. }
  7442. }
  7443. class Indiedb {
  7444. name = 'Indiedb';
  7445. buttons = [ 'doTask' ];
  7446. static test() {
  7447. return window.location.host === 'www.indiedb.com';
  7448. }
  7449. async after() {
  7450. try {
  7451. if (!this.#checkLogin()) {
  7452. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7453. }
  7454. if (!await this.#checkLeftKey()) {
  7455. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7456. }
  7457. } catch (error) {
  7458. throwError(error, 'Indiedb.after');
  7459. }
  7460. }
  7461. async doTask() {
  7462. try {
  7463. if (!await this.#join()) {
  7464. return false;
  7465. }
  7466. return await this.#do();
  7467. } catch (error) {
  7468. throwError(error, 'Indiedb.doTask');
  7469. return false;
  7470. }
  7471. }
  7472. async #join() {
  7473. try {
  7474. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7475. scripts_echoLog({}).error(i18n('needLogin'));
  7476. return false;
  7477. }
  7478. const currentoption = $('a.buttonenter.buttongiveaway');
  7479. if (/join giveaway/gim.test(currentoption.text())) {
  7480. const logStatus = scripts_echoLog({
  7481. text: `${i18n('joiningGiveaway')}...`
  7482. });
  7483. const {
  7484. result,
  7485. statusText,
  7486. status,
  7487. data
  7488. } = await tools_httpRequest({
  7489. url: currentoption.attr('href'),
  7490. method: 'POST',
  7491. data: 'ajax=t',
  7492. dataType: 'json',
  7493. headers: {
  7494. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  7495. Accept: 'application/json, text/javascript, */*; q=0.01',
  7496. Origin: window.location.origin,
  7497. referer: window.location.href
  7498. }
  7499. });
  7500. if (result === 'Success') {
  7501. if (data?.status === 200) {
  7502. if (data.response?.success) {
  7503. currentoption.addClass('buttonentered').text('Success - Giveaway joined');
  7504. $('#giveawaysjoined').slideDown();
  7505. $('#giveawaysrecommend').slideDown();
  7506. logStatus.success(`Success${data.response?.text ? `:${data.response?.text}` : ''}`);
  7507. return true;
  7508. }
  7509. logStatus.error(`Error${data.response?.text ? `:${data.response?.text}` : ''}`);
  7510. return false;
  7511. }
  7512. if (await this.#join2()) {
  7513. logStatus.success('Success');
  7514. return true;
  7515. }
  7516. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7517. return false;
  7518. }
  7519. logStatus.error(`${result}:${statusText}(${status})`);
  7520. return false;
  7521. } else if (/success/gim.test($('a.buttonenter.buttongiveaway').text())) {
  7522. return true;
  7523. }
  7524. scripts_echoLog({}).warning(i18n('needJoinGiveaway'));
  7525. return false;
  7526. } catch (error) {
  7527. throwError(error, 'Indiedb.join');
  7528. return false;
  7529. }
  7530. }
  7531. async #join2() {
  7532. try {
  7533. return await new Promise(resolve => {
  7534. const targetNode = document.getElementById('giveawaysjoined');
  7535. const config = {
  7536. attributes: true
  7537. };
  7538. const observer = new MutationObserver(() => {
  7539. if ($('#giveawaysjoined').is(':visible')) {
  7540. resolve(true);
  7541. observer.disconnect();
  7542. }
  7543. });
  7544. observer.observe(targetNode, config);
  7545. $('a.buttonenter.buttongiveaway')[0]?.click();
  7546. setTimeout(() => {
  7547. resolve(false);
  7548. observer.disconnect();
  7549. }, 3e4);
  7550. });
  7551. } catch (error) {
  7552. throwError(error, 'Indiedb.join2');
  7553. return false;
  7554. }
  7555. }
  7556. async #do() {
  7557. try {
  7558. const id = $('script').map((index, script) => {
  7559. if (/\$\(document\)/gim.test(script.innerHTML)) {
  7560. return [ script.innerHTML.match(/"\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0], script.innerHTML.match(/"\/newsletter\/ajax\/subscribeprofile\/optin\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0] ];
  7561. }
  7562. return null;
  7563. });
  7564. if (id.length === 2) {
  7565. const pro = [];
  7566. const tasks = $('#giveawaysjoined a[class*=promo]');
  7567. for (const task of tasks) {
  7568. const promo = $(task);
  7569. if (!promo.hasClass('buttonentered')) {
  7570. const status = scripts_echoLog({
  7571. text: `${i18n('doing')}:${promo.parents('p').text()}...`
  7572. });
  7573. if (/facebookpromo|twitterpromo|visitpromo/gim.test(task.className)) {
  7574. let text = '';
  7575. if (promo.hasClass('facebookpromo')) {
  7576. text = 'facebookpromo';
  7577. } else if (promo.hasClass('twitterpromo')) {
  7578. text = 'twitterpromo';
  7579. } else {
  7580. text = 'visitpromo';
  7581. }
  7582. pro.push(new Promise(resolve => {
  7583. $.ajax({
  7584. type: 'POST',
  7585. url: urlPath(`/giveaways/ajax/${text}/${id[0]}`),
  7586. timeout: 6e4,
  7587. dataType: 'json',
  7588. data: {
  7589. ajax: 't'
  7590. },
  7591. error(response, error, exception) {
  7592. if (window.DEBUG) {
  7593. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7594. response: response,
  7595. error: error,
  7596. exception: exception
  7597. });
  7598. }
  7599. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7600. resolve(true);
  7601. },
  7602. success(response) {
  7603. if (response.success) {
  7604. status.success(`Success:${response.text}`);
  7605. promo.addClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7606. resolve(true);
  7607. } else {
  7608. status.error(`Error:${response.text}`);
  7609. resolve(true);
  7610. }
  7611. }
  7612. });
  7613. }));
  7614. } else if (promo.hasClass('emailoptinpromo')) {
  7615. pro.push(new Promise(resolve => {
  7616. $.ajax({
  7617. type: 'POST',
  7618. url: urlPath(`/newsletter/ajax/subscribeprofile/optin/${id[1]}`),
  7619. timeout: 6e4,
  7620. dataType: 'json',
  7621. data: {
  7622. ajax: 't',
  7623. emailsystoggle: 4
  7624. },
  7625. error(response, error, exception) {
  7626. if (window.DEBUG) {
  7627. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7628. response: response,
  7629. error: error,
  7630. exception: exception
  7631. });
  7632. }
  7633. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7634. resolve(true);
  7635. },
  7636. success(response) {
  7637. if (response.success) {
  7638. status.success(`Success:${response.text}`);
  7639. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7640. resolve(true);
  7641. } else {
  7642. status.error(`Error:${response.text}`);
  7643. resolve(true);
  7644. }
  7645. }
  7646. });
  7647. }));
  7648. } else if (promo.hasClass('watchingpromo')) {
  7649. pro.push(new Promise(resolve => {
  7650. const data = getUrlQuery(promo.attr('href'));
  7651. data.ajax = 't';
  7652. $.ajax({
  7653. type: 'POST',
  7654. url: urlPath(promo.attr('href')?.split(/[?#]/)[0]),
  7655. timeout: 6e4,
  7656. dataType: 'json',
  7657. data: data,
  7658. error(response, error, exception) {
  7659. if (window.DEBUG) {
  7660. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7661. response: response,
  7662. error: error,
  7663. exception: exception
  7664. });
  7665. }
  7666. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7667. resolve(true);
  7668. },
  7669. success(response) {
  7670. if (response.success) {
  7671. status.success(`Success:${response.text}`);
  7672. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7673. resolve(true);
  7674. } else {
  7675. status.error(`Error:${response.text}`);
  7676. resolve(true);
  7677. }
  7678. }
  7679. });
  7680. }));
  7681. } else if (!/the-challenge-of-adblock/gim.test(promo.attr('href'))) {
  7682. pro.push(new Promise(resolve => {
  7683. $.ajax({
  7684. type: 'POST',
  7685. url: urlPath(promo.attr('href')),
  7686. timeout: 6e4,
  7687. dataType: 'json',
  7688. data: {
  7689. ajax: 't'
  7690. },
  7691. error(response, error, exception) {
  7692. if (window.DEBUG) {
  7693. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7694. response: response,
  7695. error: error,
  7696. exception: exception
  7697. });
  7698. }
  7699. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7700. resolve(true);
  7701. },
  7702. success(response) {
  7703. if (response.success) {
  7704. status.success(`Success:${response.text}`);
  7705. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7706. resolve(true);
  7707. } else {
  7708. status.error(`Error:${response.text}`);
  7709. resolve(true);
  7710. }
  7711. }
  7712. });
  7713. }));
  7714. } else {
  7715. status.error(`Error:${i18n('unKnownTaskType')}`);
  7716. }
  7717. }
  7718. }
  7719. await Promise.all(pro);
  7720. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7721. return true;
  7722. }
  7723. scripts_echoLog({}).error(i18n('getFailed', 'TaskId'));
  7724. return false;
  7725. } catch (error) {
  7726. throwError(error, 'Indiedb.classifyTask');
  7727. return false;
  7728. }
  7729. }
  7730. #checkLogin() {
  7731. try {
  7732. if (!globalOptions.other.checkLogin) {
  7733. return true;
  7734. }
  7735. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7736. window.open('/members/login', '_self');
  7737. }
  7738. return true;
  7739. } catch (error) {
  7740. throwError(error, 'Indiedb.checkLogin');
  7741. return false;
  7742. }
  7743. }
  7744. async #checkLeftKey() {
  7745. try {
  7746. if (!globalOptions.other.checkLeftKey) {
  7747. return true;
  7748. }
  7749. if ($('a.buttonenter:contains("next time"), a.buttonenter:contains("Giveaway is closed")').length > 0) {
  7750. await external_Swal_default().fire({
  7751. icon: 'warning',
  7752. title: i18n('notice'),
  7753. text: i18n('giveawayEnded'),
  7754. confirmButtonText: i18n('confirm'),
  7755. cancelButtonText: i18n('cancel'),
  7756. showCancelButton: true
  7757. }).then(({
  7758. value
  7759. }) => {
  7760. if (value) {
  7761. window.close();
  7762. }
  7763. });
  7764. }
  7765. return true;
  7766. } catch (error) {
  7767. throwError(error, 'Indiedb.checkLeftKey');
  7768. return false;
  7769. }
  7770. }
  7771. }
  7772. const website_Indiedb = Indiedb;
  7773. const Keyhub_defaultTasksTemplate = {
  7774. steam: {
  7775. groupLinks: [],
  7776. officialGroupLinks: [],
  7777. wishlistLinks: [],
  7778. curatorLinks: []
  7779. },
  7780. discord: {
  7781. serverLinks: []
  7782. },
  7783. extra: {
  7784. videoTasks: []
  7785. },
  7786. links: []
  7787. };
  7788. const Keyhub_defaultTasks = JSON.stringify(Keyhub_defaultTasksTemplate);
  7789. class Keyhub extends website_Website {
  7790. name = 'Keyhub';
  7791. socialTasks = JSON.parse(Keyhub_defaultTasks);
  7792. undoneTasks = JSON.parse(Keyhub_defaultTasks);
  7793. buttons = [ 'doTask', 'undoTask' ];
  7794. static test() {
  7795. return window.location.host === 'key-hub.eu';
  7796. }
  7797. async after() {
  7798. try {
  7799. if (!this.#checkLogin()) {
  7800. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7801. }
  7802. if (!await this.#checkLeftKey()) {
  7803. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7804. }
  7805. $('.NSFW').hide();
  7806. } catch (error) {
  7807. throwError(error, 'Keyhub.after');
  7808. }
  7809. }
  7810. init() {
  7811. try {
  7812. const logStatus = scripts_echoLog({
  7813. text: i18n('initing')
  7814. });
  7815. if ($('a[href*="/connect/steam"]').length > 0) {
  7816. window.open('/connect/steam', '_self');
  7817. logStatus.warning(i18n('needLogin'));
  7818. return false;
  7819. }
  7820. if (!this.#getGiveawayId()) {
  7821. return false;
  7822. }
  7823. $('#VPNoverlay').hide();
  7824. $('#mainArticleSection').show();
  7825. this.initialized = true;
  7826. logStatus.success();
  7827. return true;
  7828. } catch (error) {
  7829. throwError(error, 'Keyhub.init');
  7830. return false;
  7831. }
  7832. }
  7833. async classifyTask(action) {
  7834. try {
  7835. const logStatus = scripts_echoLog({
  7836. text: i18n('getTasksInfo')
  7837. });
  7838. if (action === 'undo') {
  7839. this.socialTasks = GM_getValue(`khTasks-${this.giveawayId}`)?.tasks || JSON.parse(Keyhub_defaultTasks);
  7840. }
  7841. const tasks = $('.task:not(".googleads")').filter((index, element) => action === 'do' ? $(element).find('i.fa-check-circle:visible').length === 0 : true).find('a');
  7842. for (const task of tasks) {
  7843. let link = $(task).attr('href');
  7844. const taskDes = $(task).text().trim();
  7845. if (!link) {
  7846. continue;
  7847. }
  7848. if (/\/away\?data=/.test(link) || /steamcommunity\.com\/gid\//.test(link)) {
  7849. link = await getRedirectLink(link) || link;
  7850. }
  7851. if (/https?:\/\/key-hub\.eu\/connect\/discord/.test(link)) {
  7852. GM_openInTab(link, {
  7853. active: true
  7854. });
  7855. } else if (/steamcommunity\.com\/groups\//.test(link)) {
  7856. if (action === 'undo') {
  7857. this.socialTasks.steam.groupLinks.push(link);
  7858. }
  7859. if (action === 'do') {
  7860. this.undoneTasks.steam.groupLinks.push(link);
  7861. }
  7862. } else if (/steamcommunity\.com\/games\/[\d]+/.test(link)) {
  7863. if (action === 'undo') {
  7864. this.socialTasks.steam.officialGroupLinks.push(link);
  7865. }
  7866. if (action === 'do') {
  7867. this.undoneTasks.steam.officialGroupLinks.push(link);
  7868. }
  7869. } else if (/store\.steampowered\.com\/app\//.test(link) && /wishlist/gim.test(taskDes)) {
  7870. if (action === 'undo') {
  7871. this.socialTasks.steam.wishlistLinks.push(link);
  7872. }
  7873. if (action === 'do') {
  7874. this.undoneTasks.steam.wishlistLinks.push(link);
  7875. }
  7876. } else if (/store\.steampowered\.com\/curator\//.test(link)) {
  7877. if (action === 'undo') {
  7878. this.socialTasks.steam.curatorLinks.push(link);
  7879. }
  7880. if (action === 'do') {
  7881. this.undoneTasks.steam.curatorLinks.push(link);
  7882. }
  7883. } else if (/^https?:\/\/discord\.com\/invite\//.test(link)) {
  7884. if (action === 'undo') {
  7885. this.socialTasks.discord.serverLinks.push(link);
  7886. }
  7887. if (action === 'do') {
  7888. this.undoneTasks.discord.serverLinks.push(link);
  7889. }
  7890. } else if (/^javascript:videoTask.+/.test(link)) {
  7891. if (action === 'do') {
  7892. const taskData = link.match(/javascript:videoTask\('.+?','(.+?)'/)?.[1];
  7893. if (taskData) {
  7894. this.undoneTasks.extra.videoTasks.push(taskData);
  7895. }
  7896. }
  7897. } 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 {
  7898. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  7899. }
  7900. }
  7901. logStatus.success();
  7902. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7903. this.socialTasks = this.uniqueTasks(this.socialTasks);
  7904. if (window.DEBUG) {
  7905. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7906. }
  7907. GM_setValue(`khTasks-${this.giveawayId}`, {
  7908. tasks: this.socialTasks,
  7909. time: new Date().getTime()
  7910. });
  7911. return true;
  7912. } catch (error) {
  7913. throwError(error, 'Keyhub.classifyTask');
  7914. return false;
  7915. }
  7916. }
  7917. async #doScriptTask(data) {
  7918. try {
  7919. const logStatus = scripts_echoLog({
  7920. text: i18n('doingKeyhubTask')
  7921. });
  7922. const {
  7923. result,
  7924. statusText,
  7925. status,
  7926. data: response
  7927. } = await tools_httpRequest({
  7928. url: `/away?data=${data}`,
  7929. method: 'GET',
  7930. headers: {
  7931. origin: 'https://key-hub.eu',
  7932. referer: 'https://key-hub.eu/'
  7933. }
  7934. });
  7935. if (result === 'Success') {
  7936. if (response?.status === 200) {
  7937. logStatus.success();
  7938. return true;
  7939. }
  7940. logStatus.error(`Error:${response?.statusText}(${response?.status})`);
  7941. return false;
  7942. }
  7943. logStatus.error(`${result}:${statusText}(${status})`);
  7944. return false;
  7945. } catch (error) {
  7946. throwError(error, 'Keyhub.doScriptTask');
  7947. return false;
  7948. }
  7949. }
  7950. async extraDoTask({
  7951. videoTasks
  7952. }) {
  7953. try {
  7954. const pro = [];
  7955. for (const data of videoTasks) {
  7956. pro.push(this.#doScriptTask(data));
  7957. }
  7958. return Promise.all(pro).then(() => true);
  7959. } catch (error) {
  7960. throwError(error, 'Keyhub.extraDoTask');
  7961. return false;
  7962. }
  7963. }
  7964. #getGiveawayId() {
  7965. try {
  7966. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  7967. if (giveawayId) {
  7968. this.giveawayId = giveawayId;
  7969. return true;
  7970. }
  7971. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  7972. return false;
  7973. } catch (error) {
  7974. throwError(error, 'Keyhub.getGiveawayId');
  7975. return false;
  7976. }
  7977. }
  7978. async #checkLeftKey() {
  7979. try {
  7980. if (!globalOptions.other.checkLeftKey) {
  7981. return true;
  7982. }
  7983. const leftKey = $('#keysleft').text().trim();
  7984. if (leftKey === '0') {
  7985. await external_Swal_default().fire({
  7986. icon: 'warning',
  7987. title: i18n('notice'),
  7988. text: i18n('noKeysLeft'),
  7989. confirmButtonText: i18n('confirm'),
  7990. cancelButtonText: i18n('cancel'),
  7991. showCancelButton: true
  7992. }).then(({
  7993. value
  7994. }) => {
  7995. if (value) {
  7996. window.close();
  7997. }
  7998. });
  7999. }
  8000. return true;
  8001. } catch (error) {
  8002. throwError(error, 'Keyhub.checkLeftKey');
  8003. return false;
  8004. }
  8005. }
  8006. #checkLogin() {
  8007. try {
  8008. if (!globalOptions.other.checkLogin) {
  8009. return true;
  8010. }
  8011. if ($('a[href*="/connect/steam"]').length > 0) {
  8012. window.open('/connect/steam', '_self');
  8013. }
  8014. return true;
  8015. } catch (error) {
  8016. throwError(error, 'Keyhub.checkLogin');
  8017. return false;
  8018. }
  8019. }
  8020. }
  8021. const website_Keyhub = Keyhub;
  8022. const Givekey_defaultTasksTemplate = {
  8023. steam: {
  8024. groupLinks: [],
  8025. wishlistLinks: [],
  8026. curatorLinks: [],
  8027. curatorLikeLinks: []
  8028. },
  8029. twitter: {
  8030. userLinks: []
  8031. },
  8032. vk: {
  8033. nameLinks: []
  8034. },
  8035. discord: {
  8036. serverLinks: []
  8037. }
  8038. };
  8039. const Givekey_defaultTasks = JSON.stringify(Givekey_defaultTasksTemplate);
  8040. class Givekey extends website_Website {
  8041. name = 'Givekey';
  8042. tasks = [];
  8043. socialTasks = JSON.parse(Givekey_defaultTasks);
  8044. undoneTasks = JSON.parse(Givekey_defaultTasks);
  8045. userId;
  8046. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8047. static test() {
  8048. return window.location.host === 'givekey.ru';
  8049. }
  8050. async after() {
  8051. try {
  8052. await new Promise(resolve => {
  8053. const checker = setInterval(() => {
  8054. if ($('#navbarDropdown').length > 0) {
  8055. clearInterval(checker);
  8056. resolve(true);
  8057. }
  8058. }, 500);
  8059. });
  8060. if (!await this.#checkLeftKey()) {
  8061. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8062. }
  8063. } catch (error) {
  8064. throwError(error, 'Givekey.after');
  8065. }
  8066. }
  8067. init() {
  8068. try {
  8069. const logStatus = scripts_echoLog({
  8070. text: i18n('initing')
  8071. });
  8072. if ($('a[href*="/auth/steam"]').length > 0) {
  8073. window.open('/auth/steam', '_self');
  8074. logStatus.warning(i18n('needLogin'));
  8075. return false;
  8076. }
  8077. if (!this.#getGiveawayId()) {
  8078. return false;
  8079. }
  8080. const userId = $('meta[name="user-id"]').attr('content');
  8081. if (!userId) {
  8082. logStatus.error(i18n('getFailed', i18n('userId')));
  8083. return false;
  8084. }
  8085. this.userId = userId;
  8086. this.initialized = true;
  8087. logStatus.success();
  8088. return true;
  8089. } catch (error) {
  8090. throwError(error, 'Givekey.init');
  8091. return false;
  8092. }
  8093. }
  8094. async classifyTask(action) {
  8095. try {
  8096. const logStatus = scripts_echoLog({
  8097. text: i18n('getTasksInfo')
  8098. });
  8099. if (action === 'undo') {
  8100. this.socialTasks = GM_getValue(`gkTasks-${this.giveawayId}`)?.tasks || JSON.parse(Givekey_defaultTasks);
  8101. }
  8102. const tasks = $('.card-body:has("button") .row');
  8103. for (const task of tasks) {
  8104. const taskEle = $(task);
  8105. const isSuccess = /Complete/i.test(taskEle.find('button').text().trim());
  8106. if (isSuccess && action !== 'undo') {
  8107. continue;
  8108. }
  8109. const checkButton = taskEle.find('#task_check');
  8110. const taskId = checkButton.attr('data-id');
  8111. if (taskId) {
  8112. this.tasks.push(taskId);
  8113. }
  8114. if (action === 'verify') {
  8115. continue;
  8116. }
  8117. let href = taskEle.find('a').attr('href') || null;
  8118. const text = taskEle.find('a').text().trim();
  8119. const icon = taskEle.find('i');
  8120. if (!href || !text) {
  8121. continue;
  8122. }
  8123. if (/^https?:\/\/givekey\.ru\/giveaway\/[\d]+\/execution_task/.test(href)) {
  8124. href = await getRedirectLink(href);
  8125. }
  8126. if (!href) {
  8127. continue;
  8128. }
  8129. if (/^https?:\/\/vk\.com\//.test(href)) {
  8130. this.socialTasks.vk.nameLinks.push(href);
  8131. if (action === 'do' && !isSuccess) {
  8132. this.undoneTasks.vk.nameLinks.push(href);
  8133. }
  8134. } else if (/^https?:\/\/steamcommunity\.com\/groups/.test(href)) {
  8135. this.socialTasks.steam.groupLinks.push(href);
  8136. if (action === 'do' && !isSuccess) {
  8137. this.undoneTasks.steam.groupLinks.push(href);
  8138. }
  8139. } else if (/^https?:\/\/store\.steampowered\.com\/app\//.test(href)) {
  8140. this.socialTasks.steam.wishlistLinks.push(href);
  8141. if (action === 'do' && !isSuccess) {
  8142. this.undoneTasks.steam.wishlistLinks.push(href);
  8143. }
  8144. } else if (/Subscribe/gi.test(text) && icon.hasClass('fa-steam-square')) {
  8145. if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(href)) {
  8146. this.socialTasks.steam.curatorLinks.push(href);
  8147. if (action === 'do' && !isSuccess) {
  8148. this.undoneTasks.steam.curatorLinks.push(href);
  8149. }
  8150. } else {
  8151. this.socialTasks.steam.curatorLikeLinks.push(href);
  8152. if (action === 'do' && !isSuccess) {
  8153. this.undoneTasks.steam.curatorLikeLinks.push(href);
  8154. }
  8155. }
  8156. } else if (/^https?:\/\/twitter\.com\//.test(href) && /Subscribe/gi.test(text)) {
  8157. this.socialTasks.twitter.userLinks.push(href);
  8158. if (action === 'do' && !isSuccess) {
  8159. this.undoneTasks.twitter.userLinks.push(href);
  8160. }
  8161. } else if (icon.hasClass('fa-discord') || /^https?:\/\/discord\.com\/invite\//.test(href)) {
  8162. this.socialTasks.discord.serverLinks.push(href);
  8163. if (action === 'do' && !isSuccess) {
  8164. this.undoneTasks.discord.serverLinks.push(href);
  8165. }
  8166. } else {
  8167. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${text}(${href})`);
  8168. }
  8169. }
  8170. logStatus.success();
  8171. this.tasks = unique(this.tasks);
  8172. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8173. this.socialTasks = this.uniqueTasks(this.socialTasks);
  8174. if (window.DEBUG) {
  8175. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8176. }
  8177. GM_setValue(`gkTasks-${this.giveawayId}`, {
  8178. tasks: this.socialTasks,
  8179. time: new Date().getTime()
  8180. });
  8181. return true;
  8182. } catch (error) {
  8183. throwError(error, 'Givekey.classifyTask');
  8184. return false;
  8185. }
  8186. }
  8187. async verifyTask() {
  8188. try {
  8189. if (!this.initialized && !this.init()) {
  8190. return false;
  8191. }
  8192. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  8193. return false;
  8194. }
  8195. scripts_echoLog({}).warning(i18n('giveKeyNoticeBefore'));
  8196. const taskLength = this.tasks.length;
  8197. for (let i = 0; i < taskLength; i++) {
  8198. await this.#verify(this.tasks[i]);
  8199. if (i < taskLength - 1) {
  8200. await delay(15e3);
  8201. }
  8202. }
  8203. scripts_echoLog({}).success(i18n('allTasksComplete'));
  8204. scripts_echoLog({
  8205. html: `<li><font class="warning">${i18n('giveKeyNoticeAfter')}</font></li>`
  8206. });
  8207. return true;
  8208. } catch (error) {
  8209. throwError(error, 'Givekey.verifyTask');
  8210. return false;
  8211. }
  8212. }
  8213. async #verify(task) {
  8214. try {
  8215. const logStatus = scripts_echoLog({
  8216. html: `<li>${i18n('verifyingTask')}${task}...<font></font></li>`
  8217. });
  8218. return await new Promise(resolve => {
  8219. $.ajax({
  8220. url: 'https://givekey.ru/giveaway/task',
  8221. method: 'POST',
  8222. data: `id=${task}&user_id=${this.userId}`,
  8223. dataType: 'json',
  8224. headers: {
  8225. 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  8226. },
  8227. success: data => {
  8228. if (data.btn) {
  8229. $(`button[data-id=${this.userId}]`).html(data.btn);
  8230. }
  8231. if (data.status === 'ok') {
  8232. $(`.task_check_${data.id}`).html(`<button class="btn btn-success mb-2 btn-block" disabled>${data.btn}</button>`);
  8233. logStatus.success();
  8234. resolve(true);
  8235. } else if (data.status === 'end') {
  8236. logStatus.success();
  8237. scripts_echoLog({}).success(data.key);
  8238. resolve(true);
  8239. } else {
  8240. logStatus.error(`Error:${data.msg}`);
  8241. resolve(false);
  8242. }
  8243. },
  8244. error: xhr => {
  8245. logStatus.error(`Error:${xhr.statusText}(${xhr.status})`);
  8246. resolve(false);
  8247. }
  8248. });
  8249. });
  8250. } catch (error) {
  8251. throwError(error, 'Givekey.verify');
  8252. return false;
  8253. }
  8254. }
  8255. #getGiveawayId() {
  8256. try {
  8257. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  8258. if (giveawayId) {
  8259. this.giveawayId = giveawayId;
  8260. return true;
  8261. }
  8262. scripts_echoLog({
  8263. text: i18n('getFailed', 'GiveawayId')
  8264. });
  8265. return false;
  8266. } catch (error) {
  8267. throwError(error, 'Givekey.getGiveawayId');
  8268. return false;
  8269. }
  8270. }
  8271. async #checkLeftKey() {
  8272. try {
  8273. if (!globalOptions.other.checkLeftKey) {
  8274. return true;
  8275. }
  8276. if (!$('#keys_count').text()) {
  8277. await external_Swal_default().fire({
  8278. icon: 'warning',
  8279. title: i18n('notice'),
  8280. text: i18n('noKeysLeft'),
  8281. confirmButtonText: i18n('confirm'),
  8282. cancelButtonText: i18n('cancel'),
  8283. showCancelButton: true
  8284. }).then(({
  8285. value
  8286. }) => {
  8287. if (value) {
  8288. window.close();
  8289. }
  8290. });
  8291. }
  8292. return true;
  8293. } catch (error) {
  8294. throwError(error, 'Givekey.checkLeftKey');
  8295. return false;
  8296. }
  8297. }
  8298. }
  8299. const website_Givekey = Givekey;
  8300. class GiveeClub extends GiveawaySu {
  8301. name = 'GiveeClub';
  8302. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8303. static test() {
  8304. return /^https?:\/\/givee\.club\/.*?\/event\/[\d]+/.test(window.location.href);
  8305. }
  8306. async after() {
  8307. try {
  8308. if (!this.#checkLogin()) {
  8309. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8310. }
  8311. if (!await this.#checkLeftKey()) {
  8312. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8313. }
  8314. } catch (error) {
  8315. throwError(error, 'GiveeClub.after');
  8316. }
  8317. }
  8318. init() {
  8319. try {
  8320. const logStatus = scripts_echoLog({
  8321. text: i18n('initing')
  8322. });
  8323. if (!this.#checkLogin()) {
  8324. logStatus.warning(i18n('needLogin'));
  8325. return false;
  8326. }
  8327. if (!this.#getGiveawayId()) {
  8328. return false;
  8329. }
  8330. this.initialized = true;
  8331. logStatus.success();
  8332. return true;
  8333. } catch (error) {
  8334. throwError(error, 'GiveeClub.init');
  8335. return false;
  8336. }
  8337. }
  8338. async classifyTask(action) {
  8339. try {
  8340. const logStatus = scripts_echoLog({
  8341. text: i18n('getTasksInfo')
  8342. });
  8343. if (action === 'undo') {
  8344. this.socialTasks = GM_getValue(`gcTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  8345. return true;
  8346. }
  8347. this.undoneTasks = Giveawaysu_defaultTasks;
  8348. const pro = [];
  8349. const tasks = $('.event-actions tr');
  8350. for (const task of tasks) {
  8351. pro.push(new Promise(resolve => {
  8352. const taskDes = $(task).find('.event-action-label a');
  8353. const taskIcon = $(task).find('.event-action-icon i').attr('class') || '';
  8354. const taskName = taskDes.text().trim();
  8355. const taskType = $(task).find('button[data-type]')?.attr('data-type');
  8356. const taskFinished = $(task).find('.event-action-buttons .btn-success')?.length;
  8357. if (taskIcon.includes('ban') || /AdBlock/i.test(taskName) || taskIcon.includes('envelope') || taskFinished) {
  8358. return resolve(true);
  8359. }
  8360. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  8361. if (!taskLink) {
  8362. return resolve(false);
  8363. }
  8364. if (taskType === 'steam.group.join' && /^https?:\/\/steamcommunity\.com\/groups/.test(taskLink)) {
  8365. this.undoneTasks.steam.groupLinks.push(taskLink);
  8366. } else if (/like.*announcement/gi.test(taskName)) {
  8367. this.undoneTasks.steam.announcementLinks.push(taskLink);
  8368. } else if (taskType === 'steam.game.wishlist' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8369. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  8370. } else if (taskType === 'steam.game.wishlist' && taskDes.attr('data-steam-wishlist-appid')) {
  8371. this.undoneTasks.steam.wishlistLinks.push(`https://store.steampowered.com/app/${taskDes.attr('data-steam-wishlist-appid')}`);
  8372. } else if (taskType === 'steam.game.follow' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8373. this.undoneTasks.steam.followLinks.push(taskLink);
  8374. } else if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  8375. this.undoneTasks.steam.curatorLinks.push(taskLink);
  8376. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  8377. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  8378. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  8379. this.undoneTasks.steam.forumLinks.push(taskLink);
  8380. } else if (taskIcon.includes('discord')) {
  8381. this.undoneTasks.discord.serverLinks.push(taskLink);
  8382. } else if (taskIcon.includes('instagram')) {
  8383. this.undoneTasks.instagram.userLinks.push(taskLink);
  8384. } else if (taskIcon.includes('twitch')) {
  8385. this.undoneTasks.twitch.channelLinks.push(taskLink);
  8386. } else if (taskIcon.includes('reddit')) {
  8387. this.undoneTasks.reddit.redditLinks.push(taskLink);
  8388. } else if (/watch.*art/gim.test(taskName)) {
  8389. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  8390. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  8391. this.undoneTasks.youtube.channelLinks.push(taskLink);
  8392. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  8393. this.undoneTasks.youtube.likeLinks.push(taskLink);
  8394. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  8395. this.undoneTasks.vk.nameLinks.push(taskLink);
  8396. } else if (taskIcon.includes('twitter')) {
  8397. if (/https?:\/\/(twitter|x)\.com\/[^/]+\/?$/gim.test(taskLink)) {
  8398. this.undoneTasks.twitter.userLinks.push(taskLink);
  8399. } else if (/https?:\/\/(twitter|x)\.com\/[^/]+?\/status\/[\d]+/gim.test(taskLink)) {
  8400. this.undoneTasks.twitter.retweetLinks.push(taskLink);
  8401. }
  8402. } else {
  8403. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  8404. if (/follow.*button/gim.test(taskName)) {
  8405. this.undoneTasks.steam.followLinks.push(taskLink);
  8406. }
  8407. }
  8408. }
  8409. resolve(true);
  8410. }).catch(error => {
  8411. throwError(error, 'GiveeClub.classifyTask->getRedirectLink');
  8412. return false;
  8413. });
  8414. }));
  8415. }
  8416. await Promise.all(pro);
  8417. logStatus.success();
  8418. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8419. this.socialTasks = this.undoneTasks;
  8420. if (window.DEBUG) {
  8421. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8422. }
  8423. GM_setValue(`gcTasks-${this.giveawayId}`, {
  8424. tasks: this.socialTasks,
  8425. time: new Date().getTime()
  8426. });
  8427. return true;
  8428. } catch (error) {
  8429. throwError(error, 'GiveeClub.classifyTask');
  8430. return false;
  8431. }
  8432. }
  8433. async verifyTask() {
  8434. try {
  8435. const logStatus = scripts_echoLog({
  8436. text: i18n('giveeClubVerifyNotice')
  8437. });
  8438. const taskButtons = $('.event-actions tr button').has('i.glyphicon-refresh').not('[data-type="user.adblock"]');
  8439. for (const button of taskButtons) {
  8440. button.click();
  8441. if ($(button).attr('data-type') !== 'steam.game.wishlist') {
  8442. await delay(1e3);
  8443. }
  8444. }
  8445. logStatus.warning(i18n('giveeClubVerifyFinished'));
  8446. return true;
  8447. } catch (error) {
  8448. throwError(error, 'Givekey.verifyTask');
  8449. return false;
  8450. }
  8451. }
  8452. #checkLogin() {
  8453. try {
  8454. if (!globalOptions.other.checkLogin) {
  8455. return true;
  8456. }
  8457. if ($('a[href*="/account/auth"]').length > 0) {
  8458. window.open($('a[href*="/account/auth"]').attr('href'), '_self');
  8459. }
  8460. return true;
  8461. } catch (error) {
  8462. throwError(error, 'GiveeClub.checkLogin');
  8463. return false;
  8464. }
  8465. }
  8466. #getGiveawayId() {
  8467. const giveawayId = window.location.href.match(/\/event\/([\d]+)/)?.[1];
  8468. if (giveawayId) {
  8469. this.giveawayId = giveawayId;
  8470. return true;
  8471. }
  8472. scripts_echoLog({
  8473. text: i18n('getFailed', 'GiveawayId')
  8474. });
  8475. return false;
  8476. }
  8477. async #checkLeftKey() {
  8478. try {
  8479. if (!globalOptions.other.checkLeftKey) {
  8480. return true;
  8481. }
  8482. if ($('.event-ended').length > 0 && $('.event-winner').length === 0) {
  8483. await external_Swal_default().fire({
  8484. icon: 'warning',
  8485. title: i18n('notice'),
  8486. text: i18n('giveawayEnded'),
  8487. confirmButtonText: i18n('confirm'),
  8488. cancelButtonText: i18n('cancel'),
  8489. showCancelButton: true
  8490. }).then(({
  8491. value
  8492. }) => {
  8493. if (value) {
  8494. window.close();
  8495. }
  8496. });
  8497. }
  8498. return true;
  8499. } catch (error) {
  8500. throwError(error, 'Giveawaysu.checkLeftKey');
  8501. return false;
  8502. }
  8503. }
  8504. }
  8505. const website_GiveeClub = GiveeClub;
  8506. const defaultOptions = {
  8507. maxPoint: '99999999'
  8508. };
  8509. class OpiumPulses {
  8510. name = 'OpiumPulses';
  8511. options = {
  8512. ...defaultOptions,
  8513. ...GM_getValue('OpiumPulsesOptions')
  8514. };
  8515. maxPoints = 99999999;
  8516. myPoints = 0;
  8517. buttons = [ 'doFreeTask', 'doPointTask' ];
  8518. static test() {
  8519. return window.location.host === 'www.opiumpulses.com';
  8520. }
  8521. async after() {
  8522. try {
  8523. if (!this.#checkLogin()) {
  8524. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8525. }
  8526. this.maxPoints = parseInt(this.options.maxPoint, 10);
  8527. } catch (error) {
  8528. throwError(error, 'OpiumPulses.after');
  8529. }
  8530. }
  8531. async doFreeTask() {
  8532. try {
  8533. this.#toggleTask('FREE');
  8534. } catch (error) {
  8535. throwError(error, 'OpiumPulses.doFreeTask');
  8536. }
  8537. }
  8538. async doPointTask() {
  8539. try {
  8540. this.myPoints = parseInt($('.page-header__nav-func-user-nav-items.points-items').text().match(/[\d]+/gim)?.[0] || '0', 10);
  8541. this.#toggleTask('points');
  8542. } catch (error) {
  8543. throwError(error, 'OpiumPulses.doPointTask');
  8544. }
  8545. }
  8546. async #toggleTask(type) {
  8547. try {
  8548. const items = $(`.giveaways-page-item:contains('${type}'):not(:contains('ENTERED'))`);
  8549. for (const item of items) {
  8550. const needPoints = parseInt($(item).find('.giveaways-page-item-header-points').text().match(/[\d]+/gim)?.[0] || '999999', 10);
  8551. const name = $(item).find('.giveaways-page-item-footer-name').text().trim();
  8552. if (type === 'points' && needPoints > this.myPoints) {
  8553. scripts_echoLog({}).warning(`${i18n('noPoints')}: ${name}`);
  8554. } else if (type === 'points' && !needPoints) {
  8555. scripts_echoLog({}).warning(`${i18n('getNeedPointsFailed')}: ${name}`);
  8556. } else if (!(type === 'points' && needPoints > this.maxPoints)) {
  8557. const logStatus = scripts_echoLog({
  8558. text: `${i18n('joiningLottery')}<a href="${$(item).find('a.giveaways-page-item-img-btn-more').attr('href')}" target="_blank">${name}</a>...`
  8559. });
  8560. const aElement = $(item).find('a.giveaways-page-item-img-btn-enter:contains(\'enter\')');
  8561. if (aElement?.attr('onclick')?.includes('checkUser')) {
  8562. const giveawayId = aElement.attr('onclick')?.match(/[\d]+/)?.[0];
  8563. if (giveawayId) {
  8564. checkUser(giveawayId);
  8565. }
  8566. }
  8567. if (!aElement.attr('href')) {
  8568. logStatus.error('Error: No "href".');
  8569. continue;
  8570. }
  8571. const {
  8572. result,
  8573. statusText,
  8574. status,
  8575. data
  8576. } = await tools_httpRequest({
  8577. url: aElement.attr('href'),
  8578. method: 'GET'
  8579. });
  8580. if (result === 'Success') {
  8581. const {
  8582. result: result0,
  8583. statusText: statusText0,
  8584. status: status0,
  8585. data: data0
  8586. } = await tools_httpRequest({
  8587. url: data?.finalUrl,
  8588. method: 'GET'
  8589. });
  8590. if (data0?.responseText && /You've entered this giveaway/gim.test(data0.responseText)) {
  8591. logStatus.success();
  8592. const points = data0.responseText.match(/Points:[\s]*?([\d]+)/)?.[1];
  8593. if (type === 'points' && points) {
  8594. this.myPoints = parseInt(points, 10);
  8595. }
  8596. } else if (data0?.responseText && /You're not eligible to enter/gim.test(data0.responseText)) {
  8597. logStatus.error('You\'re not eligible to enter');
  8598. } else {
  8599. logStatus.error(`${result0}:${statusText0}(${status0})`);
  8600. }
  8601. } else {
  8602. logStatus.error(`${result}:${statusText}(${status})`);
  8603. }
  8604. }
  8605. }
  8606. scripts_echoLog({
  8607. text: '-----END-----'
  8608. });
  8609. } catch (error) {
  8610. throwError(error, 'OpiumPulses.toggleTask');
  8611. }
  8612. }
  8613. init() {
  8614. return true;
  8615. }
  8616. classifyTask() {
  8617. return true;
  8618. }
  8619. #checkLogin() {
  8620. try {
  8621. if (!globalOptions.other.checkLogin) {
  8622. return true;
  8623. }
  8624. if ($('a[href*="/site/login"]').length > 1) {
  8625. window.open('/site/login', '_self');
  8626. }
  8627. return true;
  8628. } catch (error) {
  8629. throwError(error, 'OpiumPulses.checkLogin');
  8630. return false;
  8631. }
  8632. }
  8633. }
  8634. const website_OpiumPulses = OpiumPulses;
  8635. const external_dayjs_namespaceObject = dayjs;
  8636. var external_dayjs_default = __webpack_require__.n(external_dayjs_namespaceObject);
  8637. const leftKeyChecker = {
  8638. async classify(link) {
  8639. try {
  8640. if (/^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(link)) {
  8641. return await this.giveawaySu(link);
  8642. }
  8643. if (/^https?:\/\/givee\.club\/[\w]+?\/event\/[\d]+/.test(link)) {
  8644. return await this.giveeClub(link);
  8645. }
  8646. if (/^https?:\/\/gleam\.io\/.+?\/.+/.test(link)) {
  8647. return await this.gleam(link);
  8648. }
  8649. if (/^https?:\/\/www\.indiedb\.com\/giveaways\/.+/.test(link)) {
  8650. return await this.indieDb(link);
  8651. }
  8652. if (/^https?:\/\/key-hub\.eu\/giveaway\/[\d]+/.test(link)) {
  8653. return await this.keyhub(link);
  8654. }
  8655. if (/^https?:\/\/opquests\.com\/quests\/[\d]+/.test(link)) {
  8656. return await this.opquests(link);
  8657. }
  8658. if (/^https?:\/\/itch\.io\/s\/[\d]+?\/.*/.test(link)) {
  8659. return await this.itch(link);
  8660. }
  8661. return false;
  8662. } catch (error) {
  8663. throwError(error, 'leftKeyChecker.classify');
  8664. return false;
  8665. }
  8666. },
  8667. async giveawaySu(link) {
  8668. try {
  8669. const {
  8670. result,
  8671. data
  8672. } = await tools_httpRequest({
  8673. url: link,
  8674. method: 'GET'
  8675. });
  8676. if (result === 'Success' && data?.status === 200) {
  8677. if (data.responseText.includes('class="steam-login"')) {
  8678. return false;
  8679. }
  8680. if (data.responseText.includes('class="giveaway-ended"')) {
  8681. return 'Ended';
  8682. }
  8683. return 'Active';
  8684. }
  8685. return false;
  8686. } catch (error) {
  8687. throwError(error, 'leftKeyChecker.giveawaySu');
  8688. return false;
  8689. }
  8690. },
  8691. async giveeClub(link) {
  8692. try {
  8693. const {
  8694. result,
  8695. data
  8696. } = await tools_httpRequest({
  8697. url: link,
  8698. method: 'GET'
  8699. });
  8700. if (result === 'Success' && data?.status === 200) {
  8701. if (data.responseText.includes('class="event-winner"')) {
  8702. return 'Won';
  8703. }
  8704. if (data.responseText.includes('class="event-ended"')) {
  8705. return 'Ended';
  8706. }
  8707. return 'Active';
  8708. }
  8709. return false;
  8710. } catch (error) {
  8711. throwError(error, 'leftKeyChecker.giveeClub');
  8712. return false;
  8713. }
  8714. },
  8715. async gleam(link) {
  8716. try {
  8717. const {
  8718. result,
  8719. data
  8720. } = await tools_httpRequest({
  8721. url: link,
  8722. method: 'GET'
  8723. });
  8724. if (result === 'Success' && data?.status === 200) {
  8725. if (/incentives&quot;:{&quot;[\d]+?&quot;:\[&quot;.+?&quot;\]/.test(data.responseText)) {
  8726. return 'Won';
  8727. }
  8728. const campaignDiv = data.responseText.match(/<div class='popup-blocks-container'[\w\W]+?'>/)?.[0];
  8729. if (!campaignDiv) {
  8730. return false;
  8731. }
  8732. const campaignString = $(campaignDiv).attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  8733. if (!campaignString) {
  8734. return false;
  8735. }
  8736. const {
  8737. campaign
  8738. } = JSON.parse(campaignString);
  8739. if (campaign.banned) {
  8740. return 'Banned';
  8741. }
  8742. if (campaign.finished) {
  8743. return 'Ended';
  8744. }
  8745. if (campaign.paused) {
  8746. return 'Paused';
  8747. }
  8748. if (new Date().getTime() < campaign.starts_at * 1e3) {
  8749. return 'NotStart';
  8750. }
  8751. return 'Active';
  8752. }
  8753. return false;
  8754. } catch (error) {
  8755. throwError(error, 'leftKeyChecker.gleam');
  8756. return false;
  8757. }
  8758. },
  8759. async indieDb(link) {
  8760. try {
  8761. const {
  8762. result,
  8763. data
  8764. } = await tools_httpRequest({
  8765. url: link,
  8766. method: 'GET'
  8767. });
  8768. if (result === 'Success' && data?.status === 200) {
  8769. if (data.responseText.includes('Congrats you WON')) {
  8770. return 'Won';
  8771. }
  8772. if (data.responseText.includes('Giveaway is closed') || data.responseText.includes('next time')) {
  8773. return 'Ended';
  8774. }
  8775. return 'Active';
  8776. }
  8777. return false;
  8778. } catch (error) {
  8779. throwError(error, 'leftKeyChecker.indieDb');
  8780. return false;
  8781. }
  8782. },
  8783. async keyhub(link) {
  8784. try {
  8785. const {
  8786. result,
  8787. data
  8788. } = await tools_httpRequest({
  8789. url: link,
  8790. method: 'GET'
  8791. });
  8792. if (result === 'Success' && data?.status === 200) {
  8793. const keysleft = data.responseText.match(/<span id="keysleft">([\d]+?)<\/span>/)?.[1];
  8794. if (!keysleft) {
  8795. return false;
  8796. }
  8797. if (keysleft === '0') {
  8798. return 'Ended';
  8799. }
  8800. return `Active(${keysleft})`;
  8801. }
  8802. return false;
  8803. } catch (error) {
  8804. throwError(error, 'leftKeyChecker.keyhub');
  8805. return false;
  8806. }
  8807. },
  8808. async opquests(link) {
  8809. try {
  8810. const {
  8811. result,
  8812. data
  8813. } = await tools_httpRequest({
  8814. url: link,
  8815. method: 'GET'
  8816. });
  8817. if (result === 'Success' && data?.status === 200) {
  8818. const keysleft = data.responseText.match(/<div class="">[\s]*?([\d]+?)[\s]*?of/)?.[1];
  8819. if (!keysleft) {
  8820. return false;
  8821. }
  8822. if (keysleft === '0') {
  8823. return 'Ended';
  8824. }
  8825. return `Active(${keysleft})`;
  8826. } else if (data?.status === 404) {
  8827. return 'Ended';
  8828. }
  8829. return false;
  8830. } catch (error) {
  8831. throwError(error, 'leftKeyChecker.opquests');
  8832. return false;
  8833. }
  8834. },
  8835. async itch(link) {
  8836. try {
  8837. const {
  8838. result,
  8839. data
  8840. } = await tools_httpRequest({
  8841. url: link,
  8842. method: 'GET'
  8843. });
  8844. if (result === 'Success' && data?.status === 200) {
  8845. const endDate = data.responseText.match(/{"start_date":"[0-9A-Z-:]+?".*?"end_date":"([0-9A-Z-:]+?)".*?}/)?.[1];
  8846. if (!endDate) {
  8847. return false;
  8848. }
  8849. if (new Date().getTime() > new Date(endDate).getTime()) {
  8850. return 'Ended';
  8851. }
  8852. return `Active(${external_dayjs_default()(endDate).format('YYYY-MM-DD HH:mm:ss')})`;
  8853. }
  8854. return false;
  8855. } catch (error) {
  8856. throwError(error, 'leftKeyChecker.itch');
  8857. return false;
  8858. }
  8859. }
  8860. };
  8861. const website_leftKeyChecker = leftKeyChecker;
  8862. const Keylol_defaultTasksTemplate = {
  8863. steam: {
  8864. groupLinks: [],
  8865. wishlistLinks: [],
  8866. curatorLinks: [],
  8867. curatorLikeLinks: [],
  8868. followLinks: [],
  8869. forumLinks: [],
  8870. announcementLinks: [],
  8871. workshopVoteLinks: [],
  8872. licenseLinks: []
  8873. },
  8874. discord: {
  8875. serverLinks: []
  8876. },
  8877. instagram: {
  8878. userLinks: []
  8879. },
  8880. vk: {
  8881. nameLinks: []
  8882. },
  8883. twitch: {
  8884. channelLinks: []
  8885. },
  8886. reddit: {
  8887. redditLinks: []
  8888. },
  8889. twitter: {
  8890. userLinks: [],
  8891. retweetLinks: []
  8892. },
  8893. youtube: {
  8894. channelLinks: [],
  8895. likeLinks: []
  8896. }
  8897. };
  8898. const Keylol_defaultTasks = JSON.stringify(Keylol_defaultTasksTemplate);
  8899. class Keylol extends website_Website {
  8900. name = 'Keylol';
  8901. socialTasks = JSON.parse(Keylol_defaultTasks);
  8902. undoneTasks = JSON.parse(Keylol_defaultTasks);
  8903. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect' ];
  8904. static test() {
  8905. 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'));
  8906. }
  8907. init() {
  8908. return true;
  8909. }
  8910. after() {
  8911. try {
  8912. const selector = this.name === 'Keylol' ? '#postlist>div[id^="post_"]:first' : 'div.container';
  8913. const mainPost = $(selector);
  8914. const discordLinks = mainPost.find('a[href*="discord.com"]:visible');
  8915. const redditLinks = mainPost.find('a[href*="reddit.com"]:visible');
  8916. const insLinks = mainPost.find('a[href*="instagram.com"]:visible');
  8917. const twitterLinks = mainPost.find('a[href*="twitter.com"]:visible,a[href*="x.com"]:visible');
  8918. const twitchLinks = mainPost.find('a[href*="twitch.tv"]:visible');
  8919. const vkLinks = mainPost.find('a[href*="vk.com"]:visible');
  8920. const steamStoreLinks = mainPost.find('a[href*="store.steampowered.com"]:visible');
  8921. const steamCommunityLinks = mainPost.find('a[href*="steamcommunity.com"]:visible');
  8922. const ytbLinks = mainPost.find('a[href*="youtube.com"]:visible');
  8923. if (discordLinks.length > 0) {
  8924. for (const discordLink of discordLinks) {
  8925. const link = $(discordLink).attr('href');
  8926. if (!(link && /^https?:\/\/discord\.com\/invite\/.+/.test(link))) {
  8927. continue;
  8928. }
  8929. this.#addBtn(discordLink, 'discord', 'serverLinks', link);
  8930. }
  8931. }
  8932. if (redditLinks.length > 0) {
  8933. for (const redditLink of redditLinks) {
  8934. const link = $(redditLink).attr('href');
  8935. if (!(link && /^https?:\/\/www\.reddit\.com\/(r|user)\/.+/.test(link))) {
  8936. continue;
  8937. }
  8938. this.#addBtn(redditLink, 'reddit', 'redditLinks', link);
  8939. }
  8940. }
  8941. if (insLinks.length > 0) {
  8942. for (const insLink of insLinks) {
  8943. const link = $(insLink).attr('href');
  8944. if (!(link && /^https:\/\/www\.instagram\.com\/.+/.test(link))) {
  8945. continue;
  8946. }
  8947. this.#addBtn(insLink, 'instagram', 'userLinks', link);
  8948. }
  8949. }
  8950. if (twitterLinks.length > 0) {
  8951. for (const twitterLink of twitterLinks) {
  8952. const link = $(twitterLink).attr('href');
  8953. if (!(link && /^https:\/\/twitter\.com\/.+/.test(link))) {
  8954. continue;
  8955. }
  8956. if (/https:\/\/twitter\.com\/.*?\/status\/[\d]+/.test(link)) {
  8957. this.#addBtn(twitterLink, 'twitter', 'retweetLinks', link);
  8958. } else {
  8959. this.#addBtn(twitterLink, 'twitter', 'userLinks', link);
  8960. }
  8961. }
  8962. }
  8963. if (twitchLinks.length > 0) {
  8964. for (const twitchLink of twitchLinks) {
  8965. const link = $(twitchLink).attr('href');
  8966. if (!(link && /^https:\/\/(www\.)?twitch\.tv\/.+/.test(link))) {
  8967. continue;
  8968. }
  8969. this.#addBtn(twitchLink, 'twitch', 'channelLinks', link);
  8970. }
  8971. }
  8972. if (vkLinks.length > 0) {
  8973. for (const vkLink of vkLinks) {
  8974. const link = $(vkLink).attr('href');
  8975. if (!(link && /^https:\/\/vk\.com\/.+/.test(link))) {
  8976. continue;
  8977. }
  8978. this.#addBtn(vkLink, 'vk', 'nameLinks', link);
  8979. }
  8980. }
  8981. if (steamStoreLinks.length > 0) {
  8982. for (const steamStoreLink of steamStoreLinks) {
  8983. const link = $(steamStoreLink).attr('href');
  8984. if (!link) {
  8985. continue;
  8986. }
  8987. if (/curator\/[\d]+/.test(link)) {
  8988. this.#addBtn(steamStoreLink, 'steam', 'curatorLinks', link);
  8989. } else if (/(publisher|developer|franchise)\/.+/.test(link)) {
  8990. this.#addBtn(steamStoreLink, 'steam', 'curatorLikeLinks', link);
  8991. } else if (/news(hub)?\/app\/[\d]+\/view\/[\d]+/.test(link)) {
  8992. this.#addBtn(steamStoreLink, 'steam', 'announcementLinks', link);
  8993. } else if (/app\/[\d]+/.test(link)) {
  8994. this.#addBtn(steamStoreLink, 'steam', 'followLinks', link);
  8995. this.#addBtn(steamStoreLink, 'steam', 'wishlistLinks', link);
  8996. }
  8997. }
  8998. }
  8999. if (steamCommunityLinks.length > 0) {
  9000. for (const steamCommunityLink of steamCommunityLinks) {
  9001. const link = $(steamCommunityLink).attr('href');
  9002. if (!link) {
  9003. continue;
  9004. }
  9005. if (/groups\/.+/.test(link)) {
  9006. this.#addBtn(steamCommunityLink, 'steam', 'groupLinks', link);
  9007. } else if (/announcements\/detail\/[\d]+/.test(link)) {
  9008. this.#addBtn(steamCommunityLink, 'steam', 'announcementLinks', link);
  9009. }
  9010. }
  9011. }
  9012. if (ytbLinks.length > 0) {
  9013. for (const ytbLink of ytbLinks) {
  9014. const link = $(ytbLink).attr('href');
  9015. if (!link) {
  9016. continue;
  9017. }
  9018. this.#addBtn(ytbLink, 'youtube', 'channelLinks', link);
  9019. this.#addBtn(ytbLink, 'youtube', 'likeLinks', link);
  9020. }
  9021. }
  9022. 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');
  9023. if (giveawayLinks.length > 0) {
  9024. for (const giveawayLink of giveawayLinks) {
  9025. const link = $(giveawayLink).attr('href');
  9026. if (!link) {
  9027. continue;
  9028. }
  9029. website_leftKeyChecker.classify(link).then(status => {
  9030. if (!status) {
  9031. return;
  9032. }
  9033. if (/^Active/.test(status)) {
  9034. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status active" title="${i18n('Active')}">${status}</font>`);
  9035. return;
  9036. }
  9037. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status not-active" title="${i18n(status)}">${status}</font>`);
  9038. }).catch(error => {
  9039. throwError(error, 'keylol.after -> leftKeyChecker');
  9040. });
  9041. }
  9042. }
  9043. if (this.name === 'Keylol') {
  9044. const asfLinks = mainPost.find('a[href^="#asf"]:visible');
  9045. if (asfLinks.length > 0) {
  9046. for (const asfLink of asfLinks) {
  9047. const link = $(asfLink).attr('href');
  9048. if (!link) {
  9049. continue;
  9050. }
  9051. this.#addBtn($(`a[href="${link}"]`).after('<span style="color: #ccc; margin: 0 -5px 0 5px"> | </span>').next()[0], 'steam', 'licenseLinks', `appid-${link.replace('#asf', '')}`);
  9052. }
  9053. }
  9054. const subLinks = mainPost.find('a[href*="steamdb.info/sub/"]:visible');
  9055. if (subLinks.length > 0) {
  9056. for (const subLink of subLinks) {
  9057. const link = $(subLink).attr('href');
  9058. if (!link) {
  9059. continue;
  9060. }
  9061. const subid = link.match(/^https:\/\/steamdb\.info\/sub\/([\d]+)/)?.[1];
  9062. if (!subid) {
  9063. continue;
  9064. }
  9065. this.#addBtn(subLink, 'steam', 'licenseLinks', `subid-${subid}`);
  9066. }
  9067. }
  9068. const asfLinks2 = mainPost.find('.blockcode:contains("addlicense"):visible');
  9069. if (asfLinks2.length > 0) {
  9070. for (const asfLink of asfLinks2) {
  9071. const appid = [ ...asfLink.innerText.matchAll(/a(pp)?\/([\d]+)/g) ].map(matched => matched?.[2]).filter(id => id) || [];
  9072. if (appid.length > 0) {
  9073. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `appid-${appid.join(',')}`);
  9074. }
  9075. const subid = asfLink.innerText.match(/[\d]+/g)?.filter(matched => !appid.includes(matched));
  9076. if (!subid || subid.length === 0) {
  9077. continue;
  9078. }
  9079. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `subid-${subid.join(',')}`);
  9080. }
  9081. }
  9082. }
  9083. if ($('#threadindex').length > 0) {
  9084. const [ targetNode ] = $('#postlist').children('div[id^="post_"]');
  9085. const config = {
  9086. childList: true
  9087. };
  9088. const observer = new MutationObserver(() => {
  9089. observer.disconnect();
  9090. this.after();
  9091. });
  9092. observer.observe(targetNode, config);
  9093. }
  9094. } catch (error) {
  9095. throwError(error, 'keylol.after');
  9096. }
  9097. }
  9098. classifyTask(action) {
  9099. try {
  9100. this.socialTasks = JSON.parse(Keylol_defaultTasks);
  9101. this.undoneTasks = JSON.parse(Keylol_defaultTasks);
  9102. const selectedBtns = $('.auto-task-keylol[selected="selected"]:visible');
  9103. for (const btn of selectedBtns) {
  9104. const button = $(btn);
  9105. const social = button.attr('data-social');
  9106. const type = button.attr('data-type');
  9107. const link = button.attr('data-link');
  9108. if (!(social && type && link)) {
  9109. continue;
  9110. }
  9111. if (action === 'do') {
  9112. this.undoneTasks[social][type].push(link);
  9113. }
  9114. if (action === 'undo') {
  9115. this.socialTasks[social][type].push(link);
  9116. }
  9117. }
  9118. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9119. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9120. if (window.DEBUG) {
  9121. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9122. }
  9123. return true;
  9124. } catch (error) {
  9125. throwError(error, 'Keylol.classifyTask');
  9126. return false;
  9127. }
  9128. }
  9129. selectAll() {
  9130. try {
  9131. $('.auto-task-keylol:visible').attr('selected', 'selected');
  9132. } catch (error) {
  9133. throwError(error, 'Keylol.selectAll');
  9134. }
  9135. }
  9136. selectNone() {
  9137. try {
  9138. $('.auto-task-keylol:visible').removeAttr('selected');
  9139. } catch (error) {
  9140. throwError(error, 'Keylol.selectNone');
  9141. }
  9142. }
  9143. invertSelect() {
  9144. try {
  9145. $('.auto-task-keylol:visible').each((index, element) => {
  9146. element.getAttribute('selected') ? element.removeAttribute('selected') : element.setAttribute('selected', 'selected');
  9147. });
  9148. } catch (error) {
  9149. throwError(error, 'Keylol.invertSelect');
  9150. }
  9151. }
  9152. #addBtn(before, social, linkType, link) {
  9153. try {
  9154. $(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>`);
  9155. } catch (error) {
  9156. throwError(error, 'keylol.addBtn');
  9157. }
  9158. }
  9159. }
  9160. const website_Keylol = Keylol;
  9161. const Opquests_defaultTasks = {
  9162. steam: {
  9163. groupLinks: [],
  9164. wishlistLinks: [],
  9165. followLinks: [],
  9166. curatorLikeLinks: []
  9167. }
  9168. };
  9169. class Opquests extends website_Website {
  9170. name = 'Opquests';
  9171. undoneTasks = {
  9172. ...Opquests_defaultTasks
  9173. };
  9174. buttons = [ 'doTask', 'verifyTask', 'getKey' ];
  9175. static test() {
  9176. return window.location.host === 'opquests.com';
  9177. }
  9178. async after() {
  9179. try {
  9180. if (!this.#checkLogin()) {
  9181. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9182. }
  9183. const opquestsVerifyTasks = GM_getValue('opquestsVerifyTasks') || [];
  9184. if (opquestsVerifyTasks.length > 0) {
  9185. const taskId = opquestsVerifyTasks.pop();
  9186. GM_setValue('opquestsVerifyTasks', opquestsVerifyTasks);
  9187. const [ verifyBtn ] = $(`#task_id[value="${taskId}"]`).parent().find('button[type="button"]').has('i.fa-check');
  9188. if (verifyBtn) {
  9189. verifyBtn.click();
  9190. return;
  9191. }
  9192. this.after();
  9193. return;
  9194. }
  9195. if (GM_getValue('opquestsVerifyTasks')) {
  9196. GM_deleteValue('opquestsVerifyTasks');
  9197. }
  9198. } catch (error) {
  9199. throwError(error, 'Opquests.after');
  9200. }
  9201. }
  9202. init() {
  9203. try {
  9204. const logStatus = scripts_echoLog({
  9205. text: i18n('initing')
  9206. });
  9207. if ($('a[href*="/auth/redirect"]').length > 0) {
  9208. window.open('/auth/redirect', '_self');
  9209. logStatus.warning(i18n('needLogin'));
  9210. return false;
  9211. }
  9212. if (!this.#getGiveawayId()) {
  9213. return false;
  9214. }
  9215. this.initialized = true;
  9216. logStatus.success();
  9217. return true;
  9218. } catch (error) {
  9219. throwError(error, 'Opquests.init');
  9220. return false;
  9221. }
  9222. }
  9223. async classifyTask(action) {
  9224. try {
  9225. if (action === 'undo') {
  9226. scripts_echoLog({
  9227. text: i18n('cannotUndo')
  9228. });
  9229. return false;
  9230. }
  9231. const logStatus = scripts_echoLog({
  9232. text: i18n('getTasksInfo')
  9233. });
  9234. const tasks = $('.w-full:contains("Validate") .items-center');
  9235. for (const task of tasks) {
  9236. const link = $(task).find('a:contains("Open")').attr('href');
  9237. const taskDes = $(task).find('div').eq(1).text().trim();
  9238. if (!link) {
  9239. continue;
  9240. }
  9241. if (/steamcommunity\.com\/groups\//.test(link)) {
  9242. this.undoneTasks.steam.groupLinks.push(link);
  9243. } else if (/store\.steampowered\.com\/app\//.test(link)) {
  9244. if (/wishlist/gim.test(taskDes)) {
  9245. this.undoneTasks.steam.wishlistLinks.push(link);
  9246. } else if (/follow/gim.test(taskDes)) {
  9247. this.undoneTasks.steam.followLinks.push(link);
  9248. }
  9249. } else if (/store\.steampowered\.com\/(publisher|developer|curator)\//.test(link) && /follow/gim.test(taskDes)) {
  9250. this.undoneTasks.steam.curatorLikeLinks.push(link);
  9251. } else {
  9252. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  9253. }
  9254. }
  9255. logStatus.success();
  9256. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9257. if (window.DEBUG) {
  9258. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9259. }
  9260. return true;
  9261. } catch (error) {
  9262. throwError(error, 'Opquests.classifyTask');
  9263. return false;
  9264. }
  9265. }
  9266. async verifyTask() {
  9267. try {
  9268. if (!this.initialized) {
  9269. this.init();
  9270. }
  9271. const tasks = $.makeArray($('.items-center').has('input[name="task_id"]')).map(ele => $(ele).find('input[name="task_id"]').val());
  9272. GM_setValue('opquestsVerifyTasks', tasks);
  9273. await this.#confirm();
  9274. this.after();
  9275. return true;
  9276. } catch (error) {
  9277. throwError(error, 'Opquests.verifyTask');
  9278. return false;
  9279. }
  9280. }
  9281. async #confirm() {
  9282. try {
  9283. const logStatus = scripts_echoLog({
  9284. html: `<li>${i18n('confirmingTask')}...<font></font></li>`
  9285. });
  9286. const {
  9287. result,
  9288. statusText,
  9289. status,
  9290. data
  9291. } = await tools_httpRequest({
  9292. url: `https://opquests.com/quests/${this.giveawayId}?confirm=1`,
  9293. method: 'GET',
  9294. nochche: true,
  9295. headers: {
  9296. origin: 'https://opquests.com',
  9297. referer: `https://opquests.com/warning?id=${this.giveawayId}`
  9298. }
  9299. });
  9300. if (result === 'Success') {
  9301. if (data?.status === 200) {
  9302. logStatus.success();
  9303. return true;
  9304. }
  9305. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9306. return false;
  9307. }
  9308. logStatus.error(`${result}:${statusText}(${status})`);
  9309. return false;
  9310. } catch (error) {
  9311. throwError(error, 'Opquests.confirm');
  9312. return false;
  9313. }
  9314. }
  9315. async getKey(isButton) {
  9316. try {
  9317. const logStatus = scripts_echoLog({
  9318. text: i18n('gettingKey')
  9319. });
  9320. const {
  9321. result,
  9322. statusText,
  9323. status,
  9324. data
  9325. } = await tools_httpRequest({
  9326. url: 'https://opquests.com/keys',
  9327. method: 'GET'
  9328. });
  9329. if (result === 'Success') {
  9330. if (data?.responseText) {
  9331. const key = $(data?.responseText).find(`div.items-center:contains("${$('h1.font-bold').text().trim().replace(' Quest', '')}")`).find('div.font-bold').next().text();
  9332. if (!key) {
  9333. logStatus.error('Error: Key was not found');
  9334. if (isButton) {
  9335. window.open('https://opquests.com/keys', '_self');
  9336. }
  9337. return false;
  9338. }
  9339. logStatus.success();
  9340. scripts_echoLog({}).success(key);
  9341. return true;
  9342. }
  9343. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9344. return false;
  9345. }
  9346. logStatus.error(`${result}:${statusText}(${status})`);
  9347. return false;
  9348. } catch (error) {
  9349. throwError(error, 'Opquests.getGiveawayId');
  9350. return false;
  9351. }
  9352. }
  9353. #getGiveawayId() {
  9354. try {
  9355. const giveawayId = window.location.href.match(/quests\/([\d]+)/)?.[1];
  9356. if (giveawayId) {
  9357. this.giveawayId = giveawayId;
  9358. return true;
  9359. }
  9360. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  9361. return false;
  9362. } catch (error) {
  9363. throwError(error, 'Opquests.getGiveawayId');
  9364. return false;
  9365. }
  9366. }
  9367. #checkLogin() {
  9368. try {
  9369. if (!globalOptions.other.checkLogin) {
  9370. return true;
  9371. }
  9372. if ($('a[href*="/auth/redirect"]').length > 0) {
  9373. window.open('/auth/redirect', '_self');
  9374. }
  9375. return true;
  9376. } catch (error) {
  9377. throwError(error, 'Opquests.checkLogin');
  9378. return false;
  9379. }
  9380. }
  9381. }
  9382. const website_Opquests = Opquests;
  9383. const Gleam_defaultTasksTemplate = {
  9384. steam: {
  9385. groupLinks: [],
  9386. wishlistLinks: [],
  9387. followLinks: [],
  9388. curatorLinks: [],
  9389. curatorLikeLinks: []
  9390. },
  9391. twitter: {
  9392. userLinks: [],
  9393. retweetLinks: []
  9394. },
  9395. twitch: {
  9396. channelLinks: []
  9397. },
  9398. discord: {
  9399. serverLinks: []
  9400. },
  9401. youtube: {
  9402. channelLinks: []
  9403. },
  9404. extra: {
  9405. gleam: []
  9406. }
  9407. };
  9408. const Gleam_defaultTasks = JSON.stringify(Gleam_defaultTasksTemplate);
  9409. class Gleam extends website_Website {
  9410. name = 'Gleam';
  9411. undoneTasks = JSON.parse(Gleam_defaultTasks);
  9412. socialTasks = JSON.parse(Gleam_defaultTasks);
  9413. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  9414. static test() {
  9415. return window.location.host === 'gleam.io';
  9416. }
  9417. before() {
  9418. try {
  9419. unsafeWindow.confirm = () => {};
  9420. unsafeWindow.alert = () => {};
  9421. unsafeWindow.prompt = () => {};
  9422. } catch (error) {
  9423. throwError(error, 'Gleam.before');
  9424. }
  9425. }
  9426. async after() {
  9427. try {
  9428. if (window.location.search.includes('8b07d23f4bfa65f9')) {
  9429. const checkComplete = setInterval(() => {
  9430. if ($('.entry-content .entry-method i.fa-check').length > 0) {
  9431. clearInterval(checkComplete);
  9432. window.close();
  9433. }
  9434. });
  9435. for (const task of $('.entry-content .entry-method')) {
  9436. const taskInfo = $(task).find('.user-links');
  9437. const expandInfo = $(task).find('.expandable');
  9438. const aElements = expandInfo.find('a.btn,a:contains(Continue),button:contains(Continue)');
  9439. if (aElements.length > 0) {
  9440. for (const element of aElements) {
  9441. const $element = $(element);
  9442. const href = $element.attr('href');
  9443. $element.removeAttr('href')[0].click();
  9444. $element.attr('href', href);
  9445. await delay(1e3);
  9446. }
  9447. }
  9448. taskInfo[0].click();
  9449. await delay(1e3);
  9450. }
  9451. scripts_echoLog({}).warning(i18n('gleamTaskNotice'));
  9452. } else if (!await this.#checkLeftKey()) {
  9453. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  9454. }
  9455. } catch (error) {
  9456. throwError(error, 'Gleam.after');
  9457. }
  9458. }
  9459. init() {
  9460. try {
  9461. const logStatus = scripts_echoLog({
  9462. text: i18n('initing')
  9463. });
  9464. if (!this.#getGiveawayId()) {
  9465. return false;
  9466. }
  9467. this.initialized = true;
  9468. logStatus.success();
  9469. return true;
  9470. } catch (error) {
  9471. throwError(error, 'Gleam.init');
  9472. return false;
  9473. }
  9474. }
  9475. async classifyTask(action) {
  9476. try {
  9477. const logStatus = scripts_echoLog({
  9478. text: i18n('getTasksInfo')
  9479. });
  9480. if (action === 'undo') {
  9481. this.socialTasks = GM_getValue(`gleamTasks-${this.giveawayId}`)?.tasks || JSON.parse(Gleam_defaultTasks);
  9482. }
  9483. const tasks = $('.entry-content .entry-method');
  9484. for (const task of tasks) {
  9485. const $task = $(task);
  9486. if (action === 'do' && $task.find('i.fa-question').length === 0) {
  9487. continue;
  9488. }
  9489. const socialIcon = $task.find('.icon-wrapper i');
  9490. const taskInfo = $task.find('.user-links');
  9491. const taskText = taskInfo.text().trim();
  9492. const expandInfo = $task.find('.expandable');
  9493. const aElements = expandInfo.find('a.btn');
  9494. if (aElements.length > 0) {
  9495. for (const element of aElements) {
  9496. const $element = $(element);
  9497. const href = $element.attr('href');
  9498. $element.removeAttr('href')[0].click();
  9499. $element.attr('href', href);
  9500. }
  9501. }
  9502. if (socialIcon.hasClass('fa-twitter') || socialIcon.hasClass('fa-x-twitter')) {
  9503. const link = $task.find('a[href^="https://twitter.com/"],a[href^="https://x.com/"]').attr('href');
  9504. if (!link) {
  9505. continue;
  9506. }
  9507. if (/follow/gi.test(taskText)) {
  9508. if (action === 'undo') {
  9509. this.socialTasks.twitter.userLinks.push(link);
  9510. }
  9511. if (action === 'do') {
  9512. this.undoneTasks.twitter.userLinks.push(link);
  9513. }
  9514. } else if (/retweet/gim.test(taskText)) {
  9515. if (action === 'undo') {
  9516. this.socialTasks.twitter.retweetLinks.push(link);
  9517. }
  9518. if (action === 'do') {
  9519. this.undoneTasks.twitter.retweetLinks.push(link);
  9520. }
  9521. }
  9522. } else if (socialIcon.hasClass('fa-twitch')) {
  9523. if (/follow/gim.test(taskText)) {
  9524. const link = $task.find('a[href^="https://twitch.tv/"]').attr('href');
  9525. if (!link) {
  9526. continue;
  9527. }
  9528. if (action === 'undo') {
  9529. this.socialTasks.twitch.channelLinks.push(link);
  9530. }
  9531. if (action === 'do') {
  9532. this.undoneTasks.twitch.channelLinks.push(link);
  9533. }
  9534. }
  9535. } else if (socialIcon.hasClass('fa-discord')) {
  9536. if (/join/gim.test(taskText)) {
  9537. let link = $task.find('a[href^="https://discord.com/invite/"]').attr('href');
  9538. if (!link) {
  9539. const ggLink = $task.find('a[href^="https://discord.gg/"]').attr('href')?.match(/discord\.gg\/([^/]+)/)?.[1];
  9540. if (!ggLink) {
  9541. continue;
  9542. }
  9543. link = `https://discord.com/invite/${ggLink}`;
  9544. }
  9545. if (action === 'undo') {
  9546. this.socialTasks.discord.serverLinks.push(link);
  9547. }
  9548. if (action === 'do') {
  9549. this.undoneTasks.discord.serverLinks.push(link);
  9550. }
  9551. }
  9552. } else if (socialIcon.hasClass('fa-external-link-square-alt')) {
  9553. continue;
  9554. } else if (socialIcon.hasClass('fa-youtube')) {
  9555. if (/subscribe/gim.test(taskText)) {
  9556. const link = $task.find('a[href^="https://www.youtube.com/channel/"]').attr('href');
  9557. if (!link) {
  9558. continue;
  9559. }
  9560. if (action === 'undo') {
  9561. this.socialTasks.youtube.channelLinks.push(link);
  9562. }
  9563. if (action === 'do') {
  9564. this.undoneTasks.youtube.channelLinks.push(link);
  9565. }
  9566. }
  9567. } else if (socialIcon.attr('class')?.includes('steam')) {
  9568. if (/join.*group/gi.test(taskText)) {
  9569. const link = $task.find('a[href^="https://steamcommunity.com/groups/"]').attr('href');
  9570. if (!link) {
  9571. continue;
  9572. }
  9573. if (action === 'undo') {
  9574. this.socialTasks.steam.groupLinks.push(link);
  9575. }
  9576. if (action === 'do') {
  9577. this.undoneTasks.steam.groupLinks.push(link);
  9578. }
  9579. } else if (/follow.*curator/gi.test(taskText)) {
  9580. const link = $task.find('a[href^="https://store.steampowered.com/curator/"]').attr('href');
  9581. if (!link) {
  9582. continue;
  9583. }
  9584. if (action === 'undo') {
  9585. this.socialTasks.steam.curatorLinks.push(link);
  9586. }
  9587. if (action === 'do') {
  9588. this.undoneTasks.steam.curatorLinks.push(link);
  9589. }
  9590. }
  9591. } else if (socialIcon.hasClass('fa-bullhorn') && /Complete|Increase/gi.test(taskText)) {
  9592. if (action !== 'do') {
  9593. continue;
  9594. }
  9595. const gleamLink = await this.#getGleamLink(taskText);
  9596. if (!gleamLink) {
  9597. continue;
  9598. }
  9599. this.undoneTasks.extra.gleam.push(gleamLink);
  9600. } 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 {
  9601. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskText}`);
  9602. }
  9603. }
  9604. logStatus.success();
  9605. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9606. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9607. if (window.DEBUG) {
  9608. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9609. }
  9610. GM_setValue(`gleamTasks-${this.giveawayId}`, {
  9611. tasks: this.socialTasks,
  9612. time: new Date().getTime()
  9613. });
  9614. return true;
  9615. } catch (error) {
  9616. throwError(error, 'Gleam.classifyTask');
  9617. return false;
  9618. }
  9619. }
  9620. async extraDoTask({
  9621. gleam
  9622. }) {
  9623. try {
  9624. const pro = [];
  9625. for (const link of gleam) {
  9626. pro.push(this.#doGleamTask(link));
  9627. }
  9628. return Promise.all(pro).then(() => true);
  9629. } catch (error) {
  9630. throwError(error, 'Gleam.extraDoTask');
  9631. return false;
  9632. }
  9633. }
  9634. async verifyTask() {
  9635. try {
  9636. scripts_echoLog({
  9637. text: `${i18n('verifyingTask')}...`
  9638. });
  9639. const tasks = $('.entry-content .entry-method');
  9640. unsafeWindow._OxA = '_OxA';
  9641. for (const task of tasks) {
  9642. if ($('[campaign-key="campaign.key"]').length > 0) {
  9643. return scripts_echoLog({
  9644. text: i18n('campaign')
  9645. });
  9646. }
  9647. const $task = $(task);
  9648. if ($task.find('i.fa-question').length === 0) {
  9649. continue;
  9650. }
  9651. const taskInfo = $task.find('.user-links');
  9652. taskInfo[0].click();
  9653. const aElements = $task.find('.expandable').find('a.btn');
  9654. if (aElements.length > 0) {
  9655. for (const element of aElements) {
  9656. const $element = $(element);
  9657. const href = $element.attr('href');
  9658. $element.removeAttr('href')[0].click();
  9659. $element.attr('href', href);
  9660. }
  9661. }
  9662. unsafeWindow.$hookTimer?.setSpeed(1e3);
  9663. const visitBtn = $task.find('.expandable').find('span:contains(more seconds),button:contains(more seconds)').filter(':visible');
  9664. if (visitBtn.length > 0 && unsafeWindow.$hookTimer) {
  9665. const newTab = GM_openInTab('', {
  9666. active: true
  9667. });
  9668. await delay(1e3);
  9669. newTab?.close();
  9670. window.focus();
  9671. }
  9672. await delay(3e3);
  9673. unsafeWindow.$hookTimer?.setSpeed(1);
  9674. const expandInfo = $task.find('.expandable');
  9675. const [ input ] = expandInfo.find('input');
  9676. if (input) {
  9677. const evt = new Event('input', {
  9678. bubbles: true,
  9679. cancelable: true,
  9680. composed: true
  9681. });
  9682. const valuelimit = [ ...expandInfo.text().matchAll(/"(.+?)"/g) ].at(-1)?.[1];
  9683. input.value = valuelimit || 'vloot';
  9684. input.dispatchEvent(evt);
  9685. await delay(1e3);
  9686. }
  9687. await this.#checkSync();
  9688. const continueBtn = $task.find('.expandable').find('span:contains(Continue),button:contains(Continue)');
  9689. for (const button of continueBtn) {
  9690. button.click();
  9691. await delay(500);
  9692. await this.#checkSync();
  9693. }
  9694. }
  9695. scripts_echoLog({
  9696. text: i18n('verifiedGleamTasks')
  9697. });
  9698. } catch (error) {
  9699. throwError(error, 'Gleam.verifyTask');
  9700. return false;
  9701. }
  9702. }
  9703. async #checkSync() {
  9704. try {
  9705. return await new Promise(resolve => {
  9706. const checker = setInterval(() => {
  9707. if ($('.entry-content .entry-method i.fa-sync').length === 0) {
  9708. clearInterval(checker);
  9709. resolve(true);
  9710. }
  9711. }, 500);
  9712. });
  9713. } catch (error) {
  9714. throwError(error, 'Gleam.checkSync');
  9715. return false;
  9716. }
  9717. }
  9718. async #doGleamTask(link) {
  9719. try {
  9720. const logStatus = scripts_echoLog({
  9721. text: i18n('doingGleamTask')
  9722. });
  9723. return await new Promise(resolve => {
  9724. GM_openInTab(`${link}?8b07d23f4bfa65f9`, {
  9725. active: true,
  9726. insert: true,
  9727. setParent: true
  9728. }).onclose = () => {
  9729. logStatus.success();
  9730. resolve(true);
  9731. };
  9732. });
  9733. } catch (error) {
  9734. throwError(error, 'Gleam.doGleamTask');
  9735. return false;
  9736. }
  9737. }
  9738. #getGiveawayId() {
  9739. try {
  9740. const giveawayId = window.location.pathname;
  9741. if (giveawayId) {
  9742. this.giveawayId = giveawayId;
  9743. return true;
  9744. }
  9745. scripts_echoLog({
  9746. text: i18n('getFailed', 'GiveawayId')
  9747. });
  9748. return false;
  9749. } catch (error) {
  9750. throwError(error, 'Gleam.getGiveawayId');
  9751. return false;
  9752. }
  9753. }
  9754. async #getGleamLink(title) {
  9755. try {
  9756. const logStatus = scripts_echoLog({
  9757. text: i18n('gettingGleamLink')
  9758. });
  9759. const {
  9760. result,
  9761. statusText,
  9762. status,
  9763. data
  9764. } = await tools_httpRequest({
  9765. url: 'https://www.vloot.io/api/v1/giveaways',
  9766. method: 'GET',
  9767. responseType: 'json'
  9768. });
  9769. if (result === 'Success') {
  9770. if (data?.status === 200 && data?.response?.Success === true && data?.response?.Data) {
  9771. const {
  9772. link
  9773. } = data.response.Data.find(giveaway => title.replace(/[\s]/g, '').toLowerCase().includes(giveaway.title.replace(/[\s]/g, '').toLowerCase())) || {};
  9774. if (link) {
  9775. logStatus.success();
  9776. return link;
  9777. }
  9778. logStatus.error(`Error:${i18n('getLinkFailed')}`);
  9779. return false;
  9780. }
  9781. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9782. return false;
  9783. }
  9784. logStatus.error(`${result}:${statusText}(${status})`);
  9785. return false;
  9786. } catch (error) {
  9787. throwError(error, 'Gleam.getGleamLink');
  9788. return false;
  9789. }
  9790. }
  9791. async #checkLeftKey() {
  9792. try {
  9793. if (!globalOptions.other.checkLeftKey) {
  9794. return true;
  9795. }
  9796. const campaignString = $('div.popup-blocks-container').attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  9797. if (!campaignString) {
  9798. return false;
  9799. }
  9800. const {
  9801. campaign,
  9802. incentive
  9803. } = JSON.parse(campaignString);
  9804. const controllerString = $('div.campaign.reward').attr('ng-init')?.match(/initContestant\(([\w\W]+?)\);/)?.[1];
  9805. let ownedKey = false;
  9806. if (controllerString) {
  9807. if (JSON.parse(controllerString).contestant?.claims?.incentives?.[incentive.id]?.length) {
  9808. ownedKey = true;
  9809. }
  9810. }
  9811. if (campaign.banned || campaign.finished && !ownedKey || campaign.paused || new Date().getTime() < campaign.starts_at * 1e3) {
  9812. await external_Swal_default().fire({
  9813. icon: 'warning',
  9814. title: i18n('notice'),
  9815. text: i18n('giveawayNotWork'),
  9816. confirmButtonText: i18n('confirm'),
  9817. cancelButtonText: i18n('cancel'),
  9818. showCancelButton: true
  9819. }).then(({
  9820. value
  9821. }) => {
  9822. if (value) {
  9823. window.close();
  9824. }
  9825. });
  9826. }
  9827. return true;
  9828. } catch (error) {
  9829. throwError(error, 'Gleam.checkLeftKey');
  9830. return false;
  9831. }
  9832. }
  9833. }
  9834. const website_Gleam = Gleam;
  9835. const SweepWidget_defaultOptions = {
  9836. username: '',
  9837. email: ''
  9838. };
  9839. class SweepWidget extends website_Website {
  9840. name = 'SweepWidget';
  9841. options = {
  9842. ...SweepWidget_defaultOptions,
  9843. ...GM_getValue('SweepWidgetOptions')
  9844. };
  9845. buttons = [ 'doTask' ];
  9846. static test() {
  9847. return /^https?:\/\/sweepwidget\.com\/view\/[\d]+/.test(window.location.href);
  9848. }
  9849. async after() {
  9850. try {
  9851. if (!this.#checkLogin()) {
  9852. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9853. }
  9854. } catch (error) {
  9855. throwError(error, 'SweepWidget.after');
  9856. }
  9857. }
  9858. init() {
  9859. try {
  9860. const logStatus = scripts_echoLog({
  9861. text: i18n('initing')
  9862. });
  9863. if (!this.#checkLogin()) {
  9864. logStatus.warning(i18n('needLogin'));
  9865. return false;
  9866. }
  9867. if (!this.#getGiveawayId()) {
  9868. return false;
  9869. }
  9870. this.initialized = true;
  9871. logStatus.success();
  9872. return true;
  9873. } catch (error) {
  9874. throwError(error, 'SweepWidget.init');
  9875. return false;
  9876. }
  9877. }
  9878. classifyTask() {
  9879. return true;
  9880. }
  9881. async doTask() {
  9882. try {
  9883. if ($('#unlock_rewards_main_wrapper').length === 0) {
  9884. if ($('input[name="sw__login_name"]:visible').length > 0) {
  9885. $('input[name="sw__login_name"]').val(this.options.username);
  9886. }
  9887. if ($('input[name="sw__login_email"]:visible').length > 0) {
  9888. $('input[name="sw__login_email"]').val(this.options.email);
  9889. }
  9890. if ($('#sw_login_button:visible').length > 0) {
  9891. $('#sw_login_button')[0].click();
  9892. }
  9893. if (!await this.#checkEnter()) {
  9894. return false;
  9895. }
  9896. }
  9897. const logStatus = scripts_echoLog({
  9898. text: i18n('SweepWidgetNotice')
  9899. });
  9900. const tasks = $('#sw_inner_entry_methods_l2_wrapper>div.sw_entry');
  9901. for (const task of tasks) {
  9902. const $task = $(task);
  9903. if ($task.find('i.fa-check:visible').length > 0) {
  9904. continue;
  9905. }
  9906. const title = $task.find('.sw_text_inner');
  9907. title[0].click();
  9908. const aElement = $task.find('a.sw_link');
  9909. const link = aElement.attr('href');
  9910. aElement.attr('href', '#a').attr('target', '_self');
  9911. aElement[0]?.click();
  9912. await delay(300);
  9913. aElement.attr('href', link).attr('target', '_blank');
  9914. $task.find('input[type="text"]').val('test');
  9915. const verifyBtn = $task.find('input.sw_verify');
  9916. if (verifyBtn.prop('disabled') === true) {
  9917. title[0].click();
  9918. await delay(300);
  9919. title[0].click();
  9920. await delay(300);
  9921. }
  9922. $task.find('input.sw_verify').removeAttr('disabled')[0]?.click();
  9923. await this.#checkFinish($task);
  9924. await delay(parseInt(`${Math.random() * (3e3 - 1e3 + 1) + 1e3}`, 10));
  9925. }
  9926. logStatus.success();
  9927. return true;
  9928. } catch (error) {
  9929. throwError(error, 'SweepWidget.doTask');
  9930. return false;
  9931. }
  9932. }
  9933. #checkLogin() {
  9934. try {
  9935. if ($('#twitter_login_button').length > 0) {
  9936. $('#twitter_login_button')[0].click();
  9937. }
  9938. return true;
  9939. } catch (error) {
  9940. throwError(error, 'SweepWidget.checkLogin');
  9941. return false;
  9942. }
  9943. }
  9944. #getGiveawayId() {
  9945. try {
  9946. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  9947. if (giveawayId) {
  9948. this.giveawayId = giveawayId;
  9949. return true;
  9950. }
  9951. scripts_echoLog({
  9952. text: i18n('getFailed', 'GiveawayId')
  9953. });
  9954. return false;
  9955. } catch (error) {
  9956. throwError(error, 'SweepWidget.getGiveawayId');
  9957. return false;
  9958. }
  9959. }
  9960. async #checkEnter() {
  9961. try {
  9962. return new Promise(resolve => {
  9963. const checker = setInterval(() => {
  9964. if ($('#unlock_rewards_main_wrapper').length > 0) {
  9965. clearInterval(checker);
  9966. resolve(true);
  9967. }
  9968. }, 500);
  9969. });
  9970. } catch (error) {
  9971. throwError(error, 'SweepWidget.checkEnter');
  9972. return false;
  9973. }
  9974. }
  9975. async #checkFinish($task) {
  9976. try {
  9977. return new Promise(resolve => {
  9978. const checker = setInterval(() => {
  9979. if ($task.find('i.fa-check:visible').length > 0 || $task.find('.sw_entry_input:visible').length === 0) {
  9980. clearInterval(checker);
  9981. resolve(true);
  9982. }
  9983. }, 500);
  9984. });
  9985. } catch (error) {
  9986. throwError(error, 'SweepWidget.checkFinish');
  9987. return false;
  9988. }
  9989. }
  9990. }
  9991. const website_SweepWidget = SweepWidget;
  9992. const defaultWhiteList = {
  9993. discord: {
  9994. servers: []
  9995. },
  9996. instagram: {
  9997. users: []
  9998. },
  9999. twitch: {
  10000. channels: []
  10001. },
  10002. twitter: {
  10003. users: [],
  10004. retweets: [],
  10005. likes: []
  10006. },
  10007. vk: {
  10008. names: []
  10009. },
  10010. youtube: {
  10011. channels: [],
  10012. likes: []
  10013. },
  10014. reddit: {
  10015. reddits: []
  10016. },
  10017. steam: {
  10018. groups: [],
  10019. officialGroups: [],
  10020. wishlists: [],
  10021. follows: [],
  10022. forums: [],
  10023. workshops: [],
  10024. curators: [],
  10025. workshopVotes: [],
  10026. curatorLikes: [],
  10027. announcements: [],
  10028. licenses: [],
  10029. playtests: []
  10030. }
  10031. };
  10032. const link2id = async function(type) {
  10033. try {
  10034. const link = $('#socialLink').val();
  10035. let id = '';
  10036. switch (type) {
  10037. case 'discord.servers':
  10038. id = link.match(/invite\/(.+)/)?.[1] || '';
  10039. break;
  10040.  
  10041. case 'instagram.users':
  10042. id = link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1] || '';
  10043. break;
  10044.  
  10045. case 'twitch.channels':
  10046. id = link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2] || '';
  10047. break;
  10048.  
  10049. case 'twitter.users':
  10050. id = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || '';
  10051. break;
  10052.  
  10053. case 'twitter.retweets':
  10054. id = link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1] || '';
  10055. break;
  10056.  
  10057. case 'vk.names':
  10058. id = link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1] || '';
  10059. break;
  10060.  
  10061. case 'youtube.channels':
  10062. id = (await getInfo(link, 'channel'))?.params?.channelId || '';
  10063. break;
  10064.  
  10065. case 'youtube.likes':
  10066. id = (await getInfo(link, 'likeVideo'))?.params?.videoId || '';
  10067. break;
  10068.  
  10069. case 'reddit.reddits':
  10070. id = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1] || link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1] || '';
  10071. break;
  10072.  
  10073. case 'steam.groups':
  10074. id = link.match(/groups\/(.+)\/?/)?.[1] || '';
  10075. break;
  10076.  
  10077. case 'steam.wishlists':
  10078. case 'steam.follows':
  10079. case 'steam.forums':
  10080. id = link.match(/app\/([\d]+)/)?.[1] || '';
  10081. break;
  10082.  
  10083. case 'steam.workshops':
  10084. id = link.match(/\?id=([\d]+)/)?.[1] || '';
  10085. break;
  10086.  
  10087. case 'steam.curators':
  10088. {
  10089. if (link.includes('curator')) {
  10090. id = link.match(/curator\/([\d]+)/)?.[1] || '';
  10091. } else {
  10092. const param = link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3);
  10093. if (!param || param.length !== 2) {
  10094. break;
  10095. }
  10096. const steam = new social_Steam();
  10097. if (await steam.init()) {
  10098. id = await steam.getCuratorId(param[0], param[1]) || '';
  10099. }
  10100. }
  10101. }
  10102. break;
  10103. }
  10104. return id;
  10105. } catch (error) {
  10106. throwError(error, 'link2id');
  10107. return i18n('getFailed', 'id');
  10108. }
  10109. };
  10110. const disabledType = {
  10111. steam: [ 'workshopVotes', 'curatorLikes', 'announcements' ],
  10112. twitter: [ 'likes' ]
  10113. };
  10114. const assignWhiteList = whiteList => {
  10115. try {
  10116. const newWhiteList = {};
  10117. for (const [ key, value ] of Object.entries(defaultWhiteList)) {
  10118. newWhiteList[key] = {
  10119. ...value,
  10120. ...whiteList[key]
  10121. };
  10122. }
  10123. return newWhiteList;
  10124. } catch (error) {
  10125. throwError(error, 'assignWhiteList');
  10126. return defaultWhiteList;
  10127. }
  10128. };
  10129. const whiteListOptions = function(showType) {
  10130. try {
  10131. const whiteList = assignWhiteList(GM_getValue('whiteList') || {});
  10132. let whiteListOptionsForm = `<form id="whiteListForm" class="auto-task-form">
  10133. <table class="auto-task-table"><thead><tr><td>${i18n('website')}</td><td>${i18n('type')}</td><td>${i18n('edit')}</td></tr></thead><tbody>`;
  10134. for (const [ social, types ] of Object.entries(whiteList)) {
  10135. 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('');
  10136. }
  10137. whiteListOptionsForm += '</tbody></table></form>';
  10138. if (showType === 'swal') {
  10139. external_Swal_default().fire({
  10140. title: i18n('whiteListOptions'),
  10141. html: whiteListOptionsForm,
  10142. showConfirmButton: false,
  10143. showCloseButton: true
  10144. });
  10145. } else {
  10146. $('body').append(`<h2>${i18n('whiteList')}</h2>${whiteListOptionsForm}`);
  10147. }
  10148. $('.editWhiteList').on('click', function() {
  10149. const value = $(this).attr('data-value');
  10150. if (!value) {
  10151. return;
  10152. }
  10153. const [ social, type ] = value.split('.');
  10154. if (!whiteList?.[social]?.[type]) {
  10155. scripts_echoLog({}).warning(i18n('whiteListNotFound', value));
  10156. return;
  10157. }
  10158. external_Swal_default().fire({
  10159. title: i18n('changeWhiteListOption', value),
  10160. input: 'textarea',
  10161. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10162. <button id="link2id" data-type="${value}" class="swal2-confirm swal2-styled">获取id</button>
  10163. <p style="margin-bottom:0 !important;">在下方填写白名单,每行一个</p>`,
  10164. inputValue: whiteList[social][type].join('\n'),
  10165. showConfirmButton: true,
  10166. confirmButtonText: i18n('save'),
  10167. showCancelButton: true,
  10168. cancelButtonText: i18n('close'),
  10169. showDenyButton: true,
  10170. denyButtonText: i18n('return')
  10171. }).then(({
  10172. isDenied,
  10173. isConfirmed,
  10174. value
  10175. }) => {
  10176. if (isDenied) {
  10177. if (showType === 'swal') {
  10178. whiteListOptions(showType);
  10179. }
  10180. return;
  10181. } else if (isConfirmed) {
  10182. whiteList[social][type] = value.split('\n');
  10183. GM_setValue('whiteList', whiteList);
  10184. external_Swal_default().fire({
  10185. title: i18n('changeWhiteListSuccess'),
  10186. icon: 'success'
  10187. });
  10188. }
  10189. });
  10190. $('#link2id').on('click', async function() {
  10191. const type = $(this).attr('data-type');
  10192. $('#socialLink').val(await link2id(type));
  10193. });
  10194. });
  10195. } catch (error) {
  10196. throwError(error, 'whiteListOptions');
  10197. }
  10198. };
  10199. const whiteList = whiteListOptions;
  10200. const setGistData = async (token, gistId, fileName, content) => {
  10201. try {
  10202. const logStatus = scripts_echoLog({
  10203. text: i18n('settingData')
  10204. });
  10205. const contentData = JSON.stringify({
  10206. files: {
  10207. [fileName]: {
  10208. content: JSON.stringify(content)
  10209. }
  10210. }
  10211. });
  10212. const {
  10213. result,
  10214. statusText,
  10215. status,
  10216. data
  10217. } = await tools_httpRequest({
  10218. url: `https://api.github.com/gists/${gistId}`,
  10219. headers: {
  10220. Accept: 'application/vnd.github.v3+json',
  10221. Authorization: `token ${token}`
  10222. },
  10223. data: contentData,
  10224. responseType: 'json',
  10225. method: 'POST',
  10226. timeout: 3e4
  10227. });
  10228. if (result === 'Success') {
  10229. if (data?.status === 200 && data.response.files?.[fileName]?.content === JSON.stringify(content)) {
  10230. logStatus.success();
  10231. return true;
  10232. }
  10233. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10234. return false;
  10235. }
  10236. logStatus.error(`${result}:${statusText}(${status})`);
  10237. return false;
  10238. } catch (error) {
  10239. throwError(error, 'setGistData');
  10240. return false;
  10241. }
  10242. };
  10243. const getGistData = async (token, gistId, fileName, test = false) => {
  10244. try {
  10245. const logStatus = scripts_echoLog({
  10246. text: i18n('gettingData')
  10247. });
  10248. const {
  10249. result,
  10250. statusText,
  10251. status,
  10252. data
  10253. } = await tools_httpRequest({
  10254. url: `https://api.github.com/gists/${gistId}`,
  10255. headers: {
  10256. Accept: 'application/vnd.github.v3+json',
  10257. Authorization: `token ${token}`
  10258. },
  10259. responseType: 'json',
  10260. method: 'GET',
  10261. timeout: 3e4
  10262. });
  10263. if (result === 'Success') {
  10264. if (data?.status === 200) {
  10265. const content = data.response?.files?.[fileName]?.content;
  10266. let formatedContent;
  10267. if (!content) {
  10268. logStatus.error(`Error:${i18n('noRemoteData')}`);
  10269. return false;
  10270. }
  10271. if (test) {
  10272. logStatus.success();
  10273. return true;
  10274. }
  10275. try {
  10276. formatedContent = JSON.parse(content);
  10277. } catch (error) {
  10278. logStatus.error(`Error:${i18n('errorRemoteDataFormat')}`);
  10279. return false;
  10280. }
  10281. logStatus.success();
  10282. return formatedContent;
  10283. }
  10284. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10285. return false;
  10286. }
  10287. logStatus.error(`${result}:${statusText}(${status})`);
  10288. return false;
  10289. } catch (error) {
  10290. throwError(error, 'getGistData');
  10291. return false;
  10292. }
  10293. };
  10294. const syncOptions = () => {
  10295. try {
  10296. const {
  10297. TOKEN,
  10298. GIST_ID,
  10299. FILE_NAME,
  10300. SYNC_HISTORY
  10301. } = GM_getValue('gistOptions') || {
  10302. TOKEN: '',
  10303. GIST_ID: '',
  10304. FILE_NAME: '',
  10305. SYNC_HISTORY: true
  10306. };
  10307. external_Swal_default().fire({
  10308. title: i18n('gistOptions'),
  10309. 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;">
  10310. ${i18n('upload2gist')}</button>` + `<button id="download-data" type="button" class="swal2-confirm swal2-styled" style="display: inline-block;">
  10311. ${i18n('downloadFromGist')}</button></p>`,
  10312. focusConfirm: false,
  10313. showLoaderOnConfirm: true,
  10314. 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>`,
  10315. preConfirm: async () => {
  10316. const token = $('#github-token').val();
  10317. const gistId = $('#gist-id').val();
  10318. const fileName = $('#file-name').val();
  10319. const syncHistory = $('#sync-history').prop('checked');
  10320. GM_setValue('gistOptions', {
  10321. TOKEN: token,
  10322. GIST_ID: gistId,
  10323. FILE_NAME: fileName,
  10324. SYNC_HISTORY: syncHistory
  10325. });
  10326. return await getGistData(token, gistId, fileName, true);
  10327. },
  10328. allowOutsideClick: () => !external_Swal_default().isLoading(),
  10329. confirmButtonText: i18n('saveAndTest'),
  10330. showCancelButton: true,
  10331. cancelButtonText: i18n('close')
  10332. }).then(({
  10333. value
  10334. }) => {
  10335. if (value) {
  10336. external_Swal_default().fire({
  10337. icon: 'success',
  10338. title: i18n('testSuccess')
  10339. }).then(syncOptions);
  10340. } else if (value !== undefined) {
  10341. external_Swal_default().fire({
  10342. icon: 'error',
  10343. title: i18n('testFailed')
  10344. }).then(syncOptions);
  10345. }
  10346. });
  10347. $('#upload-data').on('click', async () => {
  10348. const {
  10349. TOKEN,
  10350. GIST_ID,
  10351. FILE_NAME
  10352. } = GM_getValue('gistOptions') || {};
  10353. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10354. return external_Swal_default().fire({
  10355. icon: 'error',
  10356. title: i18n('saveAndTestNotice')
  10357. }).then(syncOptions);
  10358. }
  10359. external_Swal_default().fire({
  10360. icon: 'info',
  10361. title: i18n('processingData')
  10362. });
  10363. const data = {};
  10364. const names = GM_listValues();
  10365. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10366. for (const name of names) {
  10367. if (name === 'gistOptions' || /^[\w]+?Auth$/.test(name)) {
  10368. continue;
  10369. }
  10370. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10371. continue;
  10372. }
  10373. data[name] = GM_getValue(name);
  10374. }
  10375. external_Swal_default().update({
  10376. icon: 'info',
  10377. title: i18n('updatingData')
  10378. });
  10379. if (await setGistData(TOKEN, GIST_ID, FILE_NAME, data)) {
  10380. external_Swal_default().fire({
  10381. icon: 'success',
  10382. title: i18n('syncDataSuccess')
  10383. });
  10384. } else {
  10385. external_Swal_default().fire({
  10386. icon: 'error',
  10387. title: i18n('syncDataFailed')
  10388. });
  10389. }
  10390. });
  10391. $('#download-data').on('click', async () => {
  10392. const {
  10393. TOKEN,
  10394. GIST_ID,
  10395. FILE_NAME
  10396. } = GM_getValue('gistOptions') || {};
  10397. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10398. return external_Swal_default().fire({
  10399. icon: 'error',
  10400. title: i18n('saveAndTestNotice')
  10401. }).then(syncOptions);
  10402. }
  10403. external_Swal_default().fire({
  10404. icon: 'info',
  10405. title: i18n('downloadingData')
  10406. });
  10407. const data = await getGistData(TOKEN, GIST_ID, FILE_NAME);
  10408. if (!data) {
  10409. return external_Swal_default().fire({
  10410. icon: 'error',
  10411. title: i18n('checkedNoData')
  10412. }).then(syncOptions);
  10413. }
  10414. external_Swal_default().update({
  10415. icon: 'info',
  10416. title: i18n('savingData')
  10417. });
  10418. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10419. for (const [ name, value ] of Object.entries(data)) {
  10420. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10421. continue;
  10422. }
  10423. GM_setValue(name, value);
  10424. }
  10425. external_Swal_default().fire({
  10426. icon: 'success',
  10427. title: i18n('syncDataSuccess')
  10428. });
  10429. });
  10430. } catch (error) {
  10431. throwError(error, 'syncOptions');
  10432. }
  10433. };
  10434. const dataSync = syncOptions;
  10435. class Setting {
  10436. name = 'Setting';
  10437. buttons = [ 'saveGlobalOptions', 'syncData', 'tasksHistory' ];
  10438. syncData = dataSync;
  10439. tasksHistory() {
  10440. GM_openInTab('https://auto-task-v4.hclonely.com/history.html', {
  10441. active: true
  10442. });
  10443. }
  10444. static test() {
  10445. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/setting.html';
  10446. }
  10447. before() {
  10448. try {
  10449. $('body').html('').addClass('auto-task-options');
  10450. } catch (error) {
  10451. throwError(error, 'Setting.before');
  10452. }
  10453. }
  10454. after() {
  10455. try {
  10456. this.#environment();
  10457. changeGlobalOptions('page');
  10458. whiteList('page');
  10459. $('input[name="other.twitterVerifyId"]').after(`<button id="getTwitterUserId" type="button">${i18n('getTwitterUserId')}</button>`);
  10460. $('#getTwitterUserId').on('click', () => {
  10461. this.#getId('twitterUser');
  10462. });
  10463. $('input[name="other.youtubeVerifyChannel"]').after(`<button id="getYoutubeChannelId" type="button">${i18n('getYoutubeChannelId')}</button>`);
  10464. $('#getYoutubeChannelId').on('click', () => {
  10465. this.#getId('youtubeChannel');
  10466. });
  10467. $('input[name^="position"]').on('input', function() {
  10468. const type = $(this).attr('name').replace('position.', '');
  10469. const xLabel = 'rightleft';
  10470. const yLabel = 'topbottpm';
  10471. switch (type) {
  10472. case 'buttonSideX':
  10473. case 'buttonSideY':
  10474. case 'buttonDistance':
  10475. {
  10476. const distance = $('input[name="position.buttonDistance"]').val();
  10477. const sideX = $('input[name="position.buttonSideX"]').val();
  10478. const sideY = $('input[name="position.buttonSideY"]').val();
  10479. if (![ 'right', 'left' ].includes(sideX)) {
  10480. break;
  10481. }
  10482. if (![ 'top', 'bottom' ].includes(sideY)) {
  10483. break;
  10484. }
  10485. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10486. break;
  10487. }
  10488. const distanceArr = distance.split(',');
  10489. $('#auto-task-buttons').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10490. break;
  10491. }
  10492.  
  10493. case 'showButtonSideX':
  10494. case 'showButtonSideY':
  10495. case 'showButtonDistance':
  10496. {
  10497. const distance = $('input[name="position.showButtonDistance"]').val();
  10498. const sideX = $('input[name="position.showButtonSideX"]').val();
  10499. const sideY = $('input[name="position.showButtonSideY"]').val();
  10500. if (![ 'right', 'left' ].includes(sideX)) {
  10501. break;
  10502. }
  10503. if (![ 'top', 'bottom' ].includes(sideY)) {
  10504. break;
  10505. }
  10506. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10507. break;
  10508. }
  10509. const distanceArr = distance.split(',');
  10510. $('div.show-button-div').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10511. break;
  10512. }
  10513.  
  10514. case 'logSideX':
  10515. case 'logSideY':
  10516. case 'logDistance':
  10517. {
  10518. const distance = $('input[name="position.logDistance"]').val();
  10519. const sideX = $('input[name="position.logSideX"]').val();
  10520. const sideY = $('input[name="position.logSideY"]').val();
  10521. if (![ 'right', 'left' ].includes(sideX)) {
  10522. break;
  10523. }
  10524. if (![ 'top', 'bottom' ].includes(sideY)) {
  10525. break;
  10526. }
  10527. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10528. break;
  10529. }
  10530. const distanceArr = distance.split(',');
  10531. $('#auto-task-info').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10532. break;
  10533. }
  10534.  
  10535. default:
  10536. break;
  10537. }
  10538. });
  10539. $('input[name^="hotKey"]').attr('readonly', 'readonly').off('keydown').on('keydown', function(event) {
  10540. let functionKey = '';
  10541. if (event.altKey) {
  10542. functionKey += 'alt + ';
  10543. } else if (event.ctrlKey) {
  10544. functionKey += 'ctrl + ';
  10545. } else if (event.shiftKey) {
  10546. functionKey += 'shift + ';
  10547. }
  10548. $(this).val(functionKey + (event.key.length === 1 ? event.key.toLowerCase() : ''));
  10549. });
  10550. } catch (error) {
  10551. throwError(error, 'Setting.after');
  10552. }
  10553. }
  10554. saveGlobalOptions() {
  10555. try {
  10556. saveData();
  10557. } catch (error) {
  10558. throwError(error, 'Setting.saveGlobalOptions');
  10559. }
  10560. }
  10561. #getId(social) {
  10562. try {
  10563. external_Swal_default().fire({
  10564. title: i18n('getId', i18n(social)),
  10565. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10566. <button id="link2id" data-type="${social}" class="swal2-confirm swal2-styled">获取id</button>`,
  10567. showCancelButton: true,
  10568. cancelButtonText: i18n('close'),
  10569. showConfirmButton: false
  10570. });
  10571. $('#link2id').on('click', async function() {
  10572. const link = $('#socialLink').val();
  10573. if (!link) {
  10574. return;
  10575. }
  10576. const type = $(this).attr('data-type');
  10577. if (type === 'twitterUser') {
  10578. const name = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || link;
  10579. $('#socialLink').val(await new social_Twitter().userName2id(name) || '');
  10580. } else if (type === 'youtubeChannel') {
  10581. const name = /^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www.youtube.com\/.*/.test(link) ? link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1] : link;
  10582. $('#socialLink').val((await getInfo(name, 'channel'))?.params?.channelId || '');
  10583. }
  10584. });
  10585. } catch (error) {
  10586. throwError(error, 'Setting.getId');
  10587. }
  10588. }
  10589. #environment() {
  10590. try {
  10591. const userAgent = (0, javascript_utils_umd_min.ua)();
  10592. const environmentForm = `<form id="environmentForm" class="auto-task-form">
  10593. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('name')}</td><td>${i18n('version')}</td></tr></thead><tbody>
  10594. <tr><td>${i18n('os')}</td><td>${userAgent.os}</td><td>${userAgent.osVersion}</td></tr>
  10595. <tr><td>${i18n('browser')}</td><td>${userAgent.browserZH}</td><td>${userAgent.browserVersion}</td></tr>
  10596. <tr><td>${i18n('scriptManager')}</td><td>${GM_info.scriptHandler}</td><td>${GM_info.version}</td></tr>
  10597. <tr><td>${i18n('script')}</td><td>${GM_info.script.name}</td><td>${GM_info.script.version}</td></tr>
  10598. </tbody></table></form>`;
  10599. $('body').append(`<h2>${i18n('environment')}</h2>${environmentForm}`);
  10600. } catch (error) {
  10601. throwError(error, 'Setting.environment');
  10602. }
  10603. }
  10604. }
  10605. const website_Setting = Setting;
  10606. class History extends website_Keylol {
  10607. name = 'History';
  10608. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect', 'clearHistory' ];
  10609. static test() {
  10610. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/history.html';
  10611. }
  10612. before() {
  10613. try {
  10614. $('body').html('<div class="container"></div>').addClass('auto-task-history');
  10615. const data = GM_listValues() || [];
  10616. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  10617. for (const item of tasksHistory) {
  10618. this.#addItem(item);
  10619. }
  10620. } catch (error) {
  10621. throwError(error, 'History.before');
  10622. }
  10623. }
  10624. clearHistory() {
  10625. try {
  10626. const data = GM_listValues() || [];
  10627. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  10628. for (const item of tasksHistory) {
  10629. GM_deleteValue(item);
  10630. }
  10631. external_Swal_default().fire({
  10632. title: i18n('clearHistoryFinished'),
  10633. icon: 'success'
  10634. });
  10635. } catch (error) {
  10636. throwError(error, 'History.clearHistory');
  10637. }
  10638. }
  10639. #addItem(item) {
  10640. try {
  10641. const tasksData = GM_getValue(item);
  10642. if (!tasksData?.tasks) {
  10643. return;
  10644. }
  10645. let html = '';
  10646. let title = '';
  10647. let link = '';
  10648. const [ website, id ] = item.split('-');
  10649. switch (website) {
  10650. case 'fawTasks':
  10651. title = `Freeanywhere[${id}]`;
  10652. link = `https://freeanywhere.net/#/giveaway/${id}`;
  10653. break;
  10654.  
  10655. case 'gasTasks':
  10656. title = `Giveawaysu[${id}]`;
  10657. link = `https://giveaway.su/giveaway/view/${id}`;
  10658. break;
  10659.  
  10660. case 'gcTasks':
  10661. title = `GiveeClub[${id}]`;
  10662. link = `https://givee.club/event/${id}`;
  10663. break;
  10664.  
  10665. case 'gkTasks':
  10666. title = `Givekey[${id}]`;
  10667. link = `https://givekey.ru/giveaway/${id}`;
  10668. break;
  10669.  
  10670. case 'gleamTasks':
  10671. title = `Gleam[${id}]`;
  10672. link = `https://gleam.io${id}`;
  10673. break;
  10674.  
  10675. case 'khTasks':
  10676. title = `keyhub[${id}]`;
  10677. link = `https://key-hub.eu/giveaway/${id}`;
  10678. break;
  10679.  
  10680. case 'prysTasks':
  10681. title = `Prys[${id}]`;
  10682. link = `https://prys.revadike.com/giveaway/?id=${id}`;
  10683. break;
  10684.  
  10685. default:
  10686. return;
  10687. }
  10688. for (const [ social, types ] of Object.entries(tasksData.tasks)) {
  10689. for (const [ type, tasks ] of Object.entries(types)) {
  10690. for (const task of tasks) {
  10691. 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>`;
  10692. }
  10693. }
  10694. }
  10695. $('.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>`);
  10696. $('span.delete-task').on('click', function() {
  10697. const itemName = $(this).attr('data-name');
  10698. if (itemName) {
  10699. GM_deleteValue(itemName);
  10700. $(`div.card[data-name="${itemName}"]`).remove();
  10701. external_Swal_default().fire({
  10702. title: i18n('clearTaskFinished'),
  10703. text: itemName,
  10704. icon: 'success'
  10705. });
  10706. } else {
  10707. external_Swal_default().fire({
  10708. title: i18n('clearTaskFailed'),
  10709. icon: 'error'
  10710. });
  10711. }
  10712. });
  10713. } catch (error) {
  10714. throwError(error, 'History.addItem');
  10715. }
  10716. }
  10717. }
  10718. const website_History = History;
  10719. const GiveawayHopper_defaultTasksTemplate = {
  10720. steam: {
  10721. groupLinks: [],
  10722. wishlistLinks: [],
  10723. followLinks: [],
  10724. curatorLinks: [],
  10725. curatorLikeLinks: []
  10726. },
  10727. twitter: {
  10728. userLinks: [],
  10729. retweetLinks: []
  10730. },
  10731. twitch: {
  10732. channelLinks: []
  10733. },
  10734. discord: {
  10735. serverLinks: []
  10736. },
  10737. youtube: {
  10738. channelLinks: []
  10739. },
  10740. extra: {
  10741. giveawayHopper: []
  10742. }
  10743. };
  10744. const GiveawayHopper_defaultTasks = JSON.stringify(GiveawayHopper_defaultTasksTemplate);
  10745. class GiveawayHopper extends website_Website {
  10746. name = 'GiveawayHopper';
  10747. undoneTasks = JSON.parse(GiveawayHopper_defaultTasks);
  10748. socialTasks = JSON.parse(GiveawayHopper_defaultTasks);
  10749. tasks = [];
  10750. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  10751. static test() {
  10752. return window.location.host === 'giveawayhopper.com';
  10753. }
  10754. async after() {
  10755. try {
  10756. if (!this.#checkLogin()) {
  10757. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  10758. }
  10759. this.#getGiveawayId();
  10760. } catch (error) {
  10761. throwError(error, 'GiveawayHopper.after');
  10762. }
  10763. }
  10764. async init() {
  10765. try {
  10766. const logStatus = scripts_echoLog({
  10767. text: i18n('initing')
  10768. });
  10769. if (!await this.#checkLeftKey()) {
  10770. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  10771. }
  10772. this.initialized = true;
  10773. logStatus.success();
  10774. return true;
  10775. } catch (error) {
  10776. throwError(error, 'GiveawayHopper.init');
  10777. return false;
  10778. }
  10779. }
  10780. async classifyTask(action) {
  10781. try {
  10782. if (!this.giveawayId) {
  10783. await this.#getGiveawayId();
  10784. }
  10785. const logStatus = scripts_echoLog({
  10786. text: i18n('getTasksInfo')
  10787. });
  10788. if (action === 'undo') {
  10789. this.socialTasks = GM_getValue(`giveawayHopperTasks-${this.giveawayId}`)?.tasks || JSON.parse(GiveawayHopper_defaultTasks);
  10790. }
  10791. const {
  10792. result,
  10793. statusText,
  10794. status,
  10795. data
  10796. } = await tools_httpRequest({
  10797. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/with-auth`,
  10798. method: 'GET',
  10799. responseType: 'json',
  10800. fetch: true,
  10801. headers: {
  10802. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10803. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10804. }
  10805. });
  10806. if (result === 'Success') {
  10807. if (data?.status === 200 && data?.response?.tasks) {
  10808. this.tasks = data.response.tasks;
  10809. for (const task of data.response.tasks) {
  10810. if (task.isDone) {
  10811. continue;
  10812. }
  10813. await tools_httpRequest({
  10814. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/visited`,
  10815. method: 'GET',
  10816. responseType: 'json',
  10817. fetch: true,
  10818. headers: {
  10819. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10820. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10821. }
  10822. });
  10823. if (task.category === 'Steam' && task.type === 'JoinGroup') {
  10824. const steamGroupLink = await getRedirectLink(`https://steamcommunity.com/gid/${task.group_id}`);
  10825. if (!steamGroupLink) {
  10826. continue;
  10827. }
  10828. if (action === 'undo') {
  10829. this.socialTasks.steam.groupLinks.push(steamGroupLink);
  10830. }
  10831. if (action === 'do') {
  10832. this.undoneTasks.steam.groupLinks.push(steamGroupLink);
  10833. }
  10834. continue;
  10835. }
  10836. if (task.category === 'Discord' && task.type === 'JoinServer') {
  10837. if (action === 'undo') {
  10838. this.socialTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  10839. }
  10840. if (action === 'do') {
  10841. this.undoneTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  10842. }
  10843. continue;
  10844. }
  10845. if ([ 'TikTok', 'YouTube', 'General' ].includes(task.category)) {
  10846. continue;
  10847. }
  10848. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${task.category}-${task.type}`);
  10849. }
  10850. logStatus.success();
  10851. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  10852. this.socialTasks = this.uniqueTasks(this.socialTasks);
  10853. if (window.DEBUG) {
  10854. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  10855. }
  10856. GM_setValue(`giveawayHopperTasks-${this.giveawayId}`, {
  10857. tasks: this.socialTasks,
  10858. time: new Date().getTime()
  10859. });
  10860. return true;
  10861. }
  10862. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10863. return false;
  10864. }
  10865. logStatus.error(`${result}:${statusText}(${status})`);
  10866. return false;
  10867. } catch (error) {
  10868. throwError(error, 'GiveawayHopper.classifyTask');
  10869. return false;
  10870. }
  10871. }
  10872. async verifyTask() {
  10873. try {
  10874. for (const task of this.tasks) {
  10875. if (task.isDone) {
  10876. continue;
  10877. }
  10878. const logStatus = scripts_echoLog({
  10879. text: `${i18n('verifyingTask')}[${task.displayName?.replace(':target', task.targetName) || task.name}]...`
  10880. });
  10881. if (!task.link) {
  10882. if (task.category === 'YouTube' && task.type === 'FollowAccount') {
  10883. task.link = `https://www.youtube.com/@${task.targetName}`;
  10884. } else if (task.category === 'TikTok' && task.type === 'FollowAccount') {
  10885. task.link = `https://www.tiktok.com/@${task.targetName}`;
  10886. } else if (task.category === 'Steam' && task.type === 'JoinGroup') {
  10887. task.link = '';
  10888. } else if (task.category === 'Discord' && task.type === 'JoinServer') {
  10889. task.link = '';
  10890. }
  10891. }
  10892. if (task.link) {
  10893. await tools_httpRequest({
  10894. url: `https://giveawayhopper.com/fw?url=${encodeURIComponent(task.link)}&src=campaign&src_id=${this.giveawayId}&ref=task&ref_id=${task.id}&token=${window.sessionStorage.gw_auth}`,
  10895. method: 'GET',
  10896. fetch: true,
  10897. headers: {
  10898. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10899. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10900. }
  10901. });
  10902. }
  10903. await delay(1e3);
  10904. const postData = {
  10905. taskcategory: task.category,
  10906. taskname: task.type
  10907. };
  10908. if ([ 'YouTube', 'TikTok' ].includes(task.category)) {
  10909. postData.username = '1';
  10910. }
  10911. const {
  10912. result,
  10913. statusText,
  10914. status,
  10915. data
  10916. } = await tools_httpRequest({
  10917. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/complete`,
  10918. method: 'POST',
  10919. fetch: true,
  10920. headers: {
  10921. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10922. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1]),
  10923. 'content-type': 'application/json'
  10924. },
  10925. dataType: 'json',
  10926. data: JSON.stringify(postData)
  10927. });
  10928. if (result === 'Success') {
  10929. if (data?.status === 200 && data?.response?.completed) {
  10930. logStatus.success();
  10931. continue;
  10932. }
  10933. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10934. continue;
  10935. }
  10936. logStatus.error(`${result}:${statusText}(${status})`);
  10937. continue;
  10938. }
  10939. } catch (error) {
  10940. throwError(error, 'GiveawayHopper.verifyTask');
  10941. return false;
  10942. }
  10943. }
  10944. #getGiveawayId() {
  10945. try {
  10946. const giveawayId = window.location.pathname.split('/').at(-1);
  10947. if (giveawayId) {
  10948. this.giveawayId = giveawayId;
  10949. return true;
  10950. }
  10951. scripts_echoLog({
  10952. text: i18n('getFailed', 'GiveawayId')
  10953. });
  10954. return false;
  10955. } catch (error) {
  10956. throwError(error, 'GiveawayHopper.getGiveawayId');
  10957. return false;
  10958. }
  10959. }
  10960. #checkLogin() {
  10961. try {
  10962. if (!globalOptions.other.checkLogin) {
  10963. return true;
  10964. }
  10965. if ($('div.widget-connections-edit:contains("Log in")').length > 0) {
  10966. $('div.widget-connections-edit:contains("Log in") a')[0].click();
  10967. }
  10968. return true;
  10969. } catch (error) {
  10970. throwError(error, 'GiveawayHopper.checkLogin');
  10971. return false;
  10972. }
  10973. }
  10974. async #checkLeftKey() {
  10975. try {
  10976. if (!globalOptions.other.checkLeftKey) {
  10977. return true;
  10978. }
  10979. if ($('p.widget-single-prize span').length > 0 && parseInt($('p.widget-single-prize span').text()?.match(/\d+/)?.[0] || '0', 10) > 0) {
  10980. return true;
  10981. }
  10982. await external_Swal_default().fire({
  10983. icon: 'warning',
  10984. title: i18n('notice'),
  10985. text: i18n('noKeysLeft'),
  10986. confirmButtonText: i18n('confirm'),
  10987. cancelButtonText: i18n('cancel'),
  10988. showCancelButton: true
  10989. }).then(({
  10990. value
  10991. }) => {
  10992. if (value) {
  10993. window.close();
  10994. }
  10995. });
  10996. return true;
  10997. } catch (error) {
  10998. throwError(error, 'GiveawayHopper.checkLeftKey');
  10999. return false;
  11000. }
  11001. }
  11002. }
  11003. const website_GiveawayHopper = GiveawayHopper;
  11004. const Websites = [ Freeanywhere, GiveawaySu, website_Indiedb, website_Keyhub, website_Givekey, website_GiveeClub, website_OpiumPulses, website_Keylol, website_Opquests, website_Gleam, website_SweepWidget, website_Setting, website_History, website_GiveawayHopper ];
  11005. const websiteOptions = function(website, options) {
  11006. try {
  11007. let websiteOptionsForm = `<form id="websiteOptionsForm" class="auto-task-form">
  11008. <table class="auto-task-table"><thead><tr><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  11009. for (const [ option, value ] of Object.entries(options)) {
  11010. websiteOptionsForm += `<tr><td>${option}</td><td><input class="editOption" type="text" name="${option}" value="${value}"/></td></tr>`;
  11011. }
  11012. websiteOptionsForm += '</tbody></table></form>';
  11013. external_Swal_default().fire({
  11014. title: i18n('websiteOptions'),
  11015. html: websiteOptionsForm,
  11016. showConfirmButton: true,
  11017. confirmButtonText: i18n('save'),
  11018. showCancelButton: true,
  11019. cancelButtonText: i18n('close')
  11020. }).then(({
  11021. isConfirmed
  11022. }) => {
  11023. if (isConfirmed) {
  11024. $('#websiteOptionsForm').serializeArray().map(value => {
  11025. options[value.name] = value.value;
  11026. return value;
  11027. });
  11028. GM_setValue(`${website}Options`, options);
  11029. external_Swal_default().fire({
  11030. title: i18n('changeWebsiteOptionsSuccess'),
  11031. icon: 'success'
  11032. });
  11033. }
  11034. });
  11035. } catch (error) {
  11036. throwError(error, 'websiteOptions');
  11037. }
  11038. };
  11039. const options = websiteOptions;
  11040. const external_keyboardJS_namespaceObject = keyboardJS;
  11041. var external_keyboardJS_default = __webpack_require__.n(external_keyboardJS_namespaceObject);
  11042. const checkUpdate = async (updateLink, auto) => {
  11043. try {
  11044. const checkUrl = `${updateLink}package.json?time=${new Date().getTime()}`;
  11045. const {
  11046. result,
  11047. statusText,
  11048. status,
  11049. data
  11050. } = await tools_httpRequest({
  11051. url: checkUrl,
  11052. responseType: 'json',
  11053. method: 'GET',
  11054. timeout: 3e4
  11055. });
  11056. if (result === 'Success') {
  11057. if (data?.response?.version) {
  11058. return data.response;
  11059. }
  11060. if (!auto) {
  11061. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${data?.statusText}(${data?.status})]`);
  11062. }
  11063. return false;
  11064. }
  11065. if (!auto) {
  11066. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${result}:${statusText}(${status})]`);
  11067. }
  11068. return false;
  11069. } catch (error) {
  11070. throwError(error, 'checkUpdate');
  11071. return false;
  11072. }
  11073. };
  11074. const hasNewVersion = (currentVersion, remoteVersion) => {
  11075. try {
  11076. const [ currentRealVersion ] = currentVersion.split('-');
  11077. const [ remoteRealVersion, isPreview ] = remoteVersion.split('-');
  11078. if (isPreview && !globalOptions.other.receivePreview) {
  11079. return false;
  11080. }
  11081. const [ currentVersion1, currentVersion2, currentVersion3 ] = currentRealVersion.split('.').map(value => parseInt(value, 10));
  11082. const [ remoteVersion1, remoteVersion2, remoteVersion3 ] = remoteRealVersion.split('.').map(value => parseInt(value, 10));
  11083. if (remoteVersion1 > currentVersion1) {
  11084. return true;
  11085. }
  11086. if (remoteVersion1 < currentVersion1) {
  11087. return false;
  11088. }
  11089. if (remoteVersion2 > currentVersion2) {
  11090. return true;
  11091. }
  11092. if (remoteVersion2 < currentVersion2) {
  11093. return false;
  11094. }
  11095. if (remoteVersion3 > currentVersion3) {
  11096. return true;
  11097. }
  11098. return false;
  11099. } catch (error) {
  11100. throwError(error, 'compareVersion');
  11101. return false;
  11102. }
  11103. };
  11104. const updateChecker = async () => {
  11105. try {
  11106. const currentVersion = GM_info.script.version;
  11107. const updateSource = globalOptions.other.autoUpdateSource.toLowerCase();
  11108. const updateLinks = {
  11109. github: 'https://github.com/HCLonely/auto-task-new/raw/main/',
  11110. jsdelivr: 'https://cdn.jsdelivr.net/gh/HCLonely/auto-task-v4@main/',
  11111. standby: 'https://auto-task-v4.hclonely.com/'
  11112. };
  11113. let version;
  11114. let updateLink = '';
  11115. let packageData;
  11116. if ([ 'github', 'jsdelivr', 'standby' ].includes(updateSource)) {
  11117. updateLink = updateLinks[updateSource];
  11118. packageData = await checkUpdate(updateLink, false);
  11119. } else {
  11120. updateLink = updateLinks.github;
  11121. packageData = await checkUpdate(updateLink, true);
  11122. if (!packageData) {
  11123. updateLink = updateLinks.jsdelivr;
  11124. packageData = await checkUpdate(updateLink, true);
  11125. if (!packageData) {
  11126. updateLink = updateLinks.standby;
  11127. packageData = await checkUpdate(updateLink, true);
  11128. }
  11129. }
  11130. }
  11131. if (packageData) {
  11132. version = packageData.version || currentVersion;
  11133. } else {
  11134. version = currentVersion;
  11135. scripts_echoLog({}).error(i18n('checkUpdateFailed'));
  11136. }
  11137. if (packageData && hasNewVersion(currentVersion, version)) {
  11138. scripts_echoLog({
  11139. html: `<li><font>${i18n('newVersionNotice', version, `${updateLink}dist/${GM_info.script.name}.user.js`)}</font></li>`
  11140. });
  11141. scripts_echoLog({
  11142. html: `<li>${i18n('updateText', version)}</li><ol class="update-text">${packageData.change?.map(change => `<li>${change}</li>`).join('')}<li>${i18n('updateHistory')}</li></ol>`
  11143. });
  11144. }
  11145. } catch (error) {
  11146. throwError(error, 'updateChecker');
  11147. }
  11148. };
  11149. const scripts_updateChecker = updateChecker;
  11150. window.STYLE = GM_addStyle(auto_task.A + GM_getResourceText('style'));
  11151. window.DEBUG = !!globalOptions.other?.debug;
  11152. window.TRACE = !!globalOptions.other?.debug && typeof console.trace === 'function';
  11153. const loadScript = async () => {
  11154. if (window.name === 'ATv4_twitchAuth' && window.location.hostname === 'www.twitch.tv') {
  11155. const authToken = external_Cookies_default().get('auth-token');
  11156. const isLogin = !!external_Cookies_default().get('login');
  11157. if (isLogin) {
  11158. GM_setValue('twitchAuth', {
  11159. authToken: authToken,
  11160. clientVersion: __twilightBuildID,
  11161. clientId: commonOptions?.headers?.['Client-ID'],
  11162. deviceId: commonOptions?.headers?.['Device-ID'],
  11163. clientSessionId: window.localStorage.local_storage_app_session_id.replace(/"/g, '')
  11164. });
  11165. window.close();
  11166. external_Swal_default().fire('', i18n('closePageNotice'));
  11167. } else {
  11168. external_Swal_default().fire('', i18n('needLogin'));
  11169. }
  11170. return;
  11171. }
  11172. if (window.name === 'ATv4_redditAuth' && window.location.hostname === 'www.reddit.com') {
  11173. const betaButton = $('#redesign-beta-optin-btn');
  11174. if (betaButton.length > 0) {
  11175. return betaButton[0].click();
  11176. }
  11177. window.close();
  11178. external_Swal_default().fire('', i18n('closePageNotice'));
  11179. return;
  11180. }
  11181. let website;
  11182. for (const Website of Websites) {
  11183. if (Website.test()) {
  11184. website = new Website();
  11185. break;
  11186. }
  11187. }
  11188. if (!website) {
  11189. console.log('%c%s', 'color:#ff0000', 'Auto-Task[Warning]: 脚本停止加载,当前网站不支持!');
  11190. return;
  11191. }
  11192. if (website?.before) {
  11193. await website?.before();
  11194. }
  11195. $('body').append(`
  11196. <div id="auto-task-info"
  11197. style="display:${globalOptions.other.defaultShowLog ? 'block' : 'none'};
  11198. ${globalOptions.position.logSideX}:${globalOptions.position.logDistance.split(',')[0]}px;
  11199. ${globalOptions.position.logSideY}:${globalOptions.position.logDistance.split(',')[1]}px;">
  11200. </div>
  11201. <div id="auto-task-buttons"
  11202. style="display:${globalOptions.other.defaultShowButton ? 'block' : 'none'};
  11203. ${globalOptions.position.buttonSideX}:${globalOptions.position.buttonDistance.split(',')[0]}px;
  11204. ${globalOptions.position.buttonSideY}:${globalOptions.position.buttonDistance.split(',')[1]}px;">
  11205. </div>
  11206. <div class="show-button-div"
  11207. style="display:${globalOptions.other.defaultShowButton ? 'none' : 'block'};
  11208. ${globalOptions.position.showButtonSideX}:${globalOptions.position.showButtonDistance.split(',')[0]}px;
  11209. ${globalOptions.position.showButtonSideY}:${globalOptions.position.showButtonDistance.split(',')[1]}px;">
  11210. <a class="auto-task-website-btn"
  11211. href="javascript:void(0);"
  11212. target="_self"
  11213. title="${i18n('showButton')}"> </a>
  11214. </div>
  11215. `);
  11216. $('div.show-button-div').on('click', () => {
  11217. $('#auto-task-buttons').show();
  11218. $('div.show-button-div').hide();
  11219. });
  11220. const toggleLog = () => {
  11221. const $this = $('#toggle-log');
  11222. const status = $this.attr('data-status');
  11223. if (status === 'show') {
  11224. $('#auto-task-info').hide();
  11225. $this.attr('data-status', 'hide').text(i18n('showLog'));
  11226. } else {
  11227. $('#auto-task-info').show();
  11228. $this.attr('data-status', 'show').text(i18n('hideLog'));
  11229. }
  11230. };
  11231. external_keyboardJS_default().bind(globalOptions.hotKey.doTaskKey, () => {
  11232. if (website.doTask) {
  11233. website.doTask();
  11234. }
  11235. });
  11236. external_keyboardJS_default().bind(globalOptions.hotKey.undoTaskKey, () => {
  11237. if (website.undoTask) {
  11238. website.undoTask();
  11239. }
  11240. });
  11241. external_keyboardJS_default().bind(globalOptions.hotKey.toggleLogKey, toggleLog);
  11242. if (website?.after) {
  11243. await website?.after();
  11244. }
  11245. if (website?.buttons && $('#auto-task-buttons').children().length === 0) {
  11246. $('#auto-task-buttons').addClass(`${website.name}-buttons`);
  11247. for (const button of website.buttons) {
  11248. if (website[button]) {
  11249. const btnElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">${i18n(button)}</a></p>`);
  11250. btnElement.find('a.auto-task-website-btn').on('click', () => {
  11251. website[button]();
  11252. });
  11253. $('#auto-task-buttons').append(btnElement);
  11254. }
  11255. }
  11256. }
  11257. const hideButtonElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">
  11258. ${i18n('hideButton')}</a></p>`);
  11259. hideButtonElement.find('a.auto-task-website-btn').on('click', () => {
  11260. $('#auto-task-buttons').hide();
  11261. $('div.show-button-div').show();
  11262. });
  11263. 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'}">
  11264. ${globalOptions.other.defaultShowLog ? i18n('hideLog') : i18n('showLog')}</a></p>`);
  11265. toggleLogElement.find('a.auto-task-website-btn').on('click', toggleLog);
  11266. $('#auto-task-buttons').append(hideButtonElement).append(toggleLogElement);
  11267. if (website?.options) {
  11268. GM_registerMenuCommand(i18n('changeWebsiteOptions'), () => {
  11269. options(website.name, website.options);
  11270. });
  11271. }
  11272. if (website.name !== 'Setting') {
  11273. GM_registerMenuCommand(i18n('changeGlobalOptions'), () => {
  11274. changeGlobalOptions('swal');
  11275. });
  11276. GM_registerMenuCommand(i18n('settingPage'), () => {
  11277. GM_openInTab('https://auto-task-v4.hclonely.com/setting.html', {
  11278. active: true
  11279. });
  11280. });
  11281. }
  11282. console.log('%c%s', 'color:#1bbe1a', 'Auto-Task[Load]: 脚本加载完成');
  11283. const [ v1, v2 ] = GM_info.version.split('.');
  11284. if (!(parseInt(v1, 10) >= 5 && parseInt(v2, 10) >= 2)) {
  11285. scripts_echoLog({}).error(i18n('versionNotMatched'));
  11286. }
  11287. if (!GM_getValue('notice')) {
  11288. external_Swal_default().fire({
  11289. title: i18n('swalNotice'),
  11290. icon: 'warning'
  11291. }).then(() => {
  11292. GM_openInTab(i18n('noticeLink'), {
  11293. active: true
  11294. });
  11295. GM_setValue('notice', new Date().getTime());
  11296. });
  11297. scripts_echoLog({
  11298. html: `<li><font class="warning">${i18n('echoNotice', i18n('noticeLink'))}</font></li>`
  11299. }).font?.find('a').on('click', () => {
  11300. GM_setValue('notice', new Date().getTime());
  11301. });
  11302. }
  11303. scripts_updateChecker();
  11304. };
  11305. if (window.location.hostname === 'discord.com') {
  11306. const LocalStorage = window.localStorage;
  11307. if (window.name === 'ATv4_discordAuth') {
  11308. window.localStorage.removeItem = () => true;
  11309. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11310. if (discordAuth && discordAuth.length > 0) {
  11311. GM_setValue('discordAuth', {
  11312. auth: discordAuth
  11313. });
  11314. window.close();
  11315. external_Swal_default().fire('', i18n('closePageNotice'));
  11316. } else {
  11317. external_Swal_default().fire({
  11318. text: i18n('getDiscordAuthFailed'),
  11319. icon: 'error'
  11320. });
  11321. }
  11322. } else {
  11323. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11324. if (discordAuth && discordAuth.length > 0) {
  11325. GM_setValue('discordAuth', {
  11326. auth: discordAuth
  11327. });
  11328. }
  11329. }
  11330. } else if (window.location.hostname === 'opquests.com') {
  11331. loadScript();
  11332. } else if ((window.name === 'ATv4_updateStoreAuth' || GM_getValue('ATv4_updateStoreAuth')) && window.location.host === 'store.steampowered.com') {
  11333. $(() => {
  11334. if ($('[data-miniprofile]').length === 0) {
  11335. return;
  11336. }
  11337. const storeSessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11338. if (storeSessionID) {
  11339. GM_deleteValue('ATv4_updateStoreAuth');
  11340. GM_setValue('steamStoreAuth', {
  11341. storeSessionID: storeSessionID
  11342. });
  11343. window.close();
  11344. external_Swal_default().fire('', i18n('closePageNotice'));
  11345. } else {
  11346. external_Swal_default().fire({
  11347. title: 'Error: Get "sessionID" failed',
  11348. icon: 'error'
  11349. });
  11350. }
  11351. });
  11352. } else if ((window.name === 'ATv4_updateCommunityAuth' || GM_getValue('ATv4_updateCommunityAuth')) && window.location.host === 'steamcommunity.com') {
  11353. $(() => {
  11354. const steam64Id = document.body.innerHTML.match(/g_steamID = "(.+?)";/)?.[1];
  11355. const communitySessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11356. if (steam64Id && communitySessionID) {
  11357. GM_deleteValue('ATv4_updateCommunityAuth');
  11358. GM_setValue('steamCommunityAuth', {
  11359. steam64Id: steam64Id,
  11360. communitySessionID: communitySessionID
  11361. });
  11362. window.close();
  11363. external_Swal_default().fire('', i18n('closePageNotice'));
  11364. } else {
  11365. setTimeout(() => {
  11366. external_Swal_default().fire({
  11367. title: 'Error: Get "sessionID" failed',
  11368. icon: 'error'
  11369. });
  11370. }, 3e3);
  11371. }
  11372. });
  11373. } else {
  11374. if (window.location.hostname === 'key-hub.eu') {
  11375. unsafeWindow.keyhubtracker = 1;
  11376. unsafeWindow.gaData = {};
  11377. }
  11378. $(loadScript);
  11379. }
  11380. }();
  11381. })();