auto-task-v4

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

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

  1. // ==UserScript==
  2. // @name auto-task-v4
  3. // @namespace auto-task-v4
  4. // @version 4.6.3
  5. // @description 自动完成 Freeanywhere,Giveawaysu,GiveeClub,Givekey,Gleam,Indiedb,keyhub,OpiumPulses,Opquests,SweepWidget 等网站的任务。
  6. // @description:en Automatically complete the tasks of FreeAnyWhere, GiveawaySu, GiveeClub, Givekey, Gleam, Indiedb, keyhub, OpiumPulses, Opquests, SweepWidget websites.
  7. // @author HCLonely
  8. // @license MIT
  9. // @run-at document-start
  10. // @homepage https://auto-task-doc.js.org/
  11. // @supportURL https://github.com/HCLonely/auto-task-v4/issues
  12. // @icon https://auto-task-v4.hclonely.com/favicon.ico
  13.  
  14. // @include *://freeanywhere.net/*
  15. // @include *://giveaway.su/giveaway/view/*
  16. // @include *://givee.club/*/event/*
  17. // @include *://givekey.ru/giveaway/*
  18. // @include *://www.indiedb.com/giveaways*
  19. // @include *://key-hub.eu/giveaway/*
  20. // @include *://keylol.com/*
  21. // @include *://www.opiumpulses.com/giveaways
  22. // @include *://prys.revadike.com/giveaway/?id=*
  23. // @include *://opquests.com/quests/*
  24. // @include *://gleam.io/*
  25. // @include *://sweepwidget.com/view/*
  26. // @include *://giveawayhopper.com/c/*
  27.  
  28. // @include *://discord.com/*
  29. // @include *://www.twitch.tv/*
  30. // @include *://www.youtube.com/*
  31. // @include *://*.reddit.com/*
  32. // @include *://twitter.com/settings/account?k*
  33. // @include *://x.com/settings/account*
  34. // @include *://steamcommunity.com/*
  35. // @include *://store.steampowered.com/*
  36. // @include https://auto-task-v4.hclonely.com/setting.html
  37. // @include https://auto-task-v4.hclonely.com/history.html
  38.  
  39. // @grant GM_setValue
  40. // @grant GM_getValue
  41. // @grant GM_listValues
  42. // @grant GM_deleteValue
  43. // @grant GM_addStyle
  44. // @grant GM_xmlhttpRequest
  45. // @grant GM_registerMenuCommand
  46. // @grant GM_info
  47. // @grant GM_openInTab
  48. // @grant GM_setClipboard
  49. // @grant GM_getResourceText
  50. // @grant GM_cookie
  51. // @grant GM_addValueChangeListener
  52. // @grant GM_removeValueChangeListener
  53. // @grant unsafeWindow
  54. // @grant window.close
  55. // @grant window.localStorage
  56. // @grant window.sessionStorage
  57. // @grant window.focus
  58.  
  59. // @connect cdn.jsdelivr.net
  60. // @connect store.steampowered.com
  61. // @connect steamcommunity.com
  62. // @connect login.steampowered.com
  63. // @connect twitter.com
  64. // @connect x.com
  65. // @connect api.twitter.com
  66. // @connect youtube.com
  67. // @connect www.youtube.com
  68. // @connect facebook.com
  69. // @connect instagram.com
  70. // @connect vk.com
  71. // @connect twitch.tv
  72. // @connect www.twitch.tv
  73. // @connect gql.twitch.tv
  74. // @connect github.com
  75. // @connect discordapp.com
  76. // @connect discord.gg
  77. // @connect discord.com
  78. // @connect www.reddit.com
  79. // @connect oauth.reddit.com
  80. // @connect raw.githubusercontent.com
  81. // @connect t.me
  82. // @connect bit.ly
  83. // @connect giveaway.su
  84. // @connect google.com
  85. // @connect www.vloot.io
  86. // @connect givee.club
  87. // @connect gleam.io
  88. // @connect www.indiedb.com
  89. // @connect key-hub.eu
  90. // @connect opquests.com
  91. // @connect itch.io
  92. // @connect auto-task-v4.hclonely.com
  93. // @connect giveawayhopper.com
  94. // @connect *
  95. // @require https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
  96. // @require https://cdn.jsdelivr.net/npm/js-cookie@3.0.1/dist/js.cookie.min.js
  97. // @require https://cdn.jsdelivr.net/npm/regenerator-runtime@0.13.5/runtime.min.js
  98. // @require https://cdn.jsdelivr.net/npm/js-sha1@0.6.0/src/sha1.min.js
  99. // @require https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js
  100. // @resource style https://cdn.jsdelivr.net/npm/sweetalert2@11.3.5/dist/sweetalert2.min.css
  101. // @require https://cdn.jsdelivr.net/npm/keyboardjs@2.6.4/dist/keyboard.min.js
  102. // @require https://cdn.jsdelivr.net/npm/dayjs@1.10.7/dayjs.min.js
  103.  
  104. // @noframes
  105. // ==/UserScript==
  106.  
  107. console.log('%c%s', 'color:blue', 'Auto-Task[Load]: 脚本开始加载');
  108. (function() {
  109. var __webpack_modules__ = {
  110. 991: function(__unused_webpack_module, exports) {
  111. !function(e, n) {
  112. true ? n(exports) : 0;
  113. }(this, function(e) {
  114. 'use strict';
  115. var t = function() {
  116. return (t = Object.assign || function(e) {
  117. for (var n, o = 1, t = arguments.length; o < t; o++) {
  118. for (var r in n = arguments[o]) {
  119. Object.prototype.hasOwnProperty.call(n, r) && (e[r] = n[r]);
  120. }
  121. }
  122. return e;
  123. }).apply(this, arguments);
  124. };
  125. function r(e, n, o) {
  126. if (o || 2 === arguments.length) {
  127. for (var t, r = 0, i = n.length; r < i; r++) {
  128. !t && r in n || ((t = t || Array.prototype.slice.call(n, 0, r))[r] = n[r]);
  129. }
  130. }
  131. return e.concat(t || Array.prototype.slice.call(n));
  132. }
  133. function d(e) {
  134. return '[object Object]' === n(e);
  135. }
  136. function l(e, n) {
  137. var o = r(r([], n || [], !0), [ '_' ], !1).join('|');
  138. return e.replace(new RegExp('(('.concat(o, ')[a-z])+'), 'g'), function(e, n) {
  139. return n.replace(new RegExp(o), '').toLocaleUpperCase();
  140. });
  141. }
  142. var n = function(e) {
  143. return Object.prototype.toString.call(e);
  144. };
  145. var o = (i.prototype.init = function() {
  146. try {
  147. this.getSystemName(), this.getBrowserName();
  148. } catch (e) {
  149. console.warn('[UA formatter error] '.concat(e));
  150. }
  151. }, i.prototype.getEngine = function() {
  152. var e = this.agent;
  153. return -1 !== e.indexOf('Trident') ? 'Trident' : -1 !== e.indexOf('Firefox') ? 'Gecko' : -1 !== e.indexOf('Presto') ? 'Presto' : 'WebKit';
  154. }, i.prototype.getSystemName = function() {
  155. var e, n = (this.agent.match(/^[a-z]+\/\d+\.\d+\s?\(([a-z\d\s:;./_-]+)\)/i) || [])[1];
  156. try {
  157. var o = '';
  158. if (/Windows/i.test(n)) {
  159. var t = (n.match(/NT\s(\d+\.\d+)/) || [])[1];
  160. switch (this.info.os = 'Windows', t) {
  161. case '6.3':
  162. o = '8.1';
  163. break;
  164.  
  165. case '6.2':
  166. o = '8';
  167. break;
  168.  
  169. case '6.1':
  170. o = '7';
  171. break;
  172.  
  173. case '5.2':
  174. case '5.1':
  175. o = 'XP';
  176. break;
  177.  
  178. default:
  179. o = t;
  180. }
  181. return this.info.device = 'PC', void (this.info.osVersion = o);
  182. }
  183. if (/^Macintosh/i.test(n)) {
  184. return o = (n.match(/X\s((\d+(_|\.))+\d+)/) || [])[1], this.info.os = 'Macintosh',
  185. this.info.device = 'PC', void (this.info.osVersion = null !== (e = null == o ? void 0 : o.replace(/_/g, '.')) && void 0 !== e ? e : 'Unknown');
  186. }
  187. if (/^iPad/i.test(n)) {
  188. return o = (n.match(/((\d+_)+\d+)/) || [])[1], this.info.os = 'iPad',
  189. this.info.device = 'Tablet', void (this.info.osVersion = o.replace(/_/g, '.'));
  190. }
  191. if (/^iPhone/i.test(n)) {
  192. return o = (n.match(/((\d+_)+\d+)/) || [])[1], this.info.os = 'iPhone',
  193. this.info.device = 'Mobile', void (this.info.osVersion = o.replace(/_/g, '.'));
  194. }
  195. if (-1 !== n.indexOf('Android')) {
  196. var r = (n.match(/Android\s((\d+\.?)+\d?)/) || [])[1];
  197. return this.info.device = 'Mobile', this.info.os = 'Android', void (this.info.osVersion = r);
  198. }
  199. if (/Linux\s[a-z\d_]+/.test(n)) {
  200. return this.info.os = 'Linux', void (this.info.osVersion = 'Unknown');
  201. }
  202. this.info.os = 'Unknown', this.info.osVersion = 'Unknown';
  203. } catch (e) {
  204. this.info.os = 'Unknown', this.info.osVersion = 'Unknown';
  205. }
  206. }, i.prototype.getBrowserName = function() {
  207. var e = Object.keys(this.browserNameMap).map(function(e) {
  208. return new RegExp(''.concat(e, '(\\/|\\s)(\\d+\\.)+\\d+'));
  209. }), n = 1 < (n = (this.agent.match(/[a-z\d]+(\/|\s)(\d+\.)+\d+/gi) || []).filter(function(n) {
  210. return -1 !== e.findIndex(function(e) {
  211. return e.test(n);
  212. });
  213. })).length && !/^Safari/.test(n[n.length - 1]) ? n.reverse() : n;
  214. this.info = t(t({}, this.info), this._formatBrowserVersion(n[0]));
  215. }, i.prototype._formatBrowserVersion = function(e) {
  216. var n, o, t, r;
  217. try {
  218. for (var i = null !== (o = null === (n = e.match(/(?<name>[a-z\d]+)(\/|\s)(?<version>(\d+\.)+\d+)/i)) || void 0 === n ? void 0 : n.groups) && void 0 !== o ? o : {}, s = i.name, a = i.version, c = {}, f = 0, u = Object.entries(this.browserNameMap); f < u.length; f++) {
  219. var d = u[f], l = d[0], h = d[1];
  220. if (new RegExp(l).test(s)) {
  221. c = h;
  222. break;
  223. }
  224. }
  225. var p = {
  226. browserVersion: null != a ? a : 'Unknown',
  227. browser: null !== (t = c.en) && void 0 !== t ? t : 'Unknown',
  228. browserZH: null !== (r = (null == c ? void 0 : c.zh) || c.en) && void 0 !== r ? r : 'Unknown'
  229. };
  230. return 'Trident' === s && (p.browserVersion = {
  231. '4.0': 8,
  232. '5.0': 9,
  233. '6.0': 10,
  234. '7.0': 11
  235. }[a]), p;
  236. } catch (e) {
  237. return console.warn('[UA formatter error] '.concat(e)), {
  238. browser: 'Unknown',
  239. browserVersion: 'Unknown'
  240. };
  241. }
  242. }, i);
  243. function i(e) {
  244. this.agent = '', this.info = {
  245. browser: '',
  246. browserZH: '',
  247. browserVersion: '',
  248. os: '',
  249. osVersion: '',
  250. device: 'Unknown',
  251. engine: 'WebKit'
  252. }, this.browserNameMap = {
  253. MicroMessenger: {
  254. en: 'MicroMessenger',
  255. zh: '微信'
  256. },
  257. MetaSr: {
  258. en: 'MetaSr',
  259. zh: '搜狗浏览器'
  260. },
  261. 'QQ(Browser)?': {
  262. en: 'QQBrowser',
  263. zh: 'QQ浏览器'
  264. },
  265. UCBrowser: {
  266. en: 'UCBrowser',
  267. zh: 'UC浏览器'
  268. },
  269. '2345Explorer': {
  270. en: '2345Explorer',
  271. zh: '2345极速浏览器'
  272. },
  273. Mb2345Browser: {
  274. en: 'Mb2345Browser',
  275. zh: '2345手机浏览器'
  276. },
  277. Trident: {
  278. en: 'Internet Explorer'
  279. },
  280. 'Edge?': {
  281. en: 'Edge'
  282. },
  283. OPR: {
  284. en: 'Opera'
  285. },
  286. Vivaldi: {
  287. en: 'Vivaldi'
  288. },
  289. Firefox: {
  290. en: 'Firefox'
  291. },
  292. Chrome: {
  293. en: 'Chrome'
  294. },
  295. Safari: {
  296. en: 'Safari'
  297. }
  298. }, this.agent = e, this.init();
  299. var n = this.info, o = n.browser, e = n.browserVersion, n = n.osVersion;
  300. this.info = t(t({}, this.info), {
  301. engine: this.getEngine(),
  302. browserVersion: 'Safari' === o ? n : e
  303. });
  304. }
  305. function s() {
  306. this.cookies = {}, this.init();
  307. }
  308. var a = new (s.prototype.init = function() {
  309. var o = {};
  310. document.cookie.split(/;\s/).forEach(function(e) {
  311. var n = e.split(/=/), e = n[0], n = n[1];
  312. o[e] = n;
  313. }), this.cookies = o;
  314. }, s.prototype.getItem = function(e) {
  315. return this.cookies[e];
  316. }, s.prototype.getAllItems = function() {
  317. return this.cookies;
  318. }, s.prototype.setItem = function(e, n, o, t, r, i) {
  319. document.cookie = ''.concat(e, '=').concat(n).concat(o ? '; expires='.concat(o) : '').concat(t ? '; path='.concat(t) : '').concat(r ? '; domain='.concat(r) : '').concat(i ? '; secure' : '');
  320. }, s)();
  321. e.countDown = function e(n, o, t, r) {
  322. if (!window) {
  323. throw new Error('window is not defind.');
  324. }
  325. if (0 < n) {
  326. return r && r(), n--, window[o] = window.setTimeout(function() {
  327. e(n, o, t, r);
  328. }, 1e3), function() {
  329. return clearTimeout(window[o]);
  330. };
  331. }
  332. clearTimeout(window[o]), t && t();
  333. }, e.createRandomID = function(e) {
  334. void 0 === e && (e = 12);
  335. for (var n = [], o = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''), t = o.length, r = 0; r < e; r++) {
  336. n.push(o[Math.round(Math.random() * t)]);
  337. }
  338. return n.join('');
  339. }, e.dCookie = a, e.debounce = function(o, t, r) {
  340. var i;
  341. void 0 === t && (t = 0);
  342. var s = r = void 0 === r ? !1 : r;
  343. return function() {
  344. var e = this, n = arguments;
  345. s && (o.apply(this, arguments), s = !1), clearTimeout(i), i = setTimeout(function() {
  346. r ? s = !0 : o.apply(e, n);
  347. }, t);
  348. };
  349. }, e.deepCopy = function e(n) {
  350. if (d(n) || Array.isArray(n)) {
  351. var o, t = Array.isArray(n) ? [] : {};
  352. for (o in n) {
  353. t[o] = e(n[o]);
  354. }
  355. return t;
  356. }
  357. return n;
  358. }, e.formatQueryParams = function(e) {
  359. e = null === (e = /\?(?<params>(.*)=.+)/.exec(decodeURIComponent(e))) || void 0 === e ? void 0 : e.groups;
  360. if (!e) {
  361. return {};
  362. }
  363. for (var n = e.params.split('&'), t = {}, o = 0; o < n.length; o++) {
  364. n[o].replace(/([^?&]*)=([^?&]*)/, function(e, n, o) {
  365. return t[n] = o, e;
  366. });
  367. }
  368. return t;
  369. }, e.formatThousandth = function(e) {
  370. var n = ''.concat(e).split('.'), e = n[0], n = n[1], n = void 0 === n ? '' : n, e = e.replace(/\d{1,3}(?=(\d{3})+$)/g, '$&,');
  371. return ''.concat(e).concat(n ? '.'.concat(n) : '');
  372. }, e.generateTree = function e(n, o, t, r) {
  373. for (var i = [], s = 0; s < n.length; s++) {
  374. var a = n[s];
  375. a[t] === o && (i.push(a), a.children = e(n, a[null != r ? r : 'id'], t, r));
  376. }
  377. return i;
  378. }, e.isEmpty = function(e) {
  379. return Array.isArray(e) ? 0 === e.length : d(e) ? 0 === Object.keys(e).length : [ '[object Set]', '[object Map]' ].includes(n(e)) ? 0 === e.size : [ null, void 0, '' ].includes(e);
  380. }, e.isFunction = function(e) {
  381. return '[object Function]' === n(e);
  382. }, e.isImageUrl = function(e) {
  383. return /\.((png)|(jpe?g)|(gif)|(svg)|(webp))$/gi.test(e);
  384. }, e.isObject = d, e.isRegexp = function(e) {
  385. return '[object RegExp]' === n(e);
  386. }, e.objectKeyToCamelCase = function e(n, o, t) {
  387. if (Array.isArray(n)) {
  388. for (var r = [], i = 0; i < n.length; i++) {
  389. r[i] = e(o && n[i][o] ? n[i][o] : n[i], o, t);
  390. }
  391. } else if (d(n)) {
  392. r = {};
  393. for (var s = o && n[o] ? n[o] : n, a = 0, c = Object.entries(s); a < c.length; a++) {
  394. var f = (u = c[a])[0], u = u[1];
  395. Array.isArray(u) || d(s) ? r[l(f, t)] = e(u, o, t) : r[l(f, t)] = u;
  396. }
  397. } else {
  398. r = n;
  399. }
  400. return r;
  401. }, e.realType = n, e.searchParams = function(e, n) {
  402. return void 0 === e && (e = null === location || void 0 === location ? void 0 : location.search),
  403. new URLSearchParams(e).get(n);
  404. }, e.toLowerCamelCase = l, e.toUnderline = function(e) {
  405. return e.replace(/([A-Z])/g, function(e) {
  406. return '_'.concat(e.toLocaleLowerCase());
  407. });
  408. }, e.ua = function(e) {
  409. return void 0 === e && (e = navigator.userAgent), new o(e).info;
  410. }, Object.defineProperty(e, '__esModule', {
  411. value: !0
  412. });
  413. });
  414. },
  415. 675: function(module, __webpack_exports__, __webpack_require__) {
  416. 'use strict';
  417. __webpack_require__.d(__webpack_exports__, {
  418. A: function() {
  419. return __WEBPACK_DEFAULT_EXPORT__;
  420. }
  421. });
  422. var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(601);
  423. var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = __webpack_require__.n(_node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
  424. var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(314);
  425. var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = __webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
  426. var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()(_node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default());
  427. ___CSS_LOADER_EXPORT___.push([ module.id, `.colorful-button,#auto-task-buttons a.auto-task-website-btn,.show-button-div a.auto-task-website-btn,body.auto-task-options .auto-task-form table button{position:relative;padding:5px 10px;text-align:center;color:#fff;text-decoration:none;background:linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);border-radius:30px;background-size:400%;text-transform:capitalize}.colorful-button:hover,#auto-task-buttons a.auto-task-website-btn:hover,.show-button-div a.auto-task-website-btn:hover,body.auto-task-options .auto-task-form table button:hover{transform:scale(1.05);box-shadow:0 6px 20px rgba(0,0,0,.3);cursor:pointer}.colorful-button:hover::before,#auto-task-buttons a.auto-task-website-btn:hover::before,.show-button-div a.auto-task-website-btn:hover::before,body.auto-task-options .auto-task-form table button:hover::before{filter:blur(10px);opacity:1}.colorful-button::before,#auto-task-buttons a.auto-task-website-btn::before,.show-button-div a.auto-task-website-btn::before,body.auto-task-options .auto-task-form table button::before{content:"";position:absolute;top:-5px;left:-5px;right:-5px;bottom:-5px;z-index:-1;background:linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);border-radius:40px;background-size:400%;opacity:-1}#auto-task-info{z-index:999999999 !important}#auto-task-info{position:fixed;bottom:10px;right:10px;width:60%;max-width:500px;max-height:60%;overflow-y:auto;color:#000;background-color:#fff;padding-left:5px;border:solid 2px #add8e6;border-radius:10px}#auto-task-info li{text-align:left}#auto-task-info li a.high-light{color:#00aeff;font-weight:bold}#auto-task-info .success{color:green}#auto-task-info .error{color:red}#auto-task-info .warning{color:blue}#auto-task-info .info{color:#ff0}#auto-task-info .update-text{color:green;border:solid 2px #8dcb69;margin:5px 10px 5px 20px;border-radius:10px;padding:5px 20px}.auto-task-keylol{text-decoration:none !important}.auto-task-keylol{display:inline-block;text-transform:capitalize;margin-left:10px;border:solid 1px;border-radius:5px;padding:0 2px}.auto-task-keylol[selected=selected]{background-color:blue !important;color:#fff !important}.auto-task-form table{font-family:verdana,arial,sans-serif;font-size:11px;color:#333;border-width:1px;border-color:#999;border-collapse:collapse;width:100%}.auto-task-form table thead td{border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9;font-weight:bold;background-color:#fff}.auto-task-form table tbody tr{background-color:#d4e3e5}.auto-task-form table tbody tr:hover{background-color:#ff6 !important}.auto-task-form table tbody tr th{background-color:#c3dde0;border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9;text-transform:capitalize}.auto-task-form table tbody tr td{border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9}.swal2-modal{width:70% !important;max-width:1000px !important}body.auto-task-options{padding-top:10px;text-align:center}body.auto-task-options .auto-task-form{width:80%;max-width:1000px;margin:0 auto;padding-bottom:20px}body.auto-task-options .auto-task-form table input.editOption{width:80%}body.auto-task-options .auto-task-form table #getTwitterUserId,body.auto-task-options .auto-task-form table #getYoutubeChannelId{margin-top:5px}body.auto-task-options .auto-task-form table button{z-index:1}body.auto-task-options .auto-task-form table input[type=text]{outline-style:none;border:1px solid #ccc;border-radius:3px;padding:5px 10px;font-size:14px}body.auto-task-options .auto-task-form table input[type=text]:focus{border-color:#66afe9;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}body.auto-task-options .auto-task-form table label{position:relative;width:160px;height:80px;cursor:pointer;transform:scale(0.25);margin:-25% 0;top:-30px;display:inline-block}body.auto-task-options .auto-task-form table label input{position:relative;z-index:1;appearance:none}body.auto-task-options .auto-task-form table label input:checked~span{background:#05be05;box-shadow:0 15px 25px rgba(5,190,5,.4)}body.auto-task-options .auto-task-form table label input:checked~span i{left:84px}body.auto-task-options .auto-task-form table label input:checked~span i::before{background:#05be05;box-shadow:35px 0 0 #05be05}body.auto-task-options .auto-task-form table label input:checked~span i::after{bottom:12px;height:15px;border-bottom-left-radius:15px;border-bottom-right-radius:15px;background:#05be05}body.auto-task-options .auto-task-form table label span{position:absolute;top:0;left:0;width:100%;height:100%;background:#fe0000;border-radius:80px;transition:.5s;box-shadow:0 15px 25px rgba(254,0,0,.4)}body.auto-task-options .auto-task-form table label span i{position:absolute;top:4px;left:4px;width:72px;height:72px;background:#fff;border-radius:50%}body.auto-task-options .auto-task-form table label span i::before{content:"";position:absolute;top:22px;left:12px;width:12px;height:12px;border-radius:50%;background:#fe0000;box-shadow:35px 0 0 #fe0000;transition:.5s}body.auto-task-options .auto-task-form table label span i::after{content:"";position:absolute;bottom:15px;left:calc(50% - 15px);width:30px;height:6px;border-radius:6px;background:#fe0000;transition:.5s}body.auto-task-history{font-size:15px;font-weight:400;line-height:1.5}body.auto-task-history .container a{color:#007bff;text-decoration:none;background-color:rgba(0,0,0,0)}body.auto-task-history .container .card{width:80%;max-width:800px;border-radius:10px;background:rgba(118,118,118,.1019607843);border-top:1px solid rgba(255,255,255,.5019607843);-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);box-shadow:0 15px 25px rgba(0,0,0,.1019607843);margin:20px auto;position:relative;display:flex;flex-direction:column;word-wrap:break-word;-webkit-background-clip:border-box;background-clip:border-box;border:1px solid rgba(0,0,0,.125);border-radius:.25rem}body.auto-task-history .container .card .title{text-align:center;font-size:30px;font-weight:bold;margin:5px 0}body.auto-task-history .container .card .title a:hover{text-decoration:none;background:#93e1ff;border-radius:10px;padding:3px}body.auto-task-history .container .card ul{margin-bottom:25px}body.auto-task-history .container .card ul li{margin-bottom:5px;line-height:20px}body.auto-task-history .container .card ul a:hover{text-decoration:underline}body.auto-task-history .container .card .delete-task{right:10px;width:38px;height:35px;position:absolute;font-size:24px;cursor:pointer;border-radius:10px}body.auto-task-history .container .card .delete-task:hover{background:#fff}body.auto-task-history .container .card .time{right:5px;position:absolute;bottom:0;color:#e83e8c;font-family:'SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace';font-size:15px}#auto-task-buttons,.show-button-div{z-index:999999999 !important}#auto-task-buttons,.show-button-div{position:fixed;top:30px;right:15px;width:124px;transform:scale(0.85)}#auto-task-buttons p,.show-button-div p{margin:5px !important}#auto-task-buttons p,.show-button-div p{line-height:30px;height:40px;text-align:center}#auto-task-buttons a.auto-task-website-btn,.show-button-div a.auto-task-website-btn{width:105px;line-height:27px;font-size:20px;display:block}.show-button-div{width:20px}.auto-task-capitalize{text-transform:capitalize !important}.swal2-file:focus,.swal2-input:focus,.swal2-textarea:focus{box-shadow:inset 0px 0px 4px 1px rgba(100,150,200,.5) !important}.swal2-checkbox-custom{align-items:center;justify-content:center;background:#fff;color:inherit;margin:1em auto}.swal2-checkbox-custom input{flex-shrink:0;margin:0 .4em}.giveaway-actions #getKey{display:none !important}.auto-task-giveaway-status{color:#fff;border-radius:10px;padding:0 5px;margin-left:5px}.auto-task-giveaway-status.active{background-color:#5cb85c}.auto-task-giveaway-status.not-active{background-color:#d9534f}`, '' ]);
  428. const __WEBPACK_DEFAULT_EXPORT__ = ___CSS_LOADER_EXPORT___.toString();
  429. },
  430. 314: function(module) {
  431. 'use strict';
  432. module.exports = function(cssWithMappingToString) {
  433. var list = [];
  434. list.toString = function toString() {
  435. return this.map(function(item) {
  436. var content = '';
  437. var needLayer = typeof item[5] !== 'undefined';
  438. if (item[4]) {
  439. content += '@supports ('.concat(item[4], ') {');
  440. }
  441. if (item[2]) {
  442. content += '@media '.concat(item[2], ' {');
  443. }
  444. if (needLayer) {
  445. content += '@layer'.concat(item[5].length > 0 ? ' '.concat(item[5]) : '', ' {');
  446. }
  447. content += cssWithMappingToString(item);
  448. if (needLayer) {
  449. content += '}';
  450. }
  451. if (item[2]) {
  452. content += '}';
  453. }
  454. if (item[4]) {
  455. content += '}';
  456. }
  457. return content;
  458. }).join('');
  459. };
  460. list.i = function i(modules, media, dedupe, supports, layer) {
  461. if (typeof modules === 'string') {
  462. modules = [ [ null, modules, undefined ] ];
  463. }
  464. var alreadyImportedModules = {};
  465. if (dedupe) {
  466. for (var k = 0; k < this.length; k++) {
  467. var id = this[k][0];
  468. if (id != null) {
  469. alreadyImportedModules[id] = true;
  470. }
  471. }
  472. }
  473. for (var _k = 0; _k < modules.length; _k++) {
  474. var item = [].concat(modules[_k]);
  475. if (dedupe && alreadyImportedModules[item[0]]) {
  476. continue;
  477. }
  478. if (typeof layer !== 'undefined') {
  479. if (typeof item[5] === 'undefined') {
  480. item[5] = layer;
  481. } else {
  482. item[1] = '@layer'.concat(item[5].length > 0 ? ' '.concat(item[5]) : '', ' {').concat(item[1], '}');
  483. item[5] = layer;
  484. }
  485. }
  486. if (media) {
  487. if (!item[2]) {
  488. item[2] = media;
  489. } else {
  490. item[1] = '@media '.concat(item[2], ' {').concat(item[1], '}');
  491. item[2] = media;
  492. }
  493. }
  494. if (supports) {
  495. if (!item[4]) {
  496. item[4] = ''.concat(supports);
  497. } else {
  498. item[1] = '@supports ('.concat(item[4], ') {').concat(item[1], '}');
  499. item[4] = supports;
  500. }
  501. }
  502. list.push(item);
  503. }
  504. };
  505. return list;
  506. };
  507. },
  508. 601: function(module) {
  509. 'use strict';
  510. module.exports = function(i) {
  511. return i[1];
  512. };
  513. }
  514. };
  515. var __webpack_module_cache__ = {};
  516. function __webpack_require__(moduleId) {
  517. var cachedModule = __webpack_module_cache__[moduleId];
  518. if (cachedModule !== undefined) {
  519. return cachedModule.exports;
  520. }
  521. var module = __webpack_module_cache__[moduleId] = {
  522. id: moduleId,
  523. exports: {}
  524. };
  525. __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  526. return module.exports;
  527. }
  528. !function() {
  529. __webpack_require__.n = function(module) {
  530. var getter = module && module.__esModule ? function() {
  531. return module['default'];
  532. } : function() {
  533. return module;
  534. };
  535. __webpack_require__.d(getter, {
  536. a: getter
  537. });
  538. return getter;
  539. };
  540. }();
  541. !function() {
  542. __webpack_require__.d = function(exports, definition) {
  543. for (var key in definition) {
  544. if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  545. Object.defineProperty(exports, key, {
  546. enumerable: true,
  547. get: definition[key]
  548. });
  549. }
  550. }
  551. };
  552. }();
  553. !function() {
  554. __webpack_require__.o = function(obj, prop) {
  555. return Object.prototype.hasOwnProperty.call(obj, prop);
  556. };
  557. }();
  558. var __webpack_exports__ = {};
  559. !function() {
  560. 'use strict';
  561. const external_Swal_namespaceObject = Swal;
  562. var external_Swal_default = __webpack_require__.n(external_Swal_namespaceObject);
  563. const external_Cookies_namespaceObject = Cookies;
  564. var external_Cookies_default = __webpack_require__.n(external_Cookies_namespaceObject);
  565. var auto_task = __webpack_require__(675);
  566. var javascript_utils_umd_min = __webpack_require__(991);
  567. const httpRequest = async (options, times = 0) => {
  568. if (window.TRACE) {
  569. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  570. }
  571. try {
  572. const result = await new Promise(resolve => {
  573. if (options.dataType) {
  574. options.responseType = options.dataType;
  575. }
  576. const requestObj = {
  577. ...{
  578. timeout: 3e4,
  579. ontimeout(data) {
  580. resolve({
  581. result: 'Error',
  582. statusText: 'Timeout',
  583. status: 601,
  584. data: data,
  585. options: options
  586. });
  587. },
  588. onabort(data) {
  589. resolve({
  590. result: 'Error',
  591. statusText: 'Aborted',
  592. status: 602,
  593. data: data,
  594. options: options
  595. });
  596. },
  597. onerror(data) {
  598. resolve({
  599. result: 'Error',
  600. statusText: 'Error',
  601. status: 603,
  602. data: data,
  603. options: options
  604. });
  605. },
  606. onload(data) {
  607. const headers = {};
  608. data.responseHeaders?.split('\n').forEach(header => {
  609. const headerArr = header.trim().split(':');
  610. const name = headerArr.shift()?.trim() || '';
  611. const value = headerArr.join(':').trim();
  612. if (name && value) {
  613. if (headers[name]) {
  614. if (Array.isArray(headers[name])) {
  615. headers[name].push(value);
  616. } else {
  617. headers[name] = [ headers[name], value ];
  618. }
  619. } else {
  620. headers[name] = value;
  621. }
  622. }
  623. });
  624. if (headers['set-cookie'] && !Array.isArray(headers['set-cookie'])) {
  625. headers['set-cookie'] = [ headers['set-cookie'] ];
  626. }
  627. data.responseHeadersText = data.responseHeaders;
  628. data.responseHeaders = headers;
  629. data.finalUrl = data.responseHeaders?.location || data.finalUrl;
  630. if (options.responseType === 'json' && data?.response && typeof data.response !== 'object') {
  631. try {
  632. data.response = JSON.parse(data.responseText);
  633. } catch (error) {}
  634. }
  635. resolve({
  636. result: 'Success',
  637. statusText: 'Load',
  638. status: 600,
  639. data: data,
  640. options: options
  641. });
  642. }
  643. },
  644. ...options
  645. };
  646. GM_xmlhttpRequest(requestObj);
  647. });
  648. if (window.DEBUG) {
  649. console.log('%cAuto-Task[httpRequest]:', 'color:blue', JSON.stringify(result));
  650. }
  651. if (result.status !== 600 && times < 2) {
  652. return await httpRequest(options, times + 1);
  653. }
  654. return result;
  655. } catch (error) {
  656. console.log('%cAuto-Task[httpRequest]:', 'color:red', JSON.stringify({
  657. errorMsg: error,
  658. options: options
  659. }));
  660. throwError(error, 'httpRequest');
  661. return {
  662. result: 'JsError',
  663. statusText: 'Error',
  664. status: 604,
  665. error: error,
  666. options: options
  667. };
  668. }
  669. };
  670. const tools_httpRequest = httpRequest;
  671. const echoLog = ({
  672. type,
  673. text,
  674. html,
  675. id
  676. }) => {
  677. const emptyStatus = {
  678. success: () => emptyStatus,
  679. error: () => emptyStatus,
  680. warning: () => emptyStatus,
  681. info: () => emptyStatus,
  682. view: () => emptyStatus
  683. };
  684. try {
  685. let ele;
  686. if (type) {
  687. switch (type) {
  688. case 'joiningSteamGroup':
  689. case 'leavingSteamGroup':
  690. case 'gettingSteamGroupId':
  691. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/groups/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  692. break;
  693.  
  694. case 'joiningSteamOfficialGroup':
  695. case 'leavingSteamOfficialGroup':
  696. case 'gettingSteamOfficialGroupId':
  697. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/games/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  698. break;
  699.  
  700. case 'subscribingForum':
  701. case 'unsubscribingForum':
  702. case 'gettingForumId':
  703. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/app/${text}/discussions/" target="_blank">${text}</a>]...<font></font></li>`);
  704. break;
  705.  
  706. case 'followingCurator':
  707. case 'unfollowingCurator':
  708. case 'gettingCuratorId':
  709. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/${text?.includes('/') ? text : `curator/${text}`}" target="_blank">${text}</a>]...<font></font></li>`);
  710. break;
  711.  
  712. case 'addingToWishlist':
  713. case 'removingFromWishlist':
  714. case 'followingGame':
  715. case 'unfollowingGame':
  716. case 'gettingSubid':
  717. case 'addingFreeLicense':
  718. case 'requestingPlayTestAccess':
  719. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/app/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  720. break;
  721.  
  722. case 'addingFreeLicenseSubid':
  723. ele = $(`<li>${i18n('addingFreeLicense')}[<a href="https://steamdb.info/sub/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  724. break;
  725.  
  726. case 'favoritingWorkshop':
  727. case 'unfavoritingWorkshop':
  728. case 'gettingWorkshopAppId':
  729. case 'votingUpWorkshop':
  730. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/sharedfiles/filedetails/?id=${text}" target="_blank">
  731. ${text}</a>]...<font></font></li>`);
  732. break;
  733.  
  734. case 'gettingAnnouncementParams':
  735. case 'likingAnnouncement':
  736. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/news/app/${text}/view/${id}" target="_blank">
  737. ${id}</a>]...<font></font></li>`);
  738. break;
  739.  
  740. case 'joiningDiscordServer':
  741. case 'gettingDiscordGuild':
  742. ele = $(`<li>${i18n(type)}[<a href="https://discord.com/invite/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  743. break;
  744.  
  745. case 'leavingDiscordServer':
  746. ele = $(`<li>${i18n(type)}[<a href="https://discord.com/channels/@me/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  747. break;
  748.  
  749. case 'updateDiscordAuth':
  750. ele = $(`<li style="color:red;">${i18n('updateDiscordAuth')}</li>`);
  751. break;
  752.  
  753. case 'followingTwitchChannel':
  754. case 'unfollowingTwitchChannel':
  755. case 'gettingTwitchChannelId':
  756. ele = $(`<li>${i18n(type)}[<a href="https://www.twitch.tv/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  757. break;
  758.  
  759. case 'gettingInsUserId':
  760. case 'followingIns':
  761. case 'unfollowingIns':
  762. ele = $(`<li>${i18n(type)}[<a href="https://www.instagram.com/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  763. break;
  764.  
  765. case 'gettingTwitterUserId':
  766. case 'followingTwitterUser':
  767. case 'unfollowingTwitterUser':
  768. ele = $(`<li>${i18n(type)}[<a href="https://x.com/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  769. break;
  770.  
  771. case 'retweetting':
  772. case 'unretweetting':
  773. ele = $(`<li>${i18n(type)}${text}...<font></font></li>`);
  774. break;
  775.  
  776. case 'joiningReddit':
  777. case 'leavingReddit':
  778. ele = $(`<li>${i18n(type)}[<a href="https://www.reddit.com/r/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  779. break;
  780.  
  781. case 'followingRedditUser':
  782. case 'unfollowingRedditUser':
  783. ele = $(`<li>${i18n(type)}[<a href="https://www.reddit.com/user/${text?.replace('u_', '')}" target="_blank">
  784. ${text?.replace('u_', '')}</a>]...<font></font></li>`);
  785. break;
  786.  
  787. case 'followingYtbChannel':
  788. case 'unfollowingYtbChannel':
  789. ele = $(`<li>${i18n(type)}[<a href="https://www.youtube.com/channel/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  790. break;
  791.  
  792. case 'likingYtbVideo':
  793. case 'unlikingYtbVideo':
  794. ele = $(`<li>${i18n(type)}[<a href="https://www.youtube.com/watch?v=${text}" target="_blank">${text}</a>]...<font></font></li>`);
  795. break;
  796.  
  797. case 'gettingVkId':
  798. case 'joiningVkGroup':
  799. case 'leavingVkGroup':
  800. case 'joiningVkPublic':
  801. case 'leavingVkPublic':
  802. case 'sendingVkWall':
  803. case 'deletingVkWall':
  804. ele = $(`<li>${i18n(type)}[<a href="https://vk.com/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  805. break;
  806.  
  807. case 'visitingLink':
  808. ele = $(`<li>${i18n('visitingLink')}[<a href="${text}" target="_blank">${text}</a>]...<font></font></li>`);
  809. break;
  810.  
  811. case 'verifyingInsAuth':
  812. case 'text':
  813. ele = $(`<li>${i18n(text)}<font></font></li>`);
  814. break;
  815.  
  816. case 'html':
  817. ele = $(text || html);
  818. break;
  819.  
  820. case 'whiteList':
  821. ele = $(`<li><font class="warning">${i18n('skipTask')}[${text}(${id})](${i18n('whiteList')})</font></li>`);
  822. break;
  823.  
  824. case 'globalOptionsSkip':
  825. ele = $(`<li>${i18n('skipTaskOption')}<font class="warning">${text}</font></li>`);
  826. break;
  827.  
  828. default:
  829. ele = $(`<li>${i18n('unKnown')}:${type}(${text})...<font></font></li>`);
  830. break;
  831. }
  832. } else if (text) {
  833. ele = $(`<li>${i18n(text)}<font></font></li>`);
  834. } else if (html) {
  835. ele = $(html);
  836. } else {
  837. ele = $('<li><font></font></li>');
  838. }
  839. ele.addClass('card-text');
  840. $('#auto-task-info').append(ele);
  841. ele[0]?.scrollIntoView();
  842. const font = ele.find('font');
  843. const status = {
  844. font: font,
  845. success(text = 'Success', html = false) {
  846. this.font?.attr('class', '').addClass('success');
  847. html ? this.font?.html(text) : this.font?.text(text);
  848. return this;
  849. },
  850. error(text = 'Error', html = false) {
  851. this.font?.attr('class', '').addClass('error');
  852. html ? this.font?.html(text) : this.font?.text(text);
  853. return this;
  854. },
  855. warning(text = 'Warning', html = false) {
  856. this.font?.attr('class', '').addClass('warning');
  857. html ? this.font?.html(text) : this.font?.text(text);
  858. return this;
  859. },
  860. info(text = 'Info', html = false) {
  861. this.font?.attr('class', '').addClass('info');
  862. html ? this.font?.html(text) : this.font?.text(text);
  863. return this;
  864. },
  865. view() {
  866. this.font?.[0].scrollIntoView();
  867. return this;
  868. }
  869. };
  870. return status;
  871. } catch (error) {
  872. throwError(error, 'echoLog');
  873. return emptyStatus;
  874. }
  875. };
  876. const scripts_echoLog = echoLog;
  877. const unique = array => {
  878. try {
  879. return [ ...new Set(array) ];
  880. } catch (error) {
  881. throwError(error, 'unique');
  882. return [];
  883. }
  884. };
  885. const delay = (time = 1e3) => new Promise(resolve => {
  886. setTimeout(() => {
  887. resolve(true);
  888. }, time);
  889. });
  890. const getRedirectLink = async link => {
  891. try {
  892. if (!link) {
  893. return null;
  894. }
  895. const redirectLinksCache = GM_getValue('redirectLinks') || {};
  896. if (redirectLinksCache[link]) {
  897. redirectLinksCache[link];
  898. }
  899. return await tools_httpRequest({
  900. url: link,
  901. method: 'GET'
  902. }).then(({
  903. data
  904. }) => {
  905. if (data?.finalUrl) {
  906. redirectLinksCache[link] = data.finalUrl;
  907. GM_setValue('redirectLinks', redirectLinksCache);
  908. return data.finalUrl;
  909. }
  910. return null;
  911. });
  912. } catch (error) {
  913. throwError(error, 'getRedirectLink');
  914. return null;
  915. }
  916. };
  917. const visitLink = async (link, options) => {
  918. try {
  919. const logStatus = scripts_echoLog({
  920. type: 'visitLink',
  921. text: link
  922. });
  923. return await tools_httpRequest({
  924. url: link,
  925. method: 'GET',
  926. ...options
  927. }).then(({
  928. result,
  929. statusText,
  930. status
  931. }) => {
  932. if (result === 'Success') {
  933. logStatus.success();
  934. return true;
  935. }
  936. logStatus.error(`${result}:${statusText}(${status})`);
  937. return false;
  938. });
  939. } catch (error) {
  940. throwError(error, 'visitLink');
  941. return false;
  942. }
  943. };
  944. const getUrlQuery = url => {
  945. try {
  946. const query = {};
  947. if (url) {
  948. if (url.includes('?')) {
  949. url.split('?')[1].replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  950. query[key] = value;
  951. return str;
  952. });
  953. }
  954. } else {
  955. window.location.search.replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  956. query[key] = value;
  957. return str;
  958. });
  959. }
  960. return query;
  961. } catch (error) {
  962. throwError(error, 'getUrlQuery');
  963. return {};
  964. }
  965. };
  966. const getUuid = () => {
  967. const uuidUrl = URL.createObjectURL(new Blob()).toString();
  968. return uuidUrl.slice(uuidUrl.lastIndexOf('/') + 1);
  969. };
  970. const stringToColour = str => {
  971. try {
  972. let hash = 0;
  973. for (let i = 0; i < str.length; i++) {
  974. hash = str.charCodeAt(i) + ((hash << 5) - hash);
  975. }
  976. let colour = '#';
  977. for (let i = 0; i < 3; i++) {
  978. const value = hash >> i * 8 & 255;
  979. colour += `00${value.toString(16)}`.slice(-2);
  980. }
  981. return colour;
  982. } catch (error) {
  983. throwError(error, 'stringToColour');
  984. return '#fff';
  985. }
  986. };
  987. const defaultGlobalOptions = {
  988. doTask: {
  989. discord: {
  990. servers: true
  991. },
  992. instagram: {
  993. users: true
  994. },
  995. twitch: {
  996. channels: true
  997. },
  998. twitter: {
  999. users: true,
  1000. retweets: true
  1001. },
  1002. vk: {
  1003. names: true
  1004. },
  1005. youtube: {
  1006. channels: true,
  1007. likes: true
  1008. },
  1009. reddit: {
  1010. reddits: true
  1011. },
  1012. steam: {
  1013. groups: true,
  1014. officialGroups: true,
  1015. wishlists: true,
  1016. follows: true,
  1017. forums: true,
  1018. workshops: true,
  1019. curators: true,
  1020. workshopVotes: true,
  1021. announcements: true,
  1022. licenses: true,
  1023. playtests: true
  1024. }
  1025. },
  1026. undoTask: {
  1027. discord: {
  1028. servers: true
  1029. },
  1030. instagram: {
  1031. users: true
  1032. },
  1033. twitch: {
  1034. channels: true
  1035. },
  1036. twitter: {
  1037. users: true,
  1038. retweets: true
  1039. },
  1040. vk: {
  1041. names: true
  1042. },
  1043. youtube: {
  1044. channels: true,
  1045. likes: true
  1046. },
  1047. reddit: {
  1048. reddits: true
  1049. },
  1050. steam: {
  1051. groups: true,
  1052. officialGroups: true,
  1053. wishlists: true,
  1054. follows: true,
  1055. forums: true,
  1056. workshops: true,
  1057. curators: true
  1058. }
  1059. },
  1060. ASF: {
  1061. AsfEnabled: false,
  1062. AsfIpcUrl: '',
  1063. AsfIpcPassword: '',
  1064. AsfBotname: 'asf'
  1065. },
  1066. position: {
  1067. buttonSideX: 'right',
  1068. buttonSideY: 'top',
  1069. buttonDistance: '15,30',
  1070. showButtonSideX: 'right',
  1071. showButtonSideY: 'top',
  1072. showButtonDistance: '15,30',
  1073. logSideX: 'right',
  1074. logSideY: 'bottom',
  1075. logDistance: '10,10'
  1076. },
  1077. hotKey: {
  1078. doTaskKey: 'alt + d',
  1079. undoTaskKey: 'alt + u',
  1080. toggleLogKey: 'alt + l'
  1081. },
  1082. other: {
  1083. twitterVerifyId: '783214',
  1084. youtubeVerifyChannel: 'UCrXUsMBcfTVqwAS7DKg9C0Q',
  1085. autoUpdateSource: 'jsdelivr',
  1086. language: 'zh',
  1087. checkLogin: true,
  1088. checkLeftKey: true,
  1089. defaultShowButton: true,
  1090. defaultShowLog: true,
  1091. debug: false,
  1092. receivePreview: true
  1093. }
  1094. };
  1095. const userDefinedGlobalOptions = GM_getValue('globalOptions') || {};
  1096. const assignObject = (obj1, obj2) => {
  1097. try {
  1098. const newObj = {};
  1099. for (const [ key, value ] of Object.entries(obj1)) {
  1100. if (Object.prototype.toString.call(value) === '[object Object]' && Object.prototype.toString.call(obj2[key]) === '[object Object]') {
  1101. newObj[key] = assignObject(value, obj2[key]);
  1102. } else {
  1103. newObj[key] = obj2[key] ?? value;
  1104. }
  1105. }
  1106. return newObj;
  1107. } catch (error) {
  1108. throwError(error, 'assignObject');
  1109. return defaultGlobalOptions;
  1110. }
  1111. };
  1112. const globalOptions = assignObject(defaultGlobalOptions, userDefinedGlobalOptions);
  1113. const saveData = () => {
  1114. try {
  1115. const data = {};
  1116. $('#globalOptionsForm').serializeArray().map(value => {
  1117. data[value.name] = value.value;
  1118. return value;
  1119. });
  1120. $.makeArray($('#globalOptionsForm input')).map(element => {
  1121. const name = $(element).attr('name');
  1122. const keys = name.split('.');
  1123. if (keys.length === 3) {
  1124. globalOptions[keys[0]][keys[1]][keys[2]] = data[name] ? data[name] === 'on' ? true : data[name] : false;
  1125. } else if (keys.length === 2) {
  1126. globalOptions[keys[0]][keys[1]] = data[name] ? data[name] === 'on' ? true : data[name] : false;
  1127. }
  1128. return element;
  1129. });
  1130. GM_setValue('globalOptions', globalOptions);
  1131. external_Swal_default().fire({
  1132. title: i18n('changeGlobalOptionsSuccess'),
  1133. icon: 'success'
  1134. });
  1135. } catch (error) {
  1136. throwError(error, 'saveData');
  1137. }
  1138. };
  1139. const changeGlobalOptions = showType => {
  1140. try {
  1141. let globalOptionsForm = `<form id="globalOptionsForm" class="auto-task-form">
  1142. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  1143. for (const [ type, data1 ] of Object.entries(globalOptions)) {
  1144. for (const [ option, data2 ] of Object.entries(data1)) {
  1145. if ([ 'other', 'position', 'hotKey', 'ASF' ].includes(type)) {
  1146. if (typeof data2 === 'boolean') {
  1147. 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>`;
  1148. } else {
  1149. 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>`;
  1150. }
  1151. } else {
  1152. for (const [ socialType, data3 ] of Object.entries(data2)) {
  1153. 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>`;
  1154. }
  1155. }
  1156. }
  1157. }
  1158. globalOptionsForm += '</tbody></table></form>';
  1159. if (showType === 'swal') {
  1160. external_Swal_default().fire({
  1161. title: i18n('globalOptions'),
  1162. html: globalOptionsForm,
  1163. showConfirmButton: true,
  1164. confirmButtonText: i18n('save'),
  1165. showCancelButton: true,
  1166. cancelButtonText: i18n('close')
  1167. }).then(({
  1168. isConfirmed
  1169. }) => {
  1170. if (isConfirmed) {
  1171. saveData();
  1172. }
  1173. });
  1174. } else {
  1175. $('body').append(`<h2>${i18n('globalOptions')}</h2>${globalOptionsForm}`);
  1176. }
  1177. } catch (error) {
  1178. throwError(error, 'changeGlobalOptions');
  1179. }
  1180. };
  1181. const data = {
  1182. website: '网站',
  1183. type: '类型',
  1184. edit: '编辑',
  1185. whiteList: '白名单',
  1186. skipTask: '跳过撤销任务',
  1187. whiteListOptions: '白名单设置',
  1188. changeWhiteListOption: '设置白名单(%0)',
  1189. whiteListNotFound: '找不到此项白名单: %0',
  1190. changeWhiteListSuccess: '白名单修改成功,刷新生效!',
  1191. changeWebsiteOptions: '网站设置',
  1192. changeGlobalOptions: '全局设置',
  1193. ok: '是',
  1194. save: '保存',
  1195. close: '关闭',
  1196. return: '返回',
  1197. option: '选项',
  1198. value: '值',
  1199. websiteOptions: '当前网站设置',
  1200. changeWebsiteOptionsSuccess: '更改当前网站设置成功,刷新生效!',
  1201. changeGlobalOptionsSuccess: '更改全局设置成功,刷新生效!',
  1202. needLogin: '请先登录!',
  1203. getTasksInfo: '正在获取并处理任务信息...',
  1204. gettingKey: '正在获取Key...',
  1205. verifyingTask: '正在验证任务',
  1206. notice: '自动任务脚本提醒',
  1207. noKeysLeft: '此页面已经没有剩余key了,是否关闭?',
  1208. giveawayEnded: '此活动已结束,是否关闭?',
  1209. giveawayNotWork: '此活动因某些原因(已结束/暂停/未开始...)不可用(如果是脚本误判请及时反馈),是否关闭?',
  1210. confirm: '确定',
  1211. cancel: '取消',
  1212. unKnown: '未知',
  1213. unKnownTaskType: '未识别的任务',
  1214. doing: '正在做任务',
  1215. allTasksComplete: '所有任务已完成!',
  1216. getTaskIdFailed: '获取任务Id失败!',
  1217. initSuccess: '%0 初始化成功!',
  1218. initFailed: '%0 初始化失败!',
  1219. errorLink: '链接错误: %0',
  1220. needInit: '请先初始化',
  1221. verifyingAuth: '正在验证%0凭证...',
  1222. updatingAuth: '正在更新%0凭证...',
  1223. refreshingToken: '正在刷新%0凭证...',
  1224. settingToken: '正在设置%0凭证...',
  1225. steamStoreTab: 'Steam商店(弹窗)',
  1226. steamCommunityTab: 'Steam社区(弹窗)',
  1227. initing: '正在初始化...',
  1228. getFailed: '获取%0失败!',
  1229. checkLoginFailed: '检测登录状态失败!',
  1230. checkLeftKeyFailed: '检测剩余Key失败!',
  1231. userId: '用户Id',
  1232. joiningGiveaway: '正在加入赠Key',
  1233. needJoinGiveaway: '需要先加入赠Key',
  1234. cannotUndo: '此网站不支持取消任务',
  1235. verifyAuth: '正在验证 %0 凭证...',
  1236. closePageNotice: '如果此页面没有自动关闭,请自行关闭本页面。',
  1237. errorReport: '检测到脚本报错,是否前往反馈BUG?',
  1238. visitingLink: '正在访问链接: ',
  1239. doTask: '做任务',
  1240. undoTask: '撤销任务',
  1241. verifyTask: '验证任务',
  1242. getKey: '获取Key',
  1243. selectAll: '全选',
  1244. selectNone: '全不选',
  1245. invertSelect: '反选',
  1246. doFreeTask: '加入免费赠品',
  1247. doPointTask: '加入点数赠品',
  1248. skipTaskOption: '设置中已配置跳过任务',
  1249. other: '其他',
  1250. globalOptions: '全局设置',
  1251. checkLogin: '登录检测</br>需要登录的网站自动登录,部分网站支持',
  1252. checkLeftKey: '剩余Key检测</br>赠Key活动结束提示是否关闭,部分网站支持',
  1253. twitterVerifyId: '通过尝试关注该账号验证Twitter凭证</br>默认为Twitter官方帐号 783214</br>不想关注官方账号可以改为自己的帐号',
  1254. youtubeVerifyChannel: '通过尝试订阅该频道验证YouTube凭证</br>默认为YouTube官方频道 UCrXUsMBcfTVqwAS7DKg9C0Q</br>不想关注官方频道可以改为自己的频道',
  1255. autoUpdateSource: '更新源</br>github: 需代理,实时更新</br>jsdelivr: 可不用代理,更新有延迟</br>standby: 备用</br>auto: 依次使用github, jsdelivr, standby源进行尝试更新',
  1256. saveGlobalOptions: '保存设置',
  1257. settingPage: '设置页面',
  1258. name: '名称',
  1259. version: '版本',
  1260. scriptManager: '脚本管理器',
  1261. script: '脚本',
  1262. environment: '环境',
  1263. os: '系统',
  1264. browser: '浏览器',
  1265. getId: '获取 %0 id',
  1266. getTwitterUserId: '获取Twitter用户id(获取id功能仅在设置页面可用)',
  1267. getYoutubeChannelId: '获取Youtube频道id(获取id功能仅在设置页面可用)',
  1268. showButton: '显示按钮',
  1269. hideButton: '隐藏按钮',
  1270. showLog: '显示日志',
  1271. hideLog: '隐藏日志',
  1272. defaultShowButton: '默认显示按钮',
  1273. defaultShowLog: '默认显示日志',
  1274. debug: '输出调试日志,不要开启此选项!',
  1275. receivePreview: '接收预览版更新',
  1276. position: '组件位置',
  1277. buttonSideX: '按钮区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1278. buttonSideY: '按钮区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1279. buttonDistance: '按钮区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1280. showButtonSideX: '显示按钮水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1281. showButtonSideY: '显示按钮垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1282. showButtonDistance: '显示按钮距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1283. logSideX: '日志区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1284. logSideY: '日志区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1285. logDistance: '日志区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1286. hotKey: '快捷键',
  1287. doTaskKey: '做任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1288. undoTaskKey: '撤销任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1289. toggleLogKey: '显示/隐藏日志快捷键</br>(实时预览功能仅在设置页面可用)',
  1290. tasksHistory: '任务历史',
  1291. clearHistory: '清空历史',
  1292. clearHistoryFinished: '已清空任务历史!',
  1293. deleteTask: '删除任务',
  1294. lastChangeTime: '最后一次修改时间',
  1295. clearTaskFinished: '删除以下任务完成!',
  1296. clearTaskFailed: '删除任务失败,没有找到任务名!',
  1297. syncData: '数据同步',
  1298. settingData: '正在上传数据...',
  1299. gettingData: '正在获取数据...',
  1300. help: '帮助',
  1301. fileName: '文件名',
  1302. upload2gist: '同步到Gist',
  1303. downloadFromGist: '从Gist同步',
  1304. saveAndTest: '保存配置并测试',
  1305. testSuccess: '测试成功!',
  1306. testFailed: '测试失败!',
  1307. saveAndTestNotice: '请先保存配置并测试!',
  1308. processingData: '正在处理数据...',
  1309. updatingData: '正在上传数据...',
  1310. syncDataSuccess: '同步数据成功!',
  1311. syncDataFailed: '同步数据失败,请在控制台查看错误信息!',
  1312. downloadingData: '正在下载数据...',
  1313. checkedNoData: '没有检测到远程数据,请确认配置是否正确!',
  1314. savingData: '正在保存数据...',
  1315. syncHistory: '同步任务历史',
  1316. checkUpdateFailed: '检测更新失败',
  1317. newVersionNotice: '检测到新版本V%0, <a class="high-light" href="%1" target="_blank">点此更新</a>',
  1318. language: '语言</br>目前仅支持zh: 中文, en: 英文',
  1319. gistOptions: 'Gist 设置',
  1320. swalNotice: '检测到您第一次安装V4版本脚本,请前往阅读用前必读内容!',
  1321. echoNotice: '检测到您第一次安装V4版本脚本,请<a class="high-light" href="%0" target="_blank">点此前往</a>阅读用前必读内容!',
  1322. noticeLink: 'https://auto-task-doc.js.org/guide/#用前必读',
  1323. toGithub: '前往Github反馈',
  1324. toKeylol: '前往其乐论坛反馈',
  1325. copySuccess: '错误信息已复制到剪切板,是否前往其乐论坛反馈?',
  1326. copyFailed: '请复制下方错误信息后前往Keylol论坛反馈!',
  1327. updateText: '%0 版本更新内容:',
  1328. Active: '进行中',
  1329. Ended: '已结束',
  1330. Banned: '已封禁',
  1331. Paused: '已暂停',
  1332. notStart: '未开始',
  1333. noRemoteData: '检测到远程无数据',
  1334. errorRemoteDataFormat: '远程数据格式错误',
  1335. updateHistory: '历史更新记录<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">点此查看</a>',
  1336. AsfEnabled: '使用ASF做Steam相关任务(需<a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a>插件)',
  1337. AsfIpcUrl: 'ASF IPC 地址',
  1338. AsfIpcPassword: 'ASF IPC 密码',
  1339. versionNotMatched: '脚本管理器版本过低,需TamperMonkey >= 5.2.0或TamperMonkey Beta >= 5.2.6196',
  1340. groups: '组',
  1341. officialGroups: '官方组',
  1342. wishlists: '愿望单',
  1343. follows: '游戏关注',
  1344. forums: '论坛',
  1345. workshops: '创意工坊收藏',
  1346. curators: '鉴赏家',
  1347. workshopVotes: '创意工坊点赞',
  1348. announcements: '社区通知',
  1349. steamCommunity: 'Steam社区',
  1350. steamStore: 'Steam商店',
  1351. licenses: '入库免费游戏',
  1352. playtests: '请求访问权限',
  1353. needLoginSteamStore: '请先<a href="https://store.steampowered.com/login/" target="_blank">登录Steam商店</a>',
  1354. needLoginSteamCommunity: '请先<a href="https://steamcommunity.com/login/home/" target="_blank">登录Steam社区</a>',
  1355. joiningSteamGroup: '正在加入Steam组',
  1356. leavingSteamGroup: '正在退出Steam组',
  1357. gettingSteamGroupId: '正在获取Steam组Id',
  1358. joiningSteamOfficialGroup: '正在加入Steam官方组',
  1359. leavingSteamOfficialGroup: '正在退出Steam官方组',
  1360. gettingSteamOfficialGroupId: '正在获取Steam官方组Id',
  1361. subscribingForum: '正在订阅Steam论坛',
  1362. unsubscribingForum: '正在取消订阅Steam论坛',
  1363. gettingForumId: '正在获取Steam论坛Id',
  1364. followingCurator: '正在关注Steam鉴赏家',
  1365. unfollowingCurator: '正在取关Steam鉴赏家',
  1366. gettingCuratorId: '正在获取Steam鉴赏家Id',
  1367. addingToWishlist: '正在添加游戏到Steam愿望单',
  1368. removingFromWishlist: '正在从Steam愿望单移除游戏',
  1369. followingGame: '正在关注Steam游戏',
  1370. unfollowingGame: '正在取关Steam游戏',
  1371. favoritingWorkshop: '正在收藏Steam创意工坊物品',
  1372. unfavoritingWorkshop: '正在取消收藏Steam创意工坊物品',
  1373. gettingWorkshopAppId: '正在获取Steam创意工坊物品Id',
  1374. votingUpWorkshop: '正在点赞Steam创意工坊物品',
  1375. gettingAnnouncementParams: '正在获取Steam通知信息',
  1376. likingAnnouncement: '正在点赞Steam通知',
  1377. changingArea: '正在更换Steam地区: %0...',
  1378. notNeededChangeArea: '当前地区不需要更换',
  1379. noAnotherArea: '请检测是否开启正确开启代理',
  1380. gettingAreaInfo: '正在获取Steam地区信息...',
  1381. changeAreaNotice: '疑似锁区游戏,尝试换区执行',
  1382. steamFinishNotice: 'Steam任务完成,尝试将购物车地区换回',
  1383. gettingSubid: '正在获取游戏subid',
  1384. addingFreeLicense: '正在入库',
  1385. missParams: '缺少参数',
  1386. gettingLicenses: '正在获取Licenses...',
  1387. requestingPlayTestAccess: '正在请求访问权限',
  1388. tryChangeAreaNotice: '此功能无法检测游戏是否限区,因此会尝试换区后再入库,换区失败也不影响后续入库',
  1389. gettingUserLink: '正在获取Steam用户社区链接...',
  1390. retry: '重试',
  1391. owned: '已拥有',
  1392. redirect: '重定向',
  1393. noSubid: '无法获取,跳过',
  1394. initingASF: '正在初始化ASF...',
  1395. servers: '服务器',
  1396. joiningDiscordServer: '正在加入Discord服务器',
  1397. leavingDiscordServer: '正在退出Discord服务器',
  1398. gettingDiscordGuild: '正在获取Discord服务器Id',
  1399. getDiscordAuthFailed: '获取Discord凭证失败,请检测Discord帐号是否已登录',
  1400. discordImportantNotice: '重要提醒!!!',
  1401. discordImportantNoticeText: '由于Discord网站后台更新,目前使用此脚本加组后可能会导致Discord帐号被强制退出,且需要两步验证才能正常登录,请谨慎使用!!!',
  1402. continue: '继续',
  1403. skipDiscordTask: '跳过Discord任务',
  1404. continueAndDontRemindAgain: '继续且不再提醒',
  1405. users: '用户',
  1406. loginIns: '请先<a href="https://www.instagram.com/accounts/login/" target="_blank">登录Instagram</a>',
  1407. insBanned: '您的Instagram账户已被封禁',
  1408. verifyingInsAuth: '正在验证Instagram凭证...',
  1409. gettingInsUserId: '正在获取Instagram用户Id',
  1410. followingIns: '正在关注Instagram用户',
  1411. unfollowingIns: '正在取关Instagram用户',
  1412. reddits: '社区/用户',
  1413. loginReddit: '请先<a href="https://www.reddit.com/login/" target="_blank">登录Reddit</a>',
  1414. changingRedditVersion: '正在切换Reddit为新版页面...',
  1415. joiningReddit: '正在加入Reddit社区',
  1416. leavingReddit: '正在退出Reddit社区',
  1417. followingRedditUser: '正在关注Reddit用户',
  1418. unfollowingRedditUser: '正在取关Reddit用户',
  1419. channels: '频道',
  1420. followingTwitchChannel: '正在关注Twitch频道',
  1421. unfollowingTwitchChannel: '正在取关Twitch频道',
  1422. gettingTwitchChannelId: '正在获取Twitch频道Id',
  1423. checkingTwitchIntegrity: '正在检查Twitch完整性...',
  1424. twitterUser: '推特用户',
  1425. retweets: '转推',
  1426. gettingTwitterUserId: '正在获取推特用户Id',
  1427. followingTwitterUser: '正在关注推特用户',
  1428. unfollowingTwitterUser: '正在取关推特用户',
  1429. retweetting: '正在转推',
  1430. unretweetting: '正在撤销转推',
  1431. names: '组/社区/动态',
  1432. loginVk: '请先<a href="https://vk.com/login/" target="_blank">登录Vk</a>',
  1433. gettingVkId: '正在获取Vk任务Id',
  1434. joiningVkGroup: '正在加入Vk组',
  1435. leavingVkGroup: '正在退出Vk组',
  1436. joiningVkPublic: '正在加入Vk社区',
  1437. leavingVkPublic: '正在退出Vk社区',
  1438. sendingVkWall: '正在转发Vk动态',
  1439. deletingVkWall: '正在撤销转发Vk动态',
  1440. youtubeChannel: 'YouTube频道',
  1441. likes: '点赞',
  1442. loginYtb: '请先<a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">登录YouTube</a>',
  1443. tryUpdateYtbAuth: '请尝试<a href="https://www.youtube.com/#auth" target="_blank">更新YouTube凭证</a>',
  1444. gettingYtbToken: '正在获取YouTube Token...',
  1445. followingYtbChannel: '正在订阅YouTube频道',
  1446. unfollowingYtbChannel: '正在退订YouTube频道',
  1447. likingYtbVideo: '正在点赞YouTube视频',
  1448. unlikingYtbVideo: '正在取消点赞YouTube视频',
  1449. giveKeyNoticeBefore: '每次验证间隔15s',
  1450. giveKeyNoticeAfter: '如果没有key, 请在<a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>查看',
  1451. noPoints: '点数不够,跳过抽奖',
  1452. getNeedPointsFailed: '获取所需点数失败,跳过抽奖',
  1453. joiningLottery: '正在加入抽奖',
  1454. doingGleamTask: '正在做Gleam任务...',
  1455. gettingGleamLink: '正在获取Gleam任务链接...',
  1456. gleamTaskNotice: '如果此页面长时间未关闭,请完成任一任务后自行关闭!',
  1457. verifiedGleamTasks: '已尝试验证所有任务,验证失败的任务请尝试手动验证或完成!',
  1458. campaign: '检测到人机验证,请完成验证后重新验证任务!',
  1459. gsNotice: '为避免得到"0000-0000-0000"key, 已自动屏蔽"Grab Key"按钮,获取key时请关闭脚本!',
  1460. giveeClubVerifyNotice: '正在验证任务...',
  1461. giveeClubVerifyFinished: '请等待验证完成后自行加入赠Key',
  1462. doingKeyhubTask: '正在做Keyhub任务...',
  1463. SweepWidgetNotice: '正在处理并验证任务,每次验证任务有1~3s间隔防止触发验证过快警告...',
  1464. tasksNotCompleted: '任务未完成',
  1465. confirmingTask: '正在跳过警告页面...'
  1466. };
  1467. const zh_CN = data;
  1468. const en_US_data = {
  1469. website: 'Website',
  1470. type: 'Type',
  1471. edit: 'Edit',
  1472. whiteList: 'Whitelist',
  1473. skipTask: 'Skip undo task',
  1474. whiteListOptions: 'Whitelist options',
  1475. changeWhiteListOption: 'Whitelist option(%0)',
  1476. whiteListNotFound: 'Cannot find this whitelist: %0',
  1477. changeWhiteListSuccess: 'The whitelist is successfully modified, and the page refresh will take effect!',
  1478. changeWebsiteOptions: 'Website options',
  1479. changeGlobalOptions: 'Global options',
  1480. ok: 'OK',
  1481. save: 'Save',
  1482. close: 'Close',
  1483. return: 'Return',
  1484. option: 'Option',
  1485. value: 'Value',
  1486. websiteOptions: 'Current website settings',
  1487. changeWebsiteOptionsSuccess: 'The current website setting is changed successfully, and the page refresh will take effect!',
  1488. changeGlobalOptionsSuccess: 'The global setting is changed successfully, and the refresh will take effect!',
  1489. needLogin: 'Please log in first!',
  1490. getTasksInfo: 'Obtaining and processing task information...',
  1491. gettingKey: 'Getting Key...',
  1492. verifyingTask: 'Verifying task',
  1493. notice: 'Automatic task script notice',
  1494. noKeysLeft: 'There are no more keys left on this page. Do you want to close it?',
  1495. giveawayEnded: 'This event has ended, do you want to close it?',
  1496. 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?',
  1497. confirm: 'Confirm',
  1498. cancel: 'Cancel',
  1499. unKnown: 'Unknown',
  1500. unKnownTaskType: 'Unrecognized task',
  1501. doing: 'Doing a task',
  1502. allTasksComplete: 'All tasks have been completed!',
  1503. getTaskIdFailed: 'Failed to obtain task Id!',
  1504. initSuccess: '%0 was initialized successfully!',
  1505. initFailed: '%0 initialization failed!',
  1506. errorLink: 'Link error: %0',
  1507. needInit: 'Please initialize first',
  1508. verifyingAuth: 'Verifying %0 token...',
  1509. updatingAuth: 'Update %0 token...',
  1510. refreshingToken: 'Refreshing %0 token...',
  1511. settingToken: 'Setting %0 token...',
  1512. steamStoreTab: 'Steam store (new tab)',
  1513. steamCommunityTab: 'Steam community(new tab)',
  1514. initing: 'Initializing...',
  1515. getFailed: 'Failed to get %0!',
  1516. checkLoginFailed: 'Failed to detect login status!',
  1517. checkLeftKeyFailed: 'Failed to detect the remaining keys!',
  1518. userId: 'User Id',
  1519. joiningGiveaway: 'Joining giveaway',
  1520. needJoinGiveaway: 'Need to join the giveaway first',
  1521. cannotUndo: 'This website does not support canceling tasks',
  1522. verifyAuth: 'Verifying %0 token...',
  1523. closePageNotice: 'f this page does not close automatically, please close this page yourself.',
  1524. errorReport: 'A script error is detected, do you want to report the BUG?',
  1525. visitingLink: 'Visiting link: ',
  1526. doTask: 'DoTask',
  1527. undoTask: 'UndoTask',
  1528. verifyTask: 'Verify',
  1529. getKey: 'GetKey',
  1530. selectAll: 'SelectAll',
  1531. selectNone: 'SelectNone',
  1532. invertSelect: 'InvertSelect',
  1533. doFreeTask: 'FreeTask',
  1534. doPointTask: 'PointTask',
  1535. skipTaskOption: 'Skip task has been configured in the settings',
  1536. other: 'Other',
  1537. globalOptions: 'Global Options',
  1538. checkLogin: 'Login detection</br>Need to log in to the website automatically log in, part of this website supports.',
  1539. checkLeftKey: 'Key remaining detection</br>The end of the giveaway event prompts whether to close or not, part of this website supports.',
  1540. 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.',
  1541. 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.',
  1542. 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.',
  1543. saveGlobalOptions: 'SaveSettings',
  1544. settingPage: 'Setting Page',
  1545. name: 'Name',
  1546. version: 'Version',
  1547. scriptManager: 'Script Manager',
  1548. script: 'Script',
  1549. environment: 'Environment',
  1550. os: 'OS',
  1551. browser: 'Browser',
  1552. getId: 'Get %0 id',
  1553. getTwitterUserId: 'Get Twitter user id (Get id function is only available on the settings page).',
  1554. getYoutubeChannelId: 'Get Youtube channel id (Get id function is only available on the settings page).',
  1555. showButton: 'ShowButton',
  1556. hideButton: 'HideButton',
  1557. showLog: 'ShowLog',
  1558. hideLog: 'HideLog',
  1559. defaultShowButton: 'Default display button',
  1560. defaultShowLog: 'Display log by default',
  1561. debug: 'Output debug log, do not enable this option!',
  1562. receivePreview: 'Receive preview updates',
  1563. position: 'Component position',
  1564. buttonSideX: 'Horizontal positioning of the button area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1565. 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',
  1566. 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',
  1567. showButtonSideX: 'ShowButton horizontal positioning (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1568. showButtonSideY: 'ShowButton vertical positioning (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  1569. 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',
  1570. logSideX: 'Horizontal positioning of the log area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1571. logSideY: 'Vertical positioning of the log area (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  1572. 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',
  1573. hotKey: 'Shortcut key',
  1574. doTaskKey: 'DoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  1575. undoTaskKey: 'UndoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  1576. toggleLogKey: 'ShowLog/HideLog shortcut keys</br> (real-time preview function is only available on the settings page).',
  1577. tasksHistory: 'TasksHistory',
  1578. clearHistory: 'Clear history',
  1579. clearHistoryFinished: 'The mission history has been cleared!',
  1580. deleteTask: 'Delete task',
  1581. lastChangeTime: 'Last Change Time',
  1582. clearTaskFinished: 'Delete the following tasks completed!',
  1583. clearTaskFailed: 'Failed to delete the task, the task name was not found!',
  1584. syncData: 'DataSync',
  1585. settingData: 'Uploading data...',
  1586. gettingData: 'Getting data...',
  1587. help: 'Help',
  1588. fileName: 'Filename',
  1589. upload2gist: 'Sync to Gist',
  1590. downloadFromGist: 'Sync from Gist',
  1591. saveAndTest: 'Save configuration and test',
  1592. testSuccess: 'Test success!',
  1593. testFailed: 'Test failed!',
  1594. saveAndTestNotice: 'Please save the configuration and test first!',
  1595. processingData: 'Processing data...',
  1596. updatingData: 'Uploading data...',
  1597. syncDataSuccess: 'Synchronized data successfully!',
  1598. syncDataFailed: 'Failed to synchronize data, please check the error message on the console!',
  1599. downloadingData: 'Downloading data...',
  1600. checkedNoData: 'No remote data is detected, please confirm whether the configuration is correct!',
  1601. savingData: 'Saving data...',
  1602. syncHistory: 'Synchronize tasks history',
  1603. checkUpdateFailed: 'Check update failed',
  1604. newVersionNotice: 'Checked a new version V%0, <a class="high-light" href="%1" target="_blank">click to update</a>',
  1605. language: 'Language</br> Currently only supports zh: Chinese, en: English',
  1606. gistOptions: 'Gist Settings',
  1607. 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!',
  1608. 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!',
  1609. noticeLink: 'https://auto-task-doc.js.org/en/guide/#read-me-first',
  1610. toGithub: 'Feedback(Github)',
  1611. toKeylol: 'Feedback(Keylol)',
  1612. copySuccess: 'The error message has been copied to the clipboard. Do you want to go to the Keylol forum to give feedback?',
  1613. copyFailed: 'Please copy the error information below and report back to the Keylol forum!',
  1614. updateText: 'Updates in version %0:',
  1615. Active: 'Active',
  1616. Ended: 'Ended',
  1617. Banned: 'Banned',
  1618. Paused: 'Paused',
  1619. notStart: 'notStart',
  1620. noRemoteData: 'No data remotely',
  1621. errorRemoteDataFormat: 'Remote data has wrong format',
  1622. updateHistory: '<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">Click here</a>' + ' to view the historical update record.',
  1623. AsfEnabled: 'Use ASF to do Steam related tasks (requires <a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a> plugin)',
  1624. AsfIpcUrl: 'ASF IPC URL',
  1625. AsfIpcPassword: 'ASF IPC Password',
  1626. groups: 'Group',
  1627. officialGroups: 'Official Group',
  1628. wishlists: 'Wishlist',
  1629. follows: 'Follow Game',
  1630. forums: 'Forum',
  1631. workshops: 'Favorite Workshop',
  1632. curators: 'Curator',
  1633. workshopVotes: 'Voteup Workshop',
  1634. announcements: 'Announcement',
  1635. steamCommunity: 'Steam Community',
  1636. steamStore: 'Steam Store',
  1637. licenses: 'Add License',
  1638. playtests: 'Playtest Access',
  1639. needLoginSteamStore: 'Please <a href="https://store.steampowered.com/login/" target="_blank">log in to the Steam Store</a>',
  1640. needLoginSteamCommunity: 'Please <a href="https://steamcommunity.com/login/home/" target="_blank">log in to the Steam Community</a>',
  1641. joiningSteamGroup: 'Joining Steam Group',
  1642. leavingSteamGroup: 'Leaving Steam Group',
  1643. gettingSteamGroupId: 'Getting Steam Group Id',
  1644. joiningSteamOfficialGroup: 'Joining Steam Official Group',
  1645. leavingSteamOfficialGroup: 'Leaving Steam Official Group',
  1646. gettingSteamOfficialGroupId: 'Getting Steam Official Group Id',
  1647. subscribingForum: 'Subscribing the Steam Forum',
  1648. unsubscribingForum: 'Unsubscribing the Steam Forum',
  1649. gettingForumId: 'Getting Steam Forum Id',
  1650. followingCurator: 'Following Steam Curator',
  1651. unfollowingCurator: 'Unfollowing Steam Curator',
  1652. gettingCuratorId: 'Getting Steam Curator Id',
  1653. addingToWishlist: 'Adding the game to the Steam wishlist',
  1654. removingFromWishlist: 'Removing the game from the Steam wishlist',
  1655. followingGame: 'Following Steam games',
  1656. unfollowingGame: 'Unfollowing Steam games',
  1657. favoritingWorkshop: 'Favouring Steam Workshop Items',
  1658. unfavoritingWorkshop: 'Unfavoriting Steam Workshop Items',
  1659. gettingWorkshopAppId: 'Getting Steam Workshop Item Id',
  1660. votingUpWorkshop: 'Liking Steam workshop items',
  1661. gettingAnnouncementParams: 'Getting Steam announcement information',
  1662. likingAnnouncement: 'Liking Steam announcement',
  1663. changingArea: 'Changing Steam area: %0...',
  1664. notNeededChangeArea: 'The current area does not need to be changed',
  1665. noAnotherArea: 'Please check whether the proxy is turned on correctly',
  1666. gettingAreaInfo: 'Getting Steam area information...',
  1667. changeAreaNotice: 'Suspected of a locked zone game, try to change the zone to execute',
  1668. steamFinishNotice: 'Steam task completed, try to change the shopping cart area back to ',
  1669. gettingSubid: 'Getting subid',
  1670. addingFreeLicense: 'Adding free license',
  1671. missParams: 'Missing parameters',
  1672. gettingLicenses: 'Getting licenses...',
  1673. requestingPlayTestAccess: 'Requesting play test access',
  1674. 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.',
  1675. versionNotMatched: 'The script manager version is too low, requiring TamperMonkey >= 5.2.0 or TamperMonkey Beta >= 5.2.6196',
  1676. gettingUserLink: 'Getting steam user community link...',
  1677. retry: 'Retry',
  1678. owned: 'Owned',
  1679. redirect: 'Redirect',
  1680. noSubid: 'skip due to unrecognized',
  1681. initingASF: 'Initing ASF...',
  1682. servers: 'Server',
  1683. joiningDiscordServer: 'Joining Discord Server',
  1684. leavingDiscordServer: 'Leaving Discord Server',
  1685. gettingDiscordGuild: 'Getting Discord server Id',
  1686. getDiscordAuthFailed: 'Failed to get Discord token, please check whether the Discord account is logged in',
  1687. discordImportantNotice: 'Important Reminder! ! !',
  1688. 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! ! !',
  1689. continue: 'Continue',
  1690. skipDiscordTask: 'Skip',
  1691. continueAndDontRemindAgain: 'Continue without Reminders',
  1692. users: 'User',
  1693. loginIns: 'Please <a href="https://www.instagram.com/accounts/login/" target="_blank">log in to Instagram</a>',
  1694. insBanned: 'Your Instagram account has been banned',
  1695. verifyingInsAuth: 'Verifying Instagram token...',
  1696. gettingInsUserId: 'Getting Instagram user Id',
  1697. followingIns: 'Following Instagram user',
  1698. unfollowingIns: 'Unfollowing Instagram user',
  1699. reddits: 'Reddit/User',
  1700. loginReddit: 'Please <a href="https://www.reddit.com/login/" target="_blank">log in to Reddit</a>',
  1701. changingRedditVersion: 'Switching Reddit to a new version page...',
  1702. joiningReddit: 'Joining the Reddit',
  1703. leavingReddit: 'Leaving the Reddit',
  1704. followingRedditUser: 'Following Reddit User',
  1705. unfollowingRedditUser: 'Unfollowing Reddit User',
  1706. channels: 'Channel',
  1707. followingTwitchChannel: 'Following Twitch Channel',
  1708. unfollowingTwitchChannel: 'Unfollowing Twitch Channel',
  1709. gettingTwitchChannelId: 'Getting Twitch Channel Id',
  1710. checkingTwitchIntegrity: 'Checking Twitch integrity...',
  1711. twitterUser: 'Twitter User',
  1712. retweets: 'Retweet',
  1713. gettingTwitterUserId: 'Getting Twitter User Id',
  1714. followingTwitterUser: 'Following Twitter User',
  1715. unfollowingTwitterUser: 'Unfollowing Twitter User',
  1716. retweetting: 'Retweetting',
  1717. unretweetting: 'Unretweetting',
  1718. names: 'Group/Public/Wall',
  1719. loginVk: 'Please <a href="https://vk.com/login/" target="_blank">log in to Vk</a>',
  1720. gettingVkId: 'Getting Vk task Id',
  1721. joiningVkGroup: 'Joining Vk Group',
  1722. leavingVkGroup: 'Leaving Vk Group',
  1723. joiningVkPublic: 'Joining Vk Public',
  1724. leavingVkPublic: 'Leaving Vk Public',
  1725. sendingVkWall: 'Sending Vk Wall',
  1726. deletingVkWall: 'Deleting Vk Wall',
  1727. youtubeChannel: 'YouTube Channel',
  1728. likes: 'Like',
  1729. loginYtb: 'Please <a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">log in to YouTube</a>',
  1730. tryUpdateYtbAuth: 'Please try to <a href="https://www.youtube.com/#auth" target="_blank">update YouTube token</a>',
  1731. gettingYtbToken: 'Getting YouTube Token...',
  1732. followingYtbChannel: 'Subscribing to YouTube channel',
  1733. unfollowingYtbChannel: 'Unsubscribing to YouTube channel',
  1734. likingYtbVideo: 'Liking YouTube video',
  1735. unlikingYtbVideo: 'Unliking YouTube video',
  1736. giveKeyNoticeBefore: 'Each verification interval is 15s',
  1737. giveKeyNoticeAfter: 'If there is no key, please check at <a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>',
  1738. noPoints: 'Not enough points, skip the lottery',
  1739. getNeedPointsFailed: 'ailed to obtain the required points, skip the lottery',
  1740. joiningLottery: 'Joining the lottery',
  1741. doingGleamTask: 'Doing Gleam Task...',
  1742. gettingGleamLink: 'Getting Gleam task link...',
  1743. gleamTaskNotice: 'If this page has not been closed for a long time, please close it yourself after completing any task!',
  1744. verifiedGleamTasks: 'Attempted to verify all tasks. If the verification fails, please try to verify manually or complete it!',
  1745. campaign: 'ReCAPTCHA detected, please complete it and re-verify the tasks!',
  1746. 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!',
  1747. giveeClubVerifyNotice: 'Verifying task...',
  1748. giveeClubVerifyFinished: 'Wait for the verification to complete and join it by yourself',
  1749. doingKeyhubTask: 'Doing Keyhub Task...',
  1750. 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...',
  1751. tasksNotCompleted: 'Tasks Not Completed',
  1752. confirmingTask: 'Confirming task...'
  1753. };
  1754. const en_US = en_US_data;
  1755. const languages = {
  1756. zh: zh_CN,
  1757. en: en_US
  1758. };
  1759. const language = [ 'zh', 'en' ].includes(globalOptions.other.language) ? globalOptions.other.language : 'en';
  1760. const I18n = (key, ...argvs) => {
  1761. if (!languages[language]?.[key]) {
  1762. return key;
  1763. }
  1764. return languages[language][key].replace(/%([\d]+)/g, (match, index) => argvs[parseInt(index, 10)]);
  1765. };
  1766. const i18n = I18n;
  1767. function throwError(error, name) {
  1768. if (window.TRACE) {
  1769. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  1770. }
  1771. external_Swal_default().fire({
  1772. title: i18n('errorReport'),
  1773. icon: 'error',
  1774. showCancelButton: true,
  1775. confirmButtonText: i18n('toGithub'),
  1776. showDenyButton: true,
  1777. denyButtonText: i18n('toKeylol'),
  1778. cancelButtonText: i18n('close')
  1779. }).then(({
  1780. isDenied,
  1781. isConfirmed
  1782. }) => {
  1783. if (isConfirmed) {
  1784. 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,
  1785. 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'))}`, {
  1786. active: true
  1787. });
  1788. } else if (isDenied) {
  1789. const text = `错误链接: [url=${window.location.href}]${window.location.href}[/url]
  1790.  
  1791. 环境:
  1792.  
  1793. [code]${JSON.stringify((0, javascript_utils_umd_min.ua)(), null, 4)}[/code]
  1794.  
  1795. 脚本管理器: ${GM_info.scriptHandler} ${GM_info.version}
  1796. 脚本版本: ${GM_info.script.version}
  1797.  
  1798. 报错信息:
  1799. [code]${error.stack}[/code]
  1800.  
  1801. 执行日志:
  1802. [code]${$.makeArray($('#auto-task-info>li')).map(element => element.innerText).join('\n')}[/code]`;
  1803. GM_setClipboard(text);
  1804. external_Swal_default().fire({
  1805. title: i18n('copySuccess'),
  1806. icon: 'success',
  1807. confirmButtonText: i18n('ok')
  1808. }).then(() => {
  1809. GM_openInTab('https://keylol.com/forum.php?mod=post&action=reply&fid=319&tid=777450', {
  1810. active: true
  1811. });
  1812. });
  1813. }
  1814. });
  1815. console.log('%c%s', 'color:white;background:red', `Auto-Task[Error]: ${name}\n${error.stack}`);
  1816. }
  1817. class Social {
  1818. tasks;
  1819. getRealParams(name, links, doTask, link2param) {
  1820. try {
  1821. let realParams = [];
  1822. if (links.length > 0) {
  1823. realParams = [ ...realParams, ...links.map(link => link2param(link)).filter(link => link) ];
  1824. }
  1825. if (!doTask && this.tasks[name].length > 0) {
  1826. realParams = [ ...realParams, ...this.tasks[name] ];
  1827. }
  1828. return unique(realParams);
  1829. } catch (error) {
  1830. throwError(error, 'Social.getRealParams');
  1831. return [];
  1832. }
  1833. }
  1834. }
  1835. const social_Social = Social;
  1836. class Discord extends social_Social {
  1837. tasks;
  1838. whiteList;
  1839. #auth = GM_getValue('discordAuth') || {};
  1840. #cache = GM_getValue('discordCache') || {};
  1841. #initialized = false;
  1842. constructor() {
  1843. super();
  1844. const defaultTasksTemplate = {
  1845. servers: []
  1846. };
  1847. this.tasks = defaultTasksTemplate;
  1848. this.whiteList = {
  1849. ...defaultTasksTemplate,
  1850. ...GM_getValue('whiteList')?.discord || {}
  1851. };
  1852. }
  1853. async init(action) {
  1854. try {
  1855. if (!GM_getValue('dontRemindDiscordAgain')) {
  1856. const result = await external_Swal_default().fire({
  1857. title: i18n('discordImportantNotice'),
  1858. text: i18n('discordImportantNoticeText'),
  1859. showCancelButton: true,
  1860. showDenyButton: true,
  1861. confirmButtonText: i18n('continue'),
  1862. cancelButtonText: i18n('skipDiscordTask'),
  1863. denyButtonText: i18n('continueAndDontRemindAgain')
  1864. }).then(({
  1865. isConfirmed,
  1866. isDenied
  1867. }) => {
  1868. if (isConfirmed) {
  1869. return true;
  1870. }
  1871. if (isDenied) {
  1872. GM_setValue('dontRemindDiscordAgain', true);
  1873. return true;
  1874. }
  1875. return false;
  1876. });
  1877. if (!result) {
  1878. this.#initialized = false;
  1879. return 'skip';
  1880. }
  1881. }
  1882. if (GM_getValue('dontRemindDiscordAgain') || action === 'do' && !globalOptions.doTask.discord.servers || action === 'undo' && !globalOptions.undoTask.discord.servers) {
  1883. this.#initialized = false;
  1884. return 'skip';
  1885. }
  1886. if (this.#initialized) {
  1887. return true;
  1888. }
  1889. if (!this.#auth.auth) {
  1890. if (await this.#updateAuth()) {
  1891. this.#initialized = true;
  1892. return true;
  1893. }
  1894. return false;
  1895. }
  1896. const isVerified = await this.#verifyAuth();
  1897. if (isVerified) {
  1898. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  1899. this.#initialized = true;
  1900. return true;
  1901. }
  1902. GM_setValue('discordAuth', {
  1903. auth: null
  1904. });
  1905. if (await this.#updateAuth()) {
  1906. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  1907. this.#initialized = true;
  1908. return true;
  1909. }
  1910. scripts_echoLog({}).error(i18n('initFailed', 'Discord'));
  1911. return false;
  1912. } catch (error) {
  1913. throwError(error, 'Discord.init');
  1914. return false;
  1915. }
  1916. }
  1917. async #verifyAuth() {
  1918. try {
  1919. const logStatus = scripts_echoLog({
  1920. text: i18n('verifyingAuth', 'Discord')
  1921. });
  1922. const {
  1923. result,
  1924. statusText,
  1925. status,
  1926. data
  1927. } = await tools_httpRequest({
  1928. url: 'https://discord.com/api/v6/users/@me',
  1929. method: 'HEAD',
  1930. headers: {
  1931. authorization: this.#auth.auth
  1932. }
  1933. });
  1934. if (result === 'Success') {
  1935. if (data?.status === 200) {
  1936. logStatus.success();
  1937. return true;
  1938. }
  1939. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  1940. return false;
  1941. }
  1942. logStatus.error(`${result}:${statusText}(${status})`);
  1943. return false;
  1944. } catch (error) {
  1945. throwError(error, 'Discord.verifyAuth');
  1946. return false;
  1947. }
  1948. }
  1949. async #updateAuth() {
  1950. try {
  1951. const logStatus = scripts_echoLog({
  1952. text: i18n('updatingAuth', 'Discord')
  1953. });
  1954. return await new Promise(resolve => {
  1955. const newTab = GM_openInTab('https://discord.com/channels/@me', {
  1956. active: true,
  1957. insert: true,
  1958. setParent: true
  1959. });
  1960. newTab.name = 'ATv4_discordAuth';
  1961. newTab.onclose = async () => {
  1962. const auth = GM_getValue('discordAuth')?.auth;
  1963. if (auth) {
  1964. this.#auth = {
  1965. auth: auth
  1966. };
  1967. logStatus.success();
  1968. resolve(await this.#verifyAuth());
  1969. } else {
  1970. logStatus.error('Error: Update discord auth failed!');
  1971. resolve(false);
  1972. }
  1973. };
  1974. });
  1975. } catch (error) {
  1976. throwError(error, 'Discord.updateAuth');
  1977. return false;
  1978. }
  1979. }
  1980. async #joinServer(inviteId) {
  1981. try {
  1982. const logStatus = scripts_echoLog({
  1983. type: 'joiningDiscordServer',
  1984. text: inviteId
  1985. });
  1986. const {
  1987. result,
  1988. statusText,
  1989. status,
  1990. data
  1991. } = await tools_httpRequest({
  1992. url: `https://discord.com/api/v9/invites/${inviteId}`,
  1993. method: 'POST',
  1994. dataType: 'json',
  1995. headers: {
  1996. authorization: this.#auth.auth,
  1997. origin: 'https://discord.com',
  1998. referer: `https://discord.com/invite/${inviteId}`
  1999. }
  2000. });
  2001. if (result === 'Success' && data?.status === 200) {
  2002. logStatus.success();
  2003. const guild = String(data.response?.guild?.id);
  2004. if (guild) {
  2005. this.#setCache(inviteId, guild);
  2006. this.tasks.servers = unique([ ...this.tasks.servers, inviteId ]);
  2007. }
  2008. return true;
  2009. }
  2010. logStatus.error(`${result}:${statusText}(${status})`);
  2011. return false;
  2012. } catch (error) {
  2013. throwError(error, 'Discord.joinServer');
  2014. return false;
  2015. }
  2016. }
  2017. async #leaveServer(inviteId) {
  2018. try {
  2019. if (this.whiteList.servers.includes(inviteId)) {
  2020. scripts_echoLog({
  2021. type: 'whiteList',
  2022. text: 'Discord.leaveServer',
  2023. id: inviteId
  2024. });
  2025. return true;
  2026. }
  2027. const guild = await this.#getGuild(inviteId);
  2028. if (!guild) {
  2029. return false;
  2030. }
  2031. const logStatus = scripts_echoLog({
  2032. type: 'leavingDiscordServer',
  2033. text: guild
  2034. });
  2035. const {
  2036. result,
  2037. statusText,
  2038. status,
  2039. data
  2040. } = await tools_httpRequest({
  2041. url: `https://discord.com/api/v9/users/@me/guilds/${guild}`,
  2042. method: 'DELETE',
  2043. headers: {
  2044. authorization: this.#auth.auth
  2045. }
  2046. });
  2047. if (result === 'Success' && data?.status === 204) {
  2048. logStatus.success();
  2049. return true;
  2050. }
  2051. logStatus.error(`${result}:${statusText}(${status})`);
  2052. return false;
  2053. } catch (error) {
  2054. throwError(error, 'Discord.leaveServer');
  2055. return false;
  2056. }
  2057. }
  2058. async #getGuild(inviteId) {
  2059. try {
  2060. const logStatus = scripts_echoLog({
  2061. type: 'gettingDiscordGuild',
  2062. text: inviteId
  2063. });
  2064. const guild = this.#cache[inviteId];
  2065. if (guild) {
  2066. logStatus.success();
  2067. return guild;
  2068. }
  2069. const {
  2070. result,
  2071. statusText,
  2072. status,
  2073. data
  2074. } = await tools_httpRequest({
  2075. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2076. responseType: 'json',
  2077. method: 'GET'
  2078. });
  2079. if (result === 'Success' && data?.status === 200) {
  2080. const guild = data.response?.guild?.id;
  2081. if (guild) {
  2082. logStatus.success();
  2083. this.#setCache(inviteId, guild);
  2084. return guild;
  2085. }
  2086. logStatus.error(`${result}:${statusText}(${status})`);
  2087. return false;
  2088. }
  2089. logStatus.error(`${result}:${statusText}(${status})`);
  2090. return false;
  2091. } catch (error) {
  2092. throwError(error, 'Discord.getGuild');
  2093. return false;
  2094. }
  2095. }
  2096. async toggle({
  2097. doTask = true,
  2098. serverLinks = []
  2099. }) {
  2100. try {
  2101. if (!this.#initialized) {
  2102. scripts_echoLog({
  2103. text: i18n('needInit')
  2104. });
  2105. return false;
  2106. }
  2107. const prom = [];
  2108. if (doTask && !globalOptions.doTask.discord.servers || !doTask && !globalOptions.undoTask.discord.servers) {
  2109. scripts_echoLog({
  2110. type: 'globalOptionsSkip',
  2111. text: 'discord.servers'
  2112. });
  2113. } else {
  2114. const realServers = this.getRealParams('servers', serverLinks, doTask, link => link.match(/invite\/(.+)/)?.[1]);
  2115. if (realServers.length > 0) {
  2116. for (const server of realServers) {
  2117. if (doTask) {
  2118. prom.push(this.#joinServer(server));
  2119. } else {
  2120. prom.push(this.#leaveServer(server));
  2121. }
  2122. await delay(1e3);
  2123. }
  2124. }
  2125. }
  2126. return await Promise.all(prom).then(() => true);
  2127. } catch (error) {
  2128. throwError(error, 'Discord.toggleServers');
  2129. return false;
  2130. }
  2131. }
  2132. #setCache(inviteId, guild) {
  2133. try {
  2134. this.#cache[inviteId] = guild;
  2135. GM_setValue('discordCache', this.#cache);
  2136. } catch (error) {
  2137. throwError(error, 'Discord.setCache');
  2138. }
  2139. }
  2140. }
  2141. const social_Discord = Discord;
  2142. class Instagram extends social_Social {
  2143. tasks;
  2144. whiteList;
  2145. #cache = GM_getValue('instagramCache') || {};
  2146. #auth = {};
  2147. #initialized = false;
  2148. constructor() {
  2149. super();
  2150. const defaultTasksTemplate = {
  2151. users: []
  2152. };
  2153. this.tasks = defaultTasksTemplate;
  2154. this.whiteList = {
  2155. ...defaultTasksTemplate,
  2156. ...GM_getValue('whiteList')?.instagram || {}
  2157. };
  2158. }
  2159. async init() {
  2160. try {
  2161. if (this.#initialized) {
  2162. return true;
  2163. }
  2164. const isVerified = await this.#getUserInfo();
  2165. if (isVerified) {
  2166. scripts_echoLog({}).success(i18n('initSuccess', 'Instagram'));
  2167. this.#initialized = true;
  2168. return true;
  2169. }
  2170. scripts_echoLog({}).error(i18n('initFailed', 'Instagram'));
  2171. return false;
  2172. } catch (error) {
  2173. throwError(error, 'Instagram.init');
  2174. return false;
  2175. }
  2176. }
  2177. async #getUserInfo(name = 'instagram') {
  2178. try {
  2179. const logStatus = scripts_echoLog({
  2180. type: name === 'instagram' ? 'verifyingInsAuth' : 'gettingInsUserId',
  2181. text: name
  2182. });
  2183. const userId = this.#cache[name];
  2184. if (userId && name !== 'instagram') {
  2185. logStatus.success();
  2186. return userId;
  2187. }
  2188. const {
  2189. result,
  2190. statusText,
  2191. status,
  2192. data
  2193. } = await tools_httpRequest({
  2194. url: `https://www.instagram.com/${name}/`,
  2195. method: 'GET'
  2196. });
  2197. if (result === 'Success') {
  2198. if (data?.finalUrl.includes('accounts/login')) {
  2199. logStatus.error(`Error:${i18n('loginIns')}`, true);
  2200. return false;
  2201. } else if (data?.finalUrl.includes('www.instagram.com/challenge')) {
  2202. logStatus.error(`Error:${i18n('insBanned')}`);
  2203. return false;
  2204. }
  2205. if (data?.status === 200) {
  2206. const csrftoken = data.responseText.match(/"csrf_token":"(.+?)"/)?.[1];
  2207. const hash = data.responseText.match(/"rollout_hash":"(.+?)"/)?.[1];
  2208. if (name === 'instagram') {
  2209. if (csrftoken && hash) {
  2210. this.#auth = {
  2211. csrftoken: csrftoken,
  2212. hash: hash
  2213. };
  2214. return true;
  2215. }
  2216. return false;
  2217. }
  2218. const id = data.responseText.match(/"profilePage_([\d]+?)"/)?.[1];
  2219. if (id) {
  2220. this.#setCache(name, id);
  2221. logStatus.success();
  2222. return id;
  2223. }
  2224. logStatus.error('Error: Get ins data error!');
  2225. return false;
  2226. }
  2227. logStatus.error(`${result}:${statusText}(${status})`);
  2228. return false;
  2229. }
  2230. return false;
  2231. } catch (error) {
  2232. throwError(error, 'Instagram.getUserInfo');
  2233. return false;
  2234. }
  2235. }
  2236. async #followUser(name) {
  2237. try {
  2238. const id = await this.#getUserInfo(name);
  2239. if (!id) {
  2240. return false;
  2241. }
  2242. const logStatus = scripts_echoLog({
  2243. type: 'followingIns',
  2244. text: name
  2245. });
  2246. const {
  2247. result,
  2248. statusText,
  2249. status,
  2250. data
  2251. } = await tools_httpRequest({
  2252. url: `https://www.instagram.com/web/friendships/${id}/follow/`,
  2253. method: 'POST',
  2254. dataType: 'json',
  2255. headers: {
  2256. 'x-csrftoken': this.#auth.csrftoken,
  2257. origin: 'https://www.instagram.com',
  2258. referer: `https://www.instagram.com/${name}/`,
  2259. 'content-type': 'application/x-www-form-urlencoded',
  2260. 'sec-fetch-site': 'same-origin',
  2261. 'x-instagram-ajax': this.#auth.hash
  2262. }
  2263. });
  2264. if (result === 'Success') {
  2265. if (data?.status === 200 && data.response?.result === 'following') {
  2266. logStatus.success();
  2267. this.tasks.users = unique([ ...this.tasks.users, name ]);
  2268. return true;
  2269. }
  2270. logStatus.error(`Error:${data?.response?.feedback_message || `${data?.statusText}(${data?.status})`}`);
  2271. return false;
  2272. }
  2273. logStatus.error(`${result}:${statusText}(${status})`);
  2274. return false;
  2275. } catch (error) {
  2276. throwError(error, 'Instagram.followUser');
  2277. return false;
  2278. }
  2279. }
  2280. async #unfollowUser(name) {
  2281. try {
  2282. if (this.whiteList.users.includes(name)) {
  2283. scripts_echoLog({
  2284. type: 'whiteList',
  2285. text: 'Instagram.unfollowUser',
  2286. id: name
  2287. });
  2288. return true;
  2289. }
  2290. const id = await this.#getUserInfo(name);
  2291. if (!id) {
  2292. return false;
  2293. }
  2294. const logStatus = scripts_echoLog({
  2295. type: 'unfollowingIns',
  2296. text: name
  2297. });
  2298. const {
  2299. result,
  2300. statusText,
  2301. status,
  2302. data
  2303. } = await tools_httpRequest({
  2304. url: `https://www.instagram.com/web/friendships/${id}/unfollow/`,
  2305. method: 'POST',
  2306. dataType: 'json',
  2307. headers: {
  2308. 'x-csrftoken': this.#auth.csrftoken,
  2309. origin: 'https://www.instagram.com',
  2310. referer: `https://www.instagram.com/${name}/`,
  2311. 'content-type': 'application/x-www-form-urlencoded',
  2312. 'sec-fetch-site': 'same-origin',
  2313. 'x-instagram-ajax': this.#auth.hash
  2314. }
  2315. });
  2316. if (result === 'Success') {
  2317. if (data?.status === 200 && data.response?.status === 'ok') {
  2318. logStatus.success();
  2319. return true;
  2320. }
  2321. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2322. return false;
  2323. }
  2324. logStatus.error(`${result}:${statusText}(${status})`);
  2325. return false;
  2326. } catch (error) {
  2327. throwError(error, 'Instagram.unfollowUser');
  2328. return false;
  2329. }
  2330. }
  2331. async toggle({
  2332. doTask = true,
  2333. userLinks = []
  2334. }) {
  2335. try {
  2336. if (!this.#initialized) {
  2337. scripts_echoLog({
  2338. text: i18n('needInit')
  2339. });
  2340. return false;
  2341. }
  2342. const prom = [];
  2343. if (doTask && !globalOptions.doTask.instagram.users || !doTask && !globalOptions.undoTask.instagram.users) {
  2344. scripts_echoLog({
  2345. type: 'globalOptionsSkip',
  2346. text: 'instagram.users'
  2347. });
  2348. } else {
  2349. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1]);
  2350. if (realUsers.length > 0) {
  2351. for (const username of realUsers) {
  2352. if (doTask) {
  2353. prom.push(this.#followUser(username));
  2354. } else {
  2355. prom.push(this.#unfollowUser(username));
  2356. }
  2357. await delay(1e3);
  2358. }
  2359. }
  2360. }
  2361. return await Promise.all(prom).then(() => true);
  2362. } catch (error) {
  2363. throwError(error, 'Instagram.toggleUsers');
  2364. return false;
  2365. }
  2366. }
  2367. #setCache(name, id) {
  2368. try {
  2369. this.#cache[name] = id;
  2370. GM_setValue('instagramCache', this.#cache);
  2371. } catch (error) {
  2372. throwError(error, 'Instagram.setCache');
  2373. }
  2374. }
  2375. }
  2376. const social_Instagram = Instagram;
  2377. class Reddit extends social_Social {
  2378. tasks;
  2379. whiteList;
  2380. #auth;
  2381. #initialized = false;
  2382. constructor() {
  2383. super();
  2384. const defaultTasksTemplate = {
  2385. reddits: []
  2386. };
  2387. this.tasks = defaultTasksTemplate;
  2388. this.whiteList = {
  2389. ...defaultTasksTemplate,
  2390. ...GM_getValue('whiteList')?.reddit || {}
  2391. };
  2392. }
  2393. async init() {
  2394. try {
  2395. if (this.#initialized) {
  2396. return true;
  2397. }
  2398. const isVerified = await this.#updateAuth();
  2399. if (isVerified) {
  2400. scripts_echoLog({}).success(i18n('initSuccess', 'Reddit'));
  2401. this.#initialized = true;
  2402. return true;
  2403. }
  2404. scripts_echoLog({}).error(i18n('initFailed', 'Reddit'));
  2405. return false;
  2406. } catch (error) {
  2407. throwError(error, 'Reddit.init');
  2408. return false;
  2409. }
  2410. }
  2411. async #useBeta() {
  2412. try {
  2413. const logStatus = scripts_echoLog({
  2414. text: i18n('changingRedditVersion')
  2415. });
  2416. return await new Promise(resolve => {
  2417. const newTab = GM_openInTab('https://www.reddit.com/', {
  2418. active: true,
  2419. insert: true,
  2420. setParent: true
  2421. });
  2422. newTab.name = 'ATv4_redditAuth';
  2423. newTab.onclose = async () => {
  2424. logStatus.success();
  2425. resolve(await this.#updateAuth(true));
  2426. };
  2427. });
  2428. } catch (error) {
  2429. throwError(error, 'Reddit.useBeta');
  2430. return false;
  2431. }
  2432. }
  2433. async #updateAuth(beta = false) {
  2434. try {
  2435. const logStatus = scripts_echoLog({
  2436. text: i18n('updatingAuth', 'Reddit')
  2437. });
  2438. const {
  2439. result,
  2440. statusText,
  2441. status,
  2442. data
  2443. } = await tools_httpRequest({
  2444. url: 'https://www.reddit.com/',
  2445. method: 'GET',
  2446. nochche: true,
  2447. headers: {
  2448. 'Cache-Control': 'no-cache'
  2449. }
  2450. });
  2451. if (result === 'Success') {
  2452. if (data?.responseText.includes('www.reddit.com/login/')) {
  2453. logStatus.error(`Error:${i18n('loginReddit')}`, true);
  2454. return false;
  2455. }
  2456. if (data?.status === 200) {
  2457. if (data.responseText.includes('redesign-beta-optin-btn') && !beta) {
  2458. return await this.#useBeta();
  2459. }
  2460. const accessToken = data.responseText.match(/"accessToken":"(.*?)","expires":"(.*?)"/)?.[1];
  2461. if (accessToken) {
  2462. this.#auth = {
  2463. token: accessToken
  2464. };
  2465. logStatus.success();
  2466. return true;
  2467. }
  2468. logStatus.error('Error: Parameter "accessToken" not found!');
  2469. return false;
  2470. }
  2471. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2472. return false;
  2473. }
  2474. logStatus.error(`${result}:${statusText}(${status})`);
  2475. return false;
  2476. } catch (error) {
  2477. throwError(error, 'Reddit.updateAuth');
  2478. return false;
  2479. }
  2480. }
  2481. async #toggleTask({
  2482. name,
  2483. doTask = true
  2484. }) {
  2485. try {
  2486. if (!doTask && this.whiteList.reddits.includes(name)) {
  2487. scripts_echoLog({
  2488. type: 'whiteList',
  2489. text: 'Reddit.undoTask',
  2490. id: name
  2491. });
  2492. return true;
  2493. }
  2494. let type = doTask ? 'joiningReddit' : 'leavingReddit';
  2495. if (/^u_/.test(name)) {
  2496. type = doTask ? 'followingRedditUser' : 'unfollowingRedditUser';
  2497. }
  2498. const logStatus = scripts_echoLog({
  2499. type: type,
  2500. text: name
  2501. });
  2502. const {
  2503. result,
  2504. statusText,
  2505. status,
  2506. data
  2507. } = await tools_httpRequest({
  2508. url: 'https://oauth.reddit.com/api/subscribe?redditWebClient=desktop2x&app=desktop2x-client-production&raw_json=1&gilding_detail=1',
  2509. method: 'POST',
  2510. headers: {
  2511. authorization: `Bearer ${this.#auth.token}`,
  2512. 'content-type': 'application/x-www-form-urlencoded'
  2513. },
  2514. data: $.param({
  2515. action: doTask ? 'sub' : 'unsub',
  2516. sr_name: name,
  2517. api_type: 'json'
  2518. })
  2519. });
  2520. if (result === 'Success') {
  2521. if (data?.status === 200) {
  2522. logStatus.success();
  2523. if (doTask) {
  2524. this.tasks.reddits = unique([ ...this.tasks.reddits, name ]);
  2525. }
  2526. return true;
  2527. }
  2528. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2529. return false;
  2530. }
  2531. logStatus.error(`${result}:${statusText}(${status})`);
  2532. return false;
  2533. } catch (error) {
  2534. throwError(error, 'Reddit.toggleTask');
  2535. return false;
  2536. }
  2537. }
  2538. async toggle({
  2539. doTask = true,
  2540. redditLinks = []
  2541. }) {
  2542. try {
  2543. if (!this.#initialized) {
  2544. scripts_echoLog({
  2545. text: i18n('needInit')
  2546. });
  2547. return false;
  2548. }
  2549. const prom = [];
  2550. if (doTask && !globalOptions.doTask.reddit.reddits || !doTask && !globalOptions.undoTask.reddit.reddits) {
  2551. scripts_echoLog({
  2552. type: 'globalOptionsSkip',
  2553. text: 'reddit.reddits'
  2554. });
  2555. } else {
  2556. const realReddits = this.getRealParams('reddits', redditLinks, doTask, link => {
  2557. const name = link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1];
  2558. const userName = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1];
  2559. if (userName) {
  2560. return name || userName;
  2561. }
  2562. return name;
  2563. });
  2564. if (realReddits.length > 0) {
  2565. for (const name of realReddits) {
  2566. prom.push(this.#toggleTask({
  2567. name: name,
  2568. doTask: doTask
  2569. }));
  2570. await delay(1e3);
  2571. }
  2572. }
  2573. }
  2574. return await Promise.all(prom).then(() => true);
  2575. } catch (error) {
  2576. throwError(error, 'Reddit.toggle');
  2577. return false;
  2578. }
  2579. }
  2580. }
  2581. const social_Reddit = Reddit;
  2582. class Twitch extends social_Social {
  2583. tasks;
  2584. whiteList;
  2585. #auth = GM_getValue('twitchAuth') || {};
  2586. #cache = GM_getValue('twitchCache') || {};
  2587. #initialized = false;
  2588. #integrityToken;
  2589. constructor() {
  2590. super();
  2591. const defaultTasksTemplate = {
  2592. channels: []
  2593. };
  2594. this.tasks = defaultTasksTemplate;
  2595. this.whiteList = {
  2596. ...defaultTasksTemplate,
  2597. ...GM_getValue('whiteList')?.twitch || {}
  2598. };
  2599. }
  2600. async init() {
  2601. try {
  2602. if (this.#initialized) {
  2603. return true;
  2604. }
  2605. if (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId) {
  2606. if (await this.#updateAuth()) {
  2607. this.#initialized = true;
  2608. return true;
  2609. }
  2610. return false;
  2611. }
  2612. const isVerified = await this.#verifyAuth(true);
  2613. if (isVerified) {
  2614. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  2615. this.#initialized = true;
  2616. return true;
  2617. }
  2618. GM_setValue('twitchAuth', null);
  2619. if (await this.#updateAuth()) {
  2620. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  2621. this.#initialized = true;
  2622. return true;
  2623. }
  2624. scripts_echoLog({}).error(i18n('initFailed', 'Twitch'));
  2625. return false;
  2626. } catch (error) {
  2627. throwError(error, 'Twitch.init');
  2628. return false;
  2629. }
  2630. }
  2631. async #verifyAuth(isFirst) {
  2632. try {
  2633. const logStatus = scripts_echoLog({
  2634. text: i18n('verifyingAuth', 'Twitch')
  2635. });
  2636. const {
  2637. result,
  2638. statusText,
  2639. status,
  2640. data
  2641. } = await tools_httpRequest({
  2642. url: 'https://gql.twitch.tv/gql',
  2643. method: 'POST',
  2644. dataType: 'json',
  2645. headers: {
  2646. Authorization: `OAuth ${this.#auth.authToken}`,
  2647. 'Client-Id': this.#auth.clientId
  2648. },
  2649. data: '[{"operationName":"FrontPageNew_User","variables":{"limit":1},"extensions":{"persistedQuery":{"version":1,' + '"sha256Hash":"64bd07a2cbaca80699d62636d966cf6395a5d14a1f0a14282067dcb28b13eb11"}}}]'
  2650. });
  2651. if (result === 'Success') {
  2652. if (data?.status === 200 && data.response?.[0]?.data?.currentUser) {
  2653. await this.#integrity(isFirst);
  2654. logStatus.success();
  2655. return true;
  2656. }
  2657. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2658. return false;
  2659. }
  2660. logStatus.error(`${result}:${statusText}(${status})`);
  2661. return false;
  2662. } catch (error) {
  2663. throwError(error, 'Twitch.verifyAuth');
  2664. return false;
  2665. }
  2666. }
  2667. async #integrity(isFirst = true, ct = '') {
  2668. try {
  2669. const logStatus = scripts_echoLog({
  2670. text: i18n('checkingTwitchIntegrity')
  2671. });
  2672. if (isFirst && (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId)) {
  2673. return await this.#updateAuth(false);
  2674. }
  2675. const {
  2676. result,
  2677. statusText,
  2678. status,
  2679. data
  2680. } = await tools_httpRequest({
  2681. url: 'https://gql.twitch.tv/integrity',
  2682. method: 'POST',
  2683. dataType: 'json',
  2684. anonymous: true,
  2685. headers: {
  2686. Origin: 'https://www.twitch.tv',
  2687. Referer: 'https://www.twitch.tv/',
  2688. Authorization: `OAuth ${this.#auth.authToken}`,
  2689. 'Client-Id': this.#auth.clientId,
  2690. 'Client-Version': this.#auth.clientVersion,
  2691. 'X-Device-Id': this.#auth.deviceId,
  2692. 'Client-Session-Id': this.#auth.clientSessionId,
  2693. 'x-kpsdk-ct': ct
  2694. }
  2695. });
  2696. if (result === 'Success') {
  2697. if (!ct && data?.responseHeaders?.['x-kpsdk-ct']) {
  2698. return await this.#integrity(isFirst, data.responseHeaders['x-kpsdk-ct']);
  2699. }
  2700. if (data?.status === 200 && data.response?.token) {
  2701. this.#integrityToken = data.response.token;
  2702. logStatus.success();
  2703. return true;
  2704. }
  2705. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2706. return false;
  2707. }
  2708. logStatus.error(`${result}:${statusText}(${status})`);
  2709. return false;
  2710. } catch (error) {
  2711. throwError(error, 'Twitch.integrity');
  2712. return false;
  2713. }
  2714. }
  2715. async #updateAuth(isFirst = true) {
  2716. try {
  2717. const logStatus = scripts_echoLog({
  2718. text: i18n('updatingAuth', 'Twitch')
  2719. });
  2720. return await new Promise(resolve => {
  2721. const newTab = GM_openInTab('https://www.twitch.tv/', {
  2722. active: true,
  2723. insert: true,
  2724. setParent: true
  2725. });
  2726. newTab.name = 'ATv4_twitchAuth';
  2727. newTab.onclose = async () => {
  2728. const auth = GM_getValue('twitchAuth');
  2729. if (auth) {
  2730. this.#auth = auth;
  2731. logStatus.success();
  2732. resolve(await this.#verifyAuth(isFirst));
  2733. } else {
  2734. logStatus.error('Error: Update twitch auth failed!');
  2735. resolve(false);
  2736. }
  2737. };
  2738. });
  2739. } catch (error) {
  2740. throwError(error, 'Twitch.updateAuth');
  2741. return false;
  2742. }
  2743. }
  2744. async #toggleChannel({
  2745. name,
  2746. doTask = true
  2747. }) {
  2748. try {
  2749. if (!doTask && this.whiteList.channels.includes(name)) {
  2750. scripts_echoLog({
  2751. type: 'whiteList',
  2752. text: 'Twitch.unfollowChannel',
  2753. id: name
  2754. });
  2755. return true;
  2756. }
  2757. const channelId = await this.#getChannelId(name);
  2758. if (!channelId) {
  2759. return false;
  2760. }
  2761. const logStatus = scripts_echoLog({
  2762. type: `${doTask ? '' : 'un'}followingTwitchChannel`,
  2763. text: name
  2764. });
  2765. const followData = `[{"operationName":"FollowButton_FollowUser","variables":{"input":{"disableNotifications":false,"targetID":"${channelId}` + '"}},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"800e7346bdf7e5278a3c1d3f21b2b56e2639928f86815677a7126b093b2fdd08"}}}]';
  2766. const unfollowData = `[{"operationName":"FollowButton_UnfollowUser","variables":{"input":{"targetID":"${channelId}"}},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"f7dae976ebf41c755ae2d758546bfd176b4eeb856656098bb40e0a672ca0d880"}}}]';
  2767. const {
  2768. result,
  2769. statusText,
  2770. status,
  2771. data
  2772. } = await tools_httpRequest({
  2773. url: 'https://gql.twitch.tv/gql',
  2774. method: 'POST',
  2775. dataType: 'json',
  2776. anonymous: true,
  2777. headers: {
  2778. Origin: 'https://www.twitch.tv',
  2779. Referer: 'https://www.twitch.tv/',
  2780. Authorization: `OAuth ${this.#auth.authToken}`,
  2781. 'Client-Id': this.#auth.clientId,
  2782. 'Client-Version': this.#auth.clientVersion,
  2783. 'X-Device-Id': this.#auth.deviceId,
  2784. 'Client-Session-Id': this.#auth.clientSessionId,
  2785. 'Client-Integrity': this.#integrityToken
  2786. },
  2787. data: doTask ? followData : unfollowData
  2788. });
  2789. if (result === 'Success') {
  2790. if (data?.status === 200 && data.response?.[0] && !data.response[0].errors) {
  2791. logStatus.success();
  2792. if (doTask) {
  2793. this.tasks.channels = unique([ ...this.tasks.channels, name ]);
  2794. }
  2795. return true;
  2796. }
  2797. logStatus.error(`Error:${data?.response?.[0].errors?.[0]?.message || `${data?.statusText}(${data?.status})`}`);
  2798. return false;
  2799. }
  2800. logStatus.error(`${result}:${statusText}(${status})`);
  2801. return false;
  2802. } catch (error) {
  2803. throwError(error, 'Twitch.toggleChannel');
  2804. return false;
  2805. }
  2806. }
  2807. async #getChannelId(name) {
  2808. try {
  2809. const logStatus = scripts_echoLog({
  2810. type: 'gettingTwitchChannelId',
  2811. text: name
  2812. });
  2813. const channelId = this.#cache[name];
  2814. if (channelId) {
  2815. logStatus.success();
  2816. return channelId;
  2817. }
  2818. const {
  2819. result,
  2820. statusText,
  2821. status,
  2822. data
  2823. } = await tools_httpRequest({
  2824. url: 'https://gql.twitch.tv/gql',
  2825. method: 'POST',
  2826. headers: {
  2827. Authorization: `OAuth ${this.#auth.authToken}`,
  2828. 'Client-Id': this.#auth.clientId
  2829. },
  2830. responseType: 'json',
  2831. data: `[{"operationName":"ActiveWatchParty","variables":{"channelLogin":"${name}"},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"4a8156c97b19e3a36e081cf6d6ddb5dbf9f9b02ae60e4d2ff26ed70aebc80a30"}}}]'
  2832. });
  2833. if (result === 'Success') {
  2834. if (data?.status === 200) {
  2835. const channelId = data.response?.[0]?.data?.user?.id;
  2836. if (channelId) {
  2837. this.#setCache(name, String(channelId));
  2838. logStatus.success();
  2839. return channelId;
  2840. }
  2841. logStatus.error(`Error:${data.statusText}(${data.status})`);
  2842. return false;
  2843. }
  2844. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2845. return false;
  2846. }
  2847. logStatus.error(`${result}:${statusText}(${status})`);
  2848. return false;
  2849. } catch (error) {
  2850. throwError(error, 'Twitch.getChannelId');
  2851. return false;
  2852. }
  2853. }
  2854. async toggle({
  2855. doTask = true,
  2856. channelLinks = []
  2857. }) {
  2858. try {
  2859. if (!this.#initialized) {
  2860. scripts_echoLog({
  2861. text: i18n('needInit')
  2862. });
  2863. return false;
  2864. }
  2865. const prom = [];
  2866. if (doTask && !globalOptions.doTask.twitch.channels || !doTask && !globalOptions.undoTask.twitch.channels) {
  2867. scripts_echoLog({
  2868. type: 'globalOptionsSkip',
  2869. text: 'twitch.channels'
  2870. });
  2871. } else {
  2872. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2]);
  2873. if (realChannels.length > 0) {
  2874. for (const channel of realChannels) {
  2875. prom.push(this.#toggleChannel({
  2876. name: channel,
  2877. doTask: doTask
  2878. }));
  2879. await delay(1e3);
  2880. }
  2881. }
  2882. }
  2883. return Promise.all(prom).then(() => true);
  2884. } catch (error) {
  2885. throwError(error, 'Twitch.toggle');
  2886. return false;
  2887. }
  2888. }
  2889. #setCache(name, id) {
  2890. try {
  2891. this.#cache[name] = id;
  2892. GM_setValue('twitchCache', this.#cache);
  2893. } catch (error) {
  2894. throwError(error, 'Twitch.setCache');
  2895. }
  2896. }
  2897. }
  2898. const social_Twitch = Twitch;
  2899. class Twitter extends social_Social {
  2900. tasks;
  2901. whiteList;
  2902. #verifyId = globalOptions.other.twitterVerifyId;
  2903. #auth = GM_getValue('twitterAuth') || {};
  2904. #cache = GM_getValue('twitterCache') || {};
  2905. #initialized = false;
  2906. constructor() {
  2907. super();
  2908. const defaultTasksTemplate = {
  2909. users: [],
  2910. retweets: [],
  2911. likes: []
  2912. };
  2913. this.tasks = defaultTasksTemplate;
  2914. this.whiteList = {
  2915. ...defaultTasksTemplate,
  2916. ...GM_getValue('whiteList')?.twitter || {}
  2917. };
  2918. }
  2919. async init() {
  2920. try {
  2921. if (this.#initialized) {
  2922. return true;
  2923. }
  2924. if (!this.#auth.ct0) {
  2925. if (await this.#updateAuth()) {
  2926. this.#initialized = true;
  2927. return true;
  2928. }
  2929. return false;
  2930. }
  2931. const isVerified = await this.#verifyAuth();
  2932. if (isVerified) {
  2933. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  2934. this.#initialized = true;
  2935. return true;
  2936. }
  2937. GM_setValue('twitterAuth', null);
  2938. if (await this.#updateAuth()) {
  2939. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  2940. this.#initialized = true;
  2941. return true;
  2942. }
  2943. scripts_echoLog({}).error(i18n('initFailed', 'Twitter'));
  2944. return false;
  2945. } catch (error) {
  2946. throwError(error, 'Twitter.init');
  2947. return false;
  2948. }
  2949. }
  2950. async #verifyAuth() {
  2951. try {
  2952. return await this.#toggleUser({
  2953. name: 'verify',
  2954. doTask: true,
  2955. verify: true
  2956. });
  2957. } catch (error) {
  2958. throwError(error, 'Twitter.verifyAuth');
  2959. return false;
  2960. }
  2961. }
  2962. async #updateAuth() {
  2963. try {
  2964. const logStatus = scripts_echoLog({
  2965. text: i18n('updatingAuth', 'Twitter')
  2966. });
  2967. return await new Promise(resolve => {
  2968. GM_cookie.list({
  2969. url: 'https://x.com/settings/account'
  2970. }, async (cookies, error) => {
  2971. if (!error) {
  2972. const [ ct0, isLogin ] = cookies.map(cookie => [ 'ct0', 'twid' ].includes(cookie.name) ? cookie.value : null).filter(cookie => cookie);
  2973. if (isLogin && ct0) {
  2974. GM_setValue('twitterAuth', {
  2975. ct0: ct0
  2976. });
  2977. this.#auth = {
  2978. ct0: ct0
  2979. };
  2980. logStatus.success();
  2981. resolve(await this.#verifyAuth());
  2982. } else {
  2983. logStatus.error(i18n('needLogin'));
  2984. resolve(false);
  2985. }
  2986. } else {
  2987. logStatus.error('Error: Update twitter auth failed!');
  2988. resolve(false);
  2989. }
  2990. });
  2991. });
  2992. } catch (error) {
  2993. throwError(error, 'Twitter.updateToken');
  2994. return false;
  2995. }
  2996. }
  2997. async #toggleUser({
  2998. name,
  2999. doTask = true,
  3000. verify = false,
  3001. retry = false
  3002. }) {
  3003. try {
  3004. if (!doTask && !verify && this.whiteList.users.includes(name)) {
  3005. scripts_echoLog({
  3006. type: 'whiteList',
  3007. text: 'Twitter.unfollowUser',
  3008. id: name
  3009. });
  3010. return true;
  3011. }
  3012. const userId = verify ? this.#verifyId : await this.userName2id(name);
  3013. if (!userId) {
  3014. return false;
  3015. }
  3016. const logStatus = verify ? scripts_echoLog({
  3017. text: i18n('verifyingAuth', 'Twitter')
  3018. }) : scripts_echoLog({
  3019. type: `${doTask ? '' : 'un'}followingTwitterUser`,
  3020. text: name
  3021. });
  3022. const {
  3023. result,
  3024. statusText,
  3025. status,
  3026. data
  3027. } = await tools_httpRequest({
  3028. url: `https://x.com/i/api/1.1/friendships/${doTask ? 'create' : 'destroy'}.json`,
  3029. method: 'POST',
  3030. headers: {
  3031. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3032. 'Content-Type': 'application/x-www-form-urlencoded',
  3033. 'x-csrf-token': this.#auth.ct0,
  3034. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3035. 'X-Twitter-Active-User': 'yes'
  3036. },
  3037. responseType: 'json',
  3038. data: $.param({
  3039. include_profile_interstitial_type: 1,
  3040. include_blocking: 1,
  3041. include_blocked_by: 1,
  3042. include_followed_by: 1,
  3043. include_want_retweets: 1,
  3044. include_mute_edge: 1,
  3045. include_can_dm: 1,
  3046. include_can_media_tag: 1,
  3047. skip_status: 1,
  3048. id: userId
  3049. })
  3050. });
  3051. if (result === 'Success') {
  3052. if (data?.status === 200) {
  3053. logStatus.success();
  3054. if (doTask && !verify) {
  3055. this.tasks.users = unique([ ...this.tasks.users, name ]);
  3056. }
  3057. return true;
  3058. }
  3059. if (verify && data?.status === 403) {
  3060. if (data.response?.errors?.[0]?.code === 158) {
  3061. logStatus.success();
  3062. return true;
  3063. }
  3064. if (data.response?.errors?.[0]?.code === 353 && !retry && data.responseHeaders?.['set-cookie']) {
  3065. this.#auth.ct0 = data.responseHeaders['set-cookie']?.find(cookie => cookie.includes('ct0='))?.split(';')?.at(0)?.split('=')?.at(-1) || this.#auth.ct0;
  3066. logStatus.warning(i18n('retry'));
  3067. return this.#toggleUser({
  3068. name: name,
  3069. doTask: doTask,
  3070. verify: verify,
  3071. retry: true
  3072. });
  3073. }
  3074. }
  3075. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3076. return false;
  3077. }
  3078. logStatus.error(`${result}:${statusText}(${status})`);
  3079. return false;
  3080. } catch (error) {
  3081. throwError(error, 'Twitter.toggleUser');
  3082. return false;
  3083. }
  3084. }
  3085. async userName2id(name) {
  3086. try {
  3087. const logStatus = scripts_echoLog({
  3088. type: 'gettingTwitterUserId',
  3089. text: name
  3090. });
  3091. const userId = this.#cache[name];
  3092. if (userId) {
  3093. logStatus.success();
  3094. return userId;
  3095. }
  3096. const {
  3097. result,
  3098. statusText,
  3099. status,
  3100. data
  3101. } = await tools_httpRequest({
  3102. 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`,
  3103. method: 'GET',
  3104. headers: {
  3105. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3106. 'content-type': 'application/json',
  3107. referer: `https://x.com/${name}`,
  3108. 'x-csrf-token': this.#auth.ct0,
  3109. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3110. 'X-Twitter-Active-User': 'yes'
  3111. },
  3112. responseType: 'json'
  3113. });
  3114. if (result === 'Success') {
  3115. if (data?.status === 200) {
  3116. let response = data.response || (typeof data.responseText === 'object' ? data.responseText : null);
  3117. if (!response) {
  3118. try {
  3119. response = JSON.parse(data.responseText);
  3120. } catch (error) {
  3121. response = null;
  3122. }
  3123. }
  3124. const userId = String(response?.data?.user?.result?.rest_id);
  3125. if (userId) {
  3126. this.#setCache(name, userId);
  3127. logStatus.success();
  3128. return userId;
  3129. }
  3130. logStatus.error(`Error:${data.statusText}(${data.status})`);
  3131. return false;
  3132. }
  3133. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3134. return false;
  3135. }
  3136. logStatus.error(`${result}:${statusText}(${status})`);
  3137. return false;
  3138. } catch (error) {
  3139. throwError(error, 'Twitter.getUserId');
  3140. return false;
  3141. }
  3142. }
  3143. async #toggleRetweet({
  3144. retweetId,
  3145. doTask = true
  3146. }) {
  3147. try {
  3148. if (!doTask && this.whiteList.retweets.includes(retweetId)) {
  3149. scripts_echoLog({
  3150. type: 'whiteList',
  3151. text: 'Twitter.unretweet',
  3152. id: retweetId
  3153. });
  3154. return true;
  3155. }
  3156. const logStatus = scripts_echoLog({
  3157. type: `${doTask ? '' : 'un'}retweetting`,
  3158. text: retweetId
  3159. });
  3160. const {
  3161. result,
  3162. statusText,
  3163. status,
  3164. data
  3165. } = await tools_httpRequest({
  3166. url: `https://x.com/i/api/graphql/${doTask ? 'ojPdsZsimiJrUGLR1sjUtA/CreateRetweet' : 'iQtK4dl5hBmXewYZuEOKVw/DeleteRetweet'}`,
  3167. method: 'POST',
  3168. headers: {
  3169. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3170. 'Content-Type': 'application/json',
  3171. 'x-csrf-token': this.#auth.ct0,
  3172. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3173. 'X-Twitter-Active-User': 'yes'
  3174. },
  3175. data: `{"variables":{"tweet_id":"${retweetId}","dark_request":false},"queryId":"${doTask ? 'ojPdsZsimiJrUGLR1sjUtA' : 'iQtK4dl5hBmXewYZuEOKVw'}"}`,
  3176. responseType: 'json'
  3177. });
  3178. if (result === 'Success') {
  3179. if (data?.status === 200 || data?.status === 403 && data.response?.errors?.[0]?.code === 327) {
  3180. logStatus.success();
  3181. if (doTask) {
  3182. this.tasks.retweets = unique([ ...this.tasks.retweets, retweetId ]);
  3183. }
  3184. return true;
  3185. }
  3186. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3187. return false;
  3188. }
  3189. logStatus.error(`${result}:${statusText}(${status})`);
  3190. return false;
  3191. } catch (error) {
  3192. throwError(error, 'Twitter.toggleRetweet');
  3193. return false;
  3194. }
  3195. }
  3196. async toggle({
  3197. doTask = true,
  3198. userLinks = [],
  3199. retweetLinks = []
  3200. }) {
  3201. try {
  3202. if (!this.#initialized) {
  3203. scripts_echoLog({
  3204. text: i18n('needInit')
  3205. });
  3206. return false;
  3207. }
  3208. const prom = [];
  3209. if (doTask && !globalOptions.doTask.twitter.users || !doTask && !globalOptions.undoTask.twitter.users) {
  3210. scripts_echoLog({
  3211. type: 'globalOptionsSkip',
  3212. text: 'twitter.users'
  3213. });
  3214. } else {
  3215. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/x\.com\/(.+)/)?.[1] || link.match(/https:\/\/twitter\.com\/(.+)/)?.[1]);
  3216. if (realUsers.length > 0) {
  3217. for (const user of realUsers) {
  3218. prom.push(this.#toggleUser({
  3219. name: user,
  3220. doTask: doTask
  3221. }));
  3222. await delay(1e3);
  3223. }
  3224. }
  3225. }
  3226. if (doTask && !globalOptions.doTask.twitter.retweets || !doTask && !globalOptions.undoTask.twitter.retweets) {
  3227. scripts_echoLog({
  3228. type: 'globalOptionsSkip',
  3229. text: 'twitter.retweets'
  3230. });
  3231. } else {
  3232. const realRetweets = this.getRealParams('retweets', retweetLinks, doTask, link => link.match(/https:\/\/x\.com\/.*?\/status\/([\d]+)/)?.[1] || link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1]);
  3233. if (realRetweets.length > 0) {
  3234. for (const retweet of realRetweets) {
  3235. prom.push(this.#toggleRetweet({
  3236. retweetId: retweet,
  3237. doTask: doTask
  3238. }));
  3239. await delay(1e3);
  3240. }
  3241. }
  3242. }
  3243. return Promise.all(prom).then(() => true);
  3244. } catch (error) {
  3245. throwError(error, 'Twitter.toggle');
  3246. return false;
  3247. }
  3248. }
  3249. #setCache(name, id) {
  3250. try {
  3251. this.#cache[name] = id;
  3252. GM_setValue('twitterCache', this.#cache);
  3253. } catch (error) {
  3254. throwError(error, 'Twitter.setCache');
  3255. }
  3256. }
  3257. }
  3258. const social_Twitter = Twitter;
  3259. class Vk extends social_Social {
  3260. tasks;
  3261. whiteList;
  3262. #username = '';
  3263. #cache = GM_getValue('vkCache') || {};
  3264. #initialized = false;
  3265. constructor() {
  3266. super();
  3267. const defaultTasksTemplate = {
  3268. names: []
  3269. };
  3270. this.tasks = defaultTasksTemplate;
  3271. this.whiteList = {
  3272. ...defaultTasksTemplate,
  3273. ...GM_getValue('whiteList')?.vk || {}
  3274. };
  3275. }
  3276. async init() {
  3277. try {
  3278. if (this.#initialized) {
  3279. return true;
  3280. }
  3281. const isVerified = await this.#verifyAuth();
  3282. if (isVerified) {
  3283. scripts_echoLog({}).success(i18n('initSuccess', 'Vk'));
  3284. this.#initialized = true;
  3285. return true;
  3286. }
  3287. scripts_echoLog({}).error(i18n('initFailed', 'Vk'));
  3288. return false;
  3289. } catch (error) {
  3290. throwError(error, 'Vk.init');
  3291. return false;
  3292. }
  3293. }
  3294. async #verifyAuth() {
  3295. try {
  3296. const logStatus = scripts_echoLog({
  3297. text: i18n('verifyAuth', 'Vk')
  3298. });
  3299. const {
  3300. result,
  3301. statusText,
  3302. status,
  3303. data
  3304. } = await tools_httpRequest({
  3305. url: 'https://vk.com/im',
  3306. method: 'GET'
  3307. });
  3308. if (result === 'Success') {
  3309. if (data?.finalUrl.includes('vk.com/login')) {
  3310. logStatus.error(`Error:${i18n('loginVk')}`, true);
  3311. return false;
  3312. }
  3313. if (data?.status === 200) {
  3314. this.#username = data.responseText.match(/TopNavBtn__profileLink" href="\/(.*?)"/)?.[1] || '';
  3315. logStatus.success();
  3316. return true;
  3317. }
  3318. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3319. return false;
  3320. }
  3321. logStatus.error(`${result}:${statusText}(${status})`);
  3322. return false;
  3323. } catch (error) {
  3324. throwError(error, 'Vk.verifyAuth');
  3325. return false;
  3326. }
  3327. }
  3328. async #toggleGroup(name, dataParam, doTask = true) {
  3329. try {
  3330. const logStatus = scripts_echoLog({
  3331. type: doTask ? 'joiningVkGroup' : 'leavingVkGroup',
  3332. text: name
  3333. });
  3334. if (dataParam.groupAct === 'enter' && !doTask || dataParam.groupAct === 'leave' && doTask) {
  3335. logStatus.success();
  3336. return true;
  3337. }
  3338. const reqData = {
  3339. act: doTask ? 'enter' : 'leave',
  3340. al: 1,
  3341. gid: dataParam.groupId,
  3342. hash: dataParam.groupHash
  3343. };
  3344. if (doTask) {
  3345. reqData.context = '_';
  3346. }
  3347. const {
  3348. result,
  3349. statusText,
  3350. status,
  3351. data
  3352. } = await tools_httpRequest({
  3353. url: 'https://vk.com/al_groups.php',
  3354. method: 'POST',
  3355. headers: {
  3356. origin: 'https://vk.com',
  3357. referer: `https://vk.com/${name}`,
  3358. 'content-type': 'application/x-www-form-urlencoded'
  3359. },
  3360. data: $.param(reqData)
  3361. });
  3362. if (result === 'Success') {
  3363. if (data?.status === 200) {
  3364. logStatus.success();
  3365. if (doTask) {
  3366. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3367. }
  3368. return true;
  3369. }
  3370. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3371. return false;
  3372. }
  3373. logStatus.error(`${result}:${statusText}(${status})`);
  3374. return false;
  3375. } catch (error) {
  3376. throwError(error, 'Vk.toggleGroup');
  3377. return false;
  3378. }
  3379. }
  3380. async #togglePublic(name, dataParam, doTask = true) {
  3381. try {
  3382. const logStatus = scripts_echoLog({
  3383. type: doTask ? 'joiningVkPublic' : 'leavingVkPublic',
  3384. text: name
  3385. });
  3386. if (dataParam.publicJoined && doTask || !dataParam.publicJoined && !doTask) {
  3387. logStatus.success();
  3388. return true;
  3389. }
  3390. const {
  3391. result,
  3392. statusText,
  3393. status,
  3394. data
  3395. } = await tools_httpRequest({
  3396. url: 'https://vk.com/al_public.php',
  3397. method: 'POST',
  3398. headers: {
  3399. origin: 'https://vk.com',
  3400. referer: `https://vk.com/${name}`,
  3401. 'content-type': 'application/x-www-form-urlencoded'
  3402. },
  3403. data: $.param({
  3404. act: doTask ? 'a_enter' : 'a_leave',
  3405. al: 1,
  3406. pid: dataParam.publicPid,
  3407. hash: dataParam.publicHash
  3408. })
  3409. });
  3410. if (result === 'Success') {
  3411. if (data?.status === 200) {
  3412. logStatus.success();
  3413. if (doTask) {
  3414. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3415. }
  3416. return true;
  3417. }
  3418. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3419. return false;
  3420. }
  3421. logStatus.error(`${result}:${statusText}(${status})`);
  3422. return false;
  3423. } catch (error) {
  3424. throwError(error, 'Vk.togglePublic');
  3425. return false;
  3426. }
  3427. }
  3428. async #sendWall(name) {
  3429. try {
  3430. const logStatus = scripts_echoLog({
  3431. type: 'sendingVkWall',
  3432. text: name
  3433. });
  3434. const {
  3435. result,
  3436. statusText,
  3437. status,
  3438. data
  3439. } = await tools_httpRequest({
  3440. url: 'https://vk.com/like.php',
  3441. method: 'POST',
  3442. headers: {
  3443. origin: 'https://vk.com',
  3444. referer: `https://vk.com/${name}`,
  3445. 'content-type': 'application/x-www-form-urlencoded'
  3446. },
  3447. data: $.param({
  3448. act: 'publish_box',
  3449. al: 1,
  3450. object: name
  3451. })
  3452. });
  3453. if (result === 'Success') {
  3454. if (data?.status === 200) {
  3455. const hash = data.responseText.match(/shHash:[\s]*'(.*?)'/)?.[1];
  3456. if (hash) {
  3457. const {
  3458. result: resultR,
  3459. statusText: statusTextR,
  3460. status: statusR,
  3461. data: dataR
  3462. } = await tools_httpRequest({
  3463. url: 'https://vk.com/like.php',
  3464. method: 'POST',
  3465. headers: {
  3466. origin: 'https://vk.com',
  3467. referer: `https://vk.com/${name}`,
  3468. 'content-type': 'application/x-www-form-urlencoded'
  3469. },
  3470. data: $.param({
  3471. Message: '',
  3472. act: 'a_do_publish',
  3473. al: 1,
  3474. close_comments: 0,
  3475. friends_only: 0,
  3476. from: 'box',
  3477. hash: hash,
  3478. list: '',
  3479. mark_as_ads: 0,
  3480. mute_notifications: 0,
  3481. object: name,
  3482. ret_data: 1,
  3483. to: 0
  3484. })
  3485. });
  3486. if (resultR === 'Success') {
  3487. if (dataR?.status === 200) {
  3488. const jsonData = JSON.parse(dataR.responseText?.replace('\x3c!--', '') || '{}');
  3489. if (jsonData?.payload?.[1]?.[1]?.share_my === true) {
  3490. logStatus.success();
  3491. const postId = String(jsonData?.payload?.[1]?.[1]?.post_id);
  3492. const ownerId = String(jsonData?.payload?.[1]?.[1]?.owner_id);
  3493. if (postId && ownerId) {
  3494. this.#setCache(name, `${ownerId}_${postId}`);
  3495. }
  3496. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3497. return true;
  3498. }
  3499. }
  3500. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  3501. return false;
  3502. }
  3503. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  3504. return false;
  3505. }
  3506. logStatus.error('Error: Get "hash" failed');
  3507. return false;
  3508. }
  3509. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3510. return false;
  3511. }
  3512. logStatus.error(`${result}:${statusText}(${status})`);
  3513. return false;
  3514. } catch (error) {
  3515. throwError(error, 'Vk.sendWall');
  3516. return false;
  3517. }
  3518. }
  3519. async #deleteWall(name, dataParams) {
  3520. try {
  3521. const logStatus = scripts_echoLog({
  3522. type: 'deletingVkWall',
  3523. text: name
  3524. });
  3525. const {
  3526. result,
  3527. statusText,
  3528. status,
  3529. data
  3530. } = await tools_httpRequest({
  3531. url: 'https://vk.com/al_wall.php?act=delete',
  3532. method: 'POST',
  3533. headers: {
  3534. origin: 'https://vk.com',
  3535. referer: `https://vk.com/${this.#username}?w=wall${this.#cache[name]}%2Fall`,
  3536. 'content-type': 'application/x-www-form-urlencoded'
  3537. },
  3538. data: $.param({
  3539. act: 'delete',
  3540. al: 1,
  3541. confirm: 0,
  3542. from: 'wkview',
  3543. hash: dataParams.wallHash,
  3544. post: this.#cache[name]
  3545. })
  3546. });
  3547. if (result === 'Success') {
  3548. if (data?.status === 200) {
  3549. const jsonData = JSON.parse(data.responseText?.replace('\x3c!--', '') || '{}');
  3550. if (jsonData?.payload?.[1]?.[1]) {
  3551. logStatus.success();
  3552. return true;
  3553. }
  3554. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3555. return false;
  3556. }
  3557. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3558. return false;
  3559. }
  3560. logStatus.error(`${result}:${statusText}(${status})`);
  3561. return false;
  3562. } catch (error) {
  3563. throwError(error, 'Vk.deleteWall');
  3564. return false;
  3565. }
  3566. }
  3567. async #getId(name, doTask) {
  3568. try {
  3569. let url = `https://vk.com/${name}`;
  3570. if (/^wall-/.test(name)) {
  3571. if (doTask) {
  3572. return {
  3573. type: 'sendWall'
  3574. };
  3575. }
  3576. if (!this.#cache[name]) {
  3577. return {
  3578. type: 'unSupport'
  3579. };
  3580. }
  3581. url = `https://vk.com/${this.#username}?w=wall${this.#cache[name]}`;
  3582. }
  3583. const logStatus = scripts_echoLog({
  3584. type: 'gettingVkId',
  3585. text: name
  3586. });
  3587. const {
  3588. result,
  3589. statusText,
  3590. status,
  3591. data
  3592. } = await tools_httpRequest({
  3593. url: url,
  3594. method: 'GET'
  3595. });
  3596. if (result === 'Success') {
  3597. if (data?.status === 200) {
  3598. const [ , groupAct, groupId, , groupHash ] = data.responseText.match(/Groups.(enter|leave)\(.*?,.*?([\d]+?), (&#39;|')(.*?)(&#39;|')/) || [];
  3599. const publicHash = data.responseText.match(/"enterHash":"(.*?)"/)?.[1];
  3600. const publicPid = data.responseText.match(/"public_id":([\d]+?),/)?.[1];
  3601. const publicJoined = !data.responseText.includes('Public.subscribe');
  3602. if (groupAct && groupId && groupHash) {
  3603. logStatus.success();
  3604. return {
  3605. groupAct: groupAct,
  3606. groupId: groupId,
  3607. groupHash: groupHash,
  3608. type: 'group'
  3609. };
  3610. } else if (publicHash && publicPid) {
  3611. logStatus.success();
  3612. return {
  3613. publicHash: publicHash,
  3614. publicPid: publicPid,
  3615. publicJoined: publicJoined,
  3616. type: 'public'
  3617. };
  3618. } else if (data.responseText.includes('wall.deletePost') && !doTask) {
  3619. const wallHash = data.responseText.match(/wall\.deletePost\(this, '.*?', '(.*?)'\)/)?.[1];
  3620. if (wallHash) {
  3621. logStatus.success();
  3622. return {
  3623. type: 'deleteWall',
  3624. wallHash: wallHash
  3625. };
  3626. }
  3627. } else if (name.includes('wall') && doTask) {
  3628. logStatus.success();
  3629. return {
  3630. type: 'sendWall'
  3631. };
  3632. }
  3633. logStatus.error('Error: Parameters not found!');
  3634. return false;
  3635. }
  3636. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3637. return false;
  3638. }
  3639. logStatus.error(`${result}:${statusText}(${status})`);
  3640. return false;
  3641. } catch (error) {
  3642. throwError(error, 'Vk.getId');
  3643. return false;
  3644. }
  3645. }
  3646. async #toggleVk({
  3647. name,
  3648. doTask = true
  3649. }) {
  3650. try {
  3651. if (!doTask && this.whiteList.names.includes(name)) {
  3652. scripts_echoLog({
  3653. type: 'whiteList',
  3654. text: 'Vk.undoTask',
  3655. id: name
  3656. });
  3657. return true;
  3658. }
  3659. const formatName = name.replace(/\/$/, '');
  3660. const data = await this.#getId(formatName, doTask);
  3661. if (!data) {
  3662. return false;
  3663. }
  3664. switch (data.type) {
  3665. case 'group':
  3666. return await this.#toggleGroup(formatName, data, doTask);
  3667.  
  3668. case 'public':
  3669. return await this.#togglePublic(formatName, data, doTask);
  3670.  
  3671. case 'sendWall':
  3672. return doTask ? await this.#sendWall(formatName) : true;
  3673.  
  3674. case 'deleteWall':
  3675. return doTask ? true : await this.#deleteWall(formatName, data);
  3676.  
  3677. default:
  3678. return false;
  3679. }
  3680. } catch (error) {
  3681. throwError(error, 'Vk.toggleVk');
  3682. return false;
  3683. }
  3684. }
  3685. async toggle({
  3686. doTask = true,
  3687. nameLinks = []
  3688. }) {
  3689. try {
  3690. if (!this.#initialized) {
  3691. scripts_echoLog({
  3692. text: i18n('needInit')
  3693. });
  3694. return false;
  3695. }
  3696. const prom = [];
  3697. if (doTask && !globalOptions.doTask.vk.names || !doTask && !globalOptions.undoTask.vk.names) {
  3698. scripts_echoLog({
  3699. type: 'globalOptionsSkip',
  3700. text: 'vk.names'
  3701. });
  3702. } else {
  3703. const realNames = this.getRealParams('names', nameLinks, doTask, link => link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1]);
  3704. if (realNames.length > 0) {
  3705. for (const name of realNames) {
  3706. prom.push(this.#toggleVk({
  3707. name: name,
  3708. doTask: doTask
  3709. }));
  3710. await delay(1e3);
  3711. }
  3712. }
  3713. }
  3714. return Promise.all(prom).then(() => true);
  3715. } catch (error) {
  3716. throwError(error, 'Vk.toggle');
  3717. return false;
  3718. }
  3719. }
  3720. #setCache(name, postId) {
  3721. try {
  3722. this.#cache[name] = postId;
  3723. GM_setValue('vkCache', this.#cache);
  3724. } catch (error) {
  3725. throwError(error, 'Vk.setCache');
  3726. }
  3727. }
  3728. }
  3729. const social_Vk = Vk;
  3730. const getInfo = async function(link, type) {
  3731. try {
  3732. const logStatus = scripts_echoLog({
  3733. text: i18n('gettingYtbToken')
  3734. });
  3735. const {
  3736. result,
  3737. statusText,
  3738. status,
  3739. data
  3740. } = await tools_httpRequest({
  3741. url: link,
  3742. method: 'GET'
  3743. });
  3744. if (result === 'Success') {
  3745. if (data?.status === 200) {
  3746. if (data.responseText.includes('accounts.google.com/ServiceLogin?service=youtube')) {
  3747. logStatus.error(`Error:${i18n('loginYtb')}`, true);
  3748. return {
  3749. needLogin: true
  3750. };
  3751. }
  3752. const apiKey = data.responseText.match(/"INNERTUBE_API_KEY":"(.*?)"/)?.[1];
  3753. const context = (data.responseText.match(/\(\{"INNERTUBE_CONTEXT":([\w\W]*?)\}\)/) || data.responseText.match(/"INNERTUBE_CONTEXT":([\w\W]*?\}),"INNERTUBE/))?.[1] || '{}';
  3754. const {
  3755. client,
  3756. request
  3757. } = JSON.parse(context);
  3758. if (apiKey && client && request) {
  3759. client.hl = 'en';
  3760. if (type === 'channel') {
  3761. const channelId = data.responseText.match(/"channelId":"(.+?)"/)?.[1];
  3762. if (channelId) {
  3763. logStatus.success();
  3764. return {
  3765. params: {
  3766. apiKey: apiKey,
  3767. client: client,
  3768. request: request,
  3769. channelId: channelId
  3770. }
  3771. };
  3772. }
  3773. logStatus.error('Error: Get "channelId" failed!');
  3774. return {};
  3775. } else if (type === 'likeVideo') {
  3776. const videoId = data.responseText.match(/<link rel="shortlinkUrl" href="https:\/\/youtu\.be\/(.*?)">/)?.[1];
  3777. const likeParams = data.responseText.match(/"likeParams":"(.*?)"/)?.[1];
  3778. if (videoId) {
  3779. logStatus.success();
  3780. return {
  3781. params: {
  3782. apiKey: apiKey,
  3783. client: client,
  3784. request: request,
  3785. videoId: videoId,
  3786. likeParams: likeParams
  3787. }
  3788. };
  3789. }
  3790. logStatus.error('Error: Get "videoId" failed!');
  3791. return {};
  3792. }
  3793. logStatus.error('Error: Unknown type');
  3794. return {};
  3795. }
  3796. logStatus.error('Error: Parameter "apiKey" not found!');
  3797. return {};
  3798. }
  3799. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3800. return {};
  3801. }
  3802. logStatus.error(`${result}:${statusText}(${status})`);
  3803. return {};
  3804. } catch (error) {
  3805. throwError(error, 'Youtube.getInfo');
  3806. return {};
  3807. }
  3808. };
  3809. class Youtube extends social_Social {
  3810. tasks;
  3811. whiteList;
  3812. #auth = GM_getValue('youtubeAuth') || {};
  3813. #initialized = false;
  3814. #verifyChannel = `https://www.youtube.com/channel/${globalOptions.other.youtubeVerifyChannel}`;
  3815. constructor() {
  3816. super();
  3817. const defaultTasksTemplate = {
  3818. channels: [],
  3819. likes: []
  3820. };
  3821. this.tasks = defaultTasksTemplate;
  3822. this.whiteList = {
  3823. ...defaultTasksTemplate,
  3824. ...GM_getValue('whiteList')?.youtube || {}
  3825. };
  3826. }
  3827. async init() {
  3828. try {
  3829. if (this.#initialized) {
  3830. return true;
  3831. }
  3832. if (!this.#auth.PAPISID) {
  3833. if (await this.#updateAuth()) {
  3834. this.#initialized = true;
  3835. return true;
  3836. }
  3837. return false;
  3838. }
  3839. const isVerified = await this.#verifyAuth();
  3840. if (isVerified) {
  3841. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  3842. this.#initialized = true;
  3843. return true;
  3844. }
  3845. GM_setValue('youtubeAuth', null);
  3846. if (await this.#updateAuth()) {
  3847. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  3848. this.#initialized = true;
  3849. return true;
  3850. }
  3851. scripts_echoLog({}).error(i18n('initFailed', 'Youtube'));
  3852. return false;
  3853. } catch (error) {
  3854. throwError(error, 'Youtube.init');
  3855. return false;
  3856. }
  3857. }
  3858. async #verifyAuth() {
  3859. try {
  3860. return await this.#toggleChannel({
  3861. link: this.#verifyChannel,
  3862. doTask: true,
  3863. verify: true
  3864. });
  3865. } catch (error) {
  3866. throwError(error, 'Youtube.verifyAuth');
  3867. return false;
  3868. }
  3869. }
  3870. async #updateAuth() {
  3871. try {
  3872. const logStatus = scripts_echoLog({
  3873. text: i18n('updatingAuth', 'Youtube')
  3874. });
  3875. return await new Promise(resolve => {
  3876. GM_cookie.list({
  3877. url: 'https://www.youtube.com/@YouTube'
  3878. }, async (cookies, error) => {
  3879. if (!error) {
  3880. const PAPISID = cookies.find(cookie => cookie.name === '__Secure-3PAPISID')?.value;
  3881. if (PAPISID) {
  3882. GM_setValue('youtubeAuth', {
  3883. PAPISID: PAPISID
  3884. });
  3885. this.#auth = {
  3886. PAPISID: PAPISID
  3887. };
  3888. logStatus.success();
  3889. resolve(await this.#verifyAuth());
  3890. } else {
  3891. logStatus.error(i18n('needLogin'));
  3892. resolve(false);
  3893. }
  3894. } else {
  3895. logStatus.error('Error: Update youtube auth failed!');
  3896. resolve(false);
  3897. }
  3898. });
  3899. });
  3900. } catch (error) {
  3901. throwError(error, 'Youtube.updateAuth');
  3902. return false;
  3903. }
  3904. }
  3905. #getInfo(link, type) {
  3906. return getInfo(link, type);
  3907. }
  3908. async #toggleChannel({
  3909. link,
  3910. doTask = true,
  3911. verify = false
  3912. }) {
  3913. try {
  3914. const {
  3915. params,
  3916. needLogin
  3917. } = await this.#getInfo(link, 'channel');
  3918. const {
  3919. apiKey,
  3920. client,
  3921. request,
  3922. channelId
  3923. } = params || {};
  3924. if (needLogin) {
  3925. scripts_echoLog({
  3926. html: i18n('loginYtb')
  3927. });
  3928. return false;
  3929. }
  3930. if (!(apiKey && client && request && channelId)) {
  3931. scripts_echoLog({
  3932. text: '"getYtbToken" failed'
  3933. });
  3934. return false;
  3935. }
  3936. if (!doTask && !verify && this.whiteList.channels.includes(channelId)) {
  3937. scripts_echoLog({
  3938. type: 'whiteList',
  3939. text: 'Youtube.unfollowChannel',
  3940. id: channelId
  3941. });
  3942. return true;
  3943. }
  3944. const logStatus = verify ? scripts_echoLog({
  3945. text: i18n('verifyingAuth', 'Youtube')
  3946. }) : scripts_echoLog({
  3947. type: doTask ? 'followingYtbChannel' : 'unfollowingYtbChannel',
  3948. text: channelId
  3949. });
  3950. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  3951. const {
  3952. result,
  3953. statusText,
  3954. status,
  3955. data
  3956. } = await tools_httpRequest({
  3957. url: `https://www.youtube.com/youtubei/v1/subscription/${doTask ? '' : 'un'}subscribe?key=${apiKey}&prettyPrint=false`,
  3958. method: 'POST',
  3959. headers: {
  3960. origin: 'https://www.youtube.com',
  3961. referer: `https://www.youtube.com/channel/${channelId}`,
  3962. 'content-type': 'application/json',
  3963. 'x-goog-authuser': '0',
  3964. 'x-goog-visitor-id': client?.visitorData,
  3965. 'x-origin': 'https://www.youtube.com',
  3966. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  3967. },
  3968. data: JSON.stringify({
  3969. context: {
  3970. client: client,
  3971. request: {
  3972. sessionId: request?.sessionId,
  3973. internalExperimentFlags: [],
  3974. consistencyTokenJars: []
  3975. },
  3976. user: {}
  3977. },
  3978. channelIds: [ channelId ],
  3979. params: doTask ? 'EgIIAhgA' : 'CgIIAhgA'
  3980. })
  3981. });
  3982. if (result === 'Success') {
  3983. if (data?.status === 200) {
  3984. if (doTask && (/"subscribed":true/.test(data.responseText) || data.responseText.includes('The subscription already exists')) || !doTask && /"subscribed":false/.test(data.responseText)) {
  3985. logStatus.success();
  3986. if (doTask && !verify) {
  3987. this.tasks.channels = unique([ ...this.tasks.channels, link ]);
  3988. }
  3989. return true;
  3990. }
  3991. if (verify && data.responseText.includes('You may not subscribe to yourself')) {
  3992. logStatus.success();
  3993. return true;
  3994. }
  3995. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  3996. return false;
  3997. }
  3998. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3999. return false;
  4000. }
  4001. logStatus.error(`${result}:${statusText}(${status})`);
  4002. return false;
  4003. } catch (error) {
  4004. throwError(error, 'Youtube.toggleChannel');
  4005. return false;
  4006. }
  4007. }
  4008. async #toggleLikeVideo({
  4009. link,
  4010. doTask = true
  4011. }) {
  4012. try {
  4013. const {
  4014. params,
  4015. needLogin
  4016. } = await this.#getInfo(link, 'likeVideo');
  4017. const {
  4018. apiKey,
  4019. client,
  4020. request,
  4021. videoId,
  4022. likeParams
  4023. } = params || {};
  4024. if (needLogin) {
  4025. scripts_echoLog({
  4026. html: `${i18n('loginYtb')}`
  4027. });
  4028. return false;
  4029. }
  4030. if (!(apiKey && client && request && videoId && likeParams)) {
  4031. scripts_echoLog({
  4032. text: '"getYtbToken" failed'
  4033. });
  4034. return false;
  4035. }
  4036. if (!doTask && this.whiteList.likes.includes(videoId)) {
  4037. scripts_echoLog({
  4038. type: 'whiteList',
  4039. text: 'Youtube.unlikeVideo',
  4040. id: videoId
  4041. });
  4042. return true;
  4043. }
  4044. const logStatus = scripts_echoLog({
  4045. type: doTask ? 'likingYtbVideo' : 'unlikingYtbVideo',
  4046. text: videoId
  4047. });
  4048. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  4049. const likeVideoData = {
  4050. context: {
  4051. client: client,
  4052. request: {
  4053. sessionId: request.sessionId,
  4054. internalExperimentFlags: [],
  4055. consistencyTokenJars: []
  4056. },
  4057. user: {}
  4058. },
  4059. target: {
  4060. videoId: videoId
  4061. }
  4062. };
  4063. if (doTask) {
  4064. if (likeParams) {
  4065. likeVideoData.params = likeParams;
  4066. } else {
  4067. logStatus.error('Empty likeParams');
  4068. return false;
  4069. }
  4070. }
  4071. const {
  4072. result,
  4073. statusText,
  4074. status,
  4075. data
  4076. } = await tools_httpRequest({
  4077. url: `https://www.youtube.com/youtubei/v1/like/${doTask ? '' : 'remove'}like?key=${apiKey}`,
  4078. method: 'POST',
  4079. headers: {
  4080. origin: 'https://www.youtube.com',
  4081. referer: `https://www.youtube.com/watch?v=${videoId}`,
  4082. 'content-type': 'application/json',
  4083. 'x-goog-authuser': '0',
  4084. 'x-goog-visitor-id': client.visitorData,
  4085. 'x-origin': 'https://www.youtube.com',
  4086. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  4087. },
  4088. data: JSON.stringify(likeVideoData)
  4089. });
  4090. if (result === 'Success') {
  4091. if (data?.status === 200) {
  4092. if (doTask && data.responseText.includes('Added to Liked videos') || !doTask && (data.responseText.includes('Removed from Liked videos') || data.responseText.includes('Dislike removed'))) {
  4093. logStatus.success();
  4094. if (doTask) {
  4095. this.tasks.likes = unique([ ...this.tasks.likes, link ]);
  4096. }
  4097. return true;
  4098. }
  4099. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4100. return false;
  4101. }
  4102. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4103. return false;
  4104. }
  4105. logStatus.error(`${result}:${statusText}(${status})`);
  4106. return false;
  4107. } catch (error) {
  4108. throwError(error, 'Youtube.toggleLikeVideo');
  4109. return false;
  4110. }
  4111. }
  4112. async toggle({
  4113. doTask = true,
  4114. channelLinks = [],
  4115. videoLinks = []
  4116. }) {
  4117. try {
  4118. if (!this.#initialized) {
  4119. scripts_echoLog({
  4120. text: i18n('needInit')
  4121. });
  4122. return false;
  4123. }
  4124. const prom = [];
  4125. if (doTask && !globalOptions.doTask.youtube.channels || !doTask && !globalOptions.undoTask.youtube.channels) {
  4126. scripts_echoLog({
  4127. type: 'globalOptionsSkip',
  4128. text: 'youtube.channels'
  4129. });
  4130. } else {
  4131. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => {
  4132. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4133. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4134. }
  4135. return link;
  4136. });
  4137. if (realChannels.length > 0) {
  4138. for (const channel of realChannels) {
  4139. prom.push(this.#toggleChannel({
  4140. link: channel,
  4141. doTask: doTask
  4142. }));
  4143. await delay(1e3);
  4144. }
  4145. }
  4146. }
  4147. if (doTask && !globalOptions.doTask.youtube.likes || !doTask && !globalOptions.undoTask.youtube.likes) {
  4148. scripts_echoLog({
  4149. type: 'globalOptionsSkip',
  4150. text: 'youtube.likes'
  4151. });
  4152. } else {
  4153. const realLikes = this.getRealParams('likes', videoLinks, doTask, link => {
  4154. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4155. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4156. }
  4157. return link;
  4158. });
  4159. if (realLikes.length > 0) {
  4160. for (const video of realLikes) {
  4161. prom.push(this.#toggleLikeVideo({
  4162. link: video,
  4163. doTask: doTask
  4164. }));
  4165. await delay(1e3);
  4166. }
  4167. }
  4168. }
  4169. return Promise.all(prom).then(() => true);
  4170. } catch (error) {
  4171. throwError(error, 'Youtube.toggle');
  4172. return false;
  4173. }
  4174. }
  4175. }
  4176. class SteamASF {
  4177. #asfOptions;
  4178. #botName = 'asf';
  4179. #groupInfo;
  4180. async init() {
  4181. try {
  4182. const asfCommandsUrl = new URL('/Api/Command/', globalOptions.ASF.AsfIpcUrl);
  4183. this.#asfOptions = {
  4184. url: asfCommandsUrl.href,
  4185. method: 'POST',
  4186. responseType: 'json',
  4187. headers: {
  4188. accept: 'application/json',
  4189. 'Content-Type': 'application/json',
  4190. Host: asfCommandsUrl.host,
  4191. Origin: asfCommandsUrl.origin,
  4192. Referer: asfCommandsUrl.href,
  4193. Authentication: globalOptions.ASF.AsfIpcPassword
  4194. }
  4195. };
  4196. if (globalOptions.ASF.AsfBotname) {
  4197. this.#botName = globalOptions.ASF.AsfBotname;
  4198. }
  4199. const logStatus = scripts_echoLog({
  4200. text: i18n('initingASF')
  4201. });
  4202. const {
  4203. result,
  4204. statusText,
  4205. status,
  4206. data
  4207. } = await tools_httpRequest({
  4208. ...this.#asfOptions,
  4209. data: '{"Command":"!stats"}'
  4210. });
  4211. if (result === 'Success') {
  4212. if (data?.response?.Success === true && data.response.Message === 'OK' && data.response.Result) {
  4213. logStatus.success();
  4214. return true;
  4215. }
  4216. if (data?.response?.Result || data?.response?.Message) {
  4217. logStatus.error(data?.response?.Result || data.response.Message);
  4218. return false;
  4219. }
  4220. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4221. return false;
  4222. }
  4223. logStatus.error(`${result}:${statusText}(${status})`);
  4224. return false;
  4225. } catch (error) {
  4226. throwError(error, 'SteamASF.init');
  4227. return false;
  4228. }
  4229. }
  4230. async joinGroup(groupName) {
  4231. try {
  4232. const logStatus = scripts_echoLog({
  4233. type: 'joiningSteamGroup',
  4234. text: groupName
  4235. });
  4236. const {
  4237. result,
  4238. statusText,
  4239. status,
  4240. data
  4241. } = await tools_httpRequest({
  4242. ...this.#asfOptions,
  4243. data: JSON.stringify({
  4244. Command: `!JOINGROUP ${this.#botName} ${groupName}`
  4245. })
  4246. });
  4247. if (result === 'Success') {
  4248. if (data?.status === 200 && [ '已加入', '已申请', 'Joined', 'Applied', 'Присоединился', 'costs' ].find(text => data.response?.Result?.includes(text))) {
  4249. logStatus.success();
  4250. return true;
  4251. }
  4252. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4253. return false;
  4254. }
  4255. logStatus.error(`${result}:${statusText}(${status})`);
  4256. return false;
  4257. } catch (error) {
  4258. throwError(error, 'SteamASF.joinGroup');
  4259. return false;
  4260. }
  4261. }
  4262. async leaveGroup(groupName) {
  4263. try {
  4264. if (!this.#groupInfo) {
  4265. if (!await this.#getGroupId()) {
  4266. return false;
  4267. }
  4268. }
  4269. const groupId = await this.#groupInfo[groupName];
  4270. if (!groupId) {
  4271. return false;
  4272. }
  4273. const logStatus = scripts_echoLog({
  4274. type: 'leavingSteamGroup',
  4275. text: groupName
  4276. });
  4277. const {
  4278. result,
  4279. statusText,
  4280. status,
  4281. data
  4282. } = await tools_httpRequest({
  4283. ...this.#asfOptions,
  4284. data: JSON.stringify({
  4285. Command: `!LEAVEGROUP ${this.#botName} ${groupId}`
  4286. })
  4287. });
  4288. if (result === 'Success') {
  4289. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4290. logStatus.success();
  4291. return true;
  4292. }
  4293. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4294. return false;
  4295. }
  4296. logStatus.error(`${result}:${statusText}(${status})`);
  4297. return false;
  4298. } catch (error) {
  4299. throwError(error, 'SteamASF.leaveGroup');
  4300. return false;
  4301. }
  4302. }
  4303. async #getGroupId() {
  4304. try {
  4305. const logStatus = scripts_echoLog({
  4306. type: 'gettingSteamGroupId',
  4307. text: 'All'
  4308. });
  4309. const {
  4310. result,
  4311. statusText,
  4312. status,
  4313. data
  4314. } = await tools_httpRequest({
  4315. ...this.#asfOptions,
  4316. data: JSON.stringify({
  4317. Command: `!GROUPLIST ${this.#botName}`
  4318. })
  4319. });
  4320. if (result === 'Success') {
  4321. if (data?.status === 200 && data.response?.Result?.includes('|')) {
  4322. this.#groupInfo = Object.fromEntries(data.response.Result.split('\n').map(line => {
  4323. const [ , name, id ] = line.trim().split('|');
  4324. if (name && id) {
  4325. return [ name, id ];
  4326. }
  4327. return null;
  4328. }).filter(ele => ele));
  4329. logStatus.success();
  4330. return true;
  4331. }
  4332. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4333. return false;
  4334. }
  4335. logStatus.error(`${result}:${statusText}(${status})`);
  4336. return false;
  4337. } catch (error) {
  4338. throwError(error, 'SteamASF.getGroupID');
  4339. return false;
  4340. }
  4341. }
  4342. async addToWishlist(gameId) {
  4343. try {
  4344. const logStatus = scripts_echoLog({
  4345. type: 'addingToWishlist',
  4346. text: gameId
  4347. });
  4348. if ((await this.#checkGame(gameId)).wishlist === true) {
  4349. logStatus.success();
  4350. return true;
  4351. }
  4352. const {
  4353. result,
  4354. statusText,
  4355. status,
  4356. data
  4357. } = await tools_httpRequest({
  4358. ...this.#asfOptions,
  4359. data: JSON.stringify({
  4360. Command: `!ADDWISHLIST ${this.#botName} ${gameId}`
  4361. })
  4362. });
  4363. if (result === 'Success') {
  4364. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4365. logStatus.success();
  4366. return true;
  4367. }
  4368. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4369. return false;
  4370. }
  4371. logStatus.error(`${result}:${statusText}(${status})`);
  4372. return false;
  4373. } catch (error) {
  4374. throwError(error, 'SteamASF.addToWishlist');
  4375. return false;
  4376. }
  4377. }
  4378. async removeFromWishlist(gameId) {
  4379. try {
  4380. const logStatus = scripts_echoLog({
  4381. type: 'removingFromWishlist',
  4382. text: gameId
  4383. });
  4384. if ((await this.#checkGame(gameId)).wishlist === false) {
  4385. logStatus.success();
  4386. return true;
  4387. }
  4388. const {
  4389. result,
  4390. statusText,
  4391. status,
  4392. data
  4393. } = await tools_httpRequest({
  4394. ...this.#asfOptions,
  4395. data: JSON.stringify({
  4396. Command: `!REMOVEWISHLIST ${this.#botName} ${gameId}`
  4397. })
  4398. });
  4399. if (result === 'Success') {
  4400. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4401. logStatus.success();
  4402. return true;
  4403. }
  4404. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4405. return false;
  4406. }
  4407. logStatus.error(`${result}:${statusText}(${status})`);
  4408. return false;
  4409. } catch (error) {
  4410. throwError(error, 'SteamASF.removeFromWishlist');
  4411. return false;
  4412. }
  4413. }
  4414. async toggleFollowGame(gameId, doTask) {
  4415. try {
  4416. const logStatus = scripts_echoLog({
  4417. type: `${doTask ? '' : 'un'}followingGame`,
  4418. text: gameId
  4419. });
  4420. if (doTask && (await this.#checkGame(gameId)).followed === true || !doTask && (await this.#checkGame(gameId)).followed === false) {
  4421. logStatus.success();
  4422. return true;
  4423. }
  4424. const {
  4425. result,
  4426. statusText,
  4427. status,
  4428. data
  4429. } = await tools_httpRequest({
  4430. ...this.#asfOptions,
  4431. data: JSON.stringify({
  4432. Command: `!${doTask ? '' : 'UN'}FOLLOWGAME ${this.#botName} ${gameId}`
  4433. })
  4434. });
  4435. if (result === 'Success') {
  4436. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4437. logStatus.success();
  4438. return true;
  4439. }
  4440. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4441. return false;
  4442. }
  4443. logStatus.error(`${result}:${statusText}(${status})`);
  4444. return false;
  4445. } catch (error) {
  4446. throwError(error, 'SteamASF.toggleFollowGame');
  4447. return false;
  4448. }
  4449. }
  4450. async #checkGame(gameId) {
  4451. try {
  4452. const {
  4453. result,
  4454. data
  4455. } = await tools_httpRequest({
  4456. ...this.#asfOptions,
  4457. data: JSON.stringify({
  4458. Command: `!CHECK ${this.#botName} ${gameId}`
  4459. })
  4460. });
  4461. if (result === 'Success') {
  4462. if (data?.status === 200 && data.response?.Result?.includes(gameId)) {
  4463. const matchedResult = data.response.Result.split('\n').find(result => result.includes(gameId))?.split('|');
  4464. if (matchedResult?.length > 3) {
  4465. return {
  4466. wishlist: matchedResult.at(-3).trim() === '√' || matchedResult.at(-2).trim() === '√',
  4467. followed: matchedResult.at(-1).trim() === '√'
  4468. };
  4469. }
  4470. return {};
  4471. }
  4472. return {};
  4473. }
  4474. return {};
  4475. } catch (error) {
  4476. throwError(error, 'SteamASF.checkGame');
  4477. return {};
  4478. }
  4479. }
  4480. async toggleCurator(curatorId, doTask = true) {
  4481. try {
  4482. const logStatus = scripts_echoLog({
  4483. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  4484. text: curatorId
  4485. });
  4486. const {
  4487. result,
  4488. statusText,
  4489. status,
  4490. data
  4491. } = await tools_httpRequest({
  4492. ...this.#asfOptions,
  4493. data: JSON.stringify({
  4494. Command: `!${doTask ? '' : 'UN'}FOLLOWCURATOR ${this.#botName} ${curatorId}`
  4495. })
  4496. });
  4497. if (result === 'Success') {
  4498. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4499. logStatus.success();
  4500. return true;
  4501. }
  4502. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4503. return false;
  4504. }
  4505. logStatus.error(`${result}:${statusText}(${status})`);
  4506. return false;
  4507. } catch (error) {
  4508. throwError(error, 'Steam.toggleCurator');
  4509. return false;
  4510. }
  4511. }
  4512. async addLicense(id) {
  4513. try {
  4514. const [ type, ids ] = id.split('-');
  4515. if (type === 'appid') {
  4516. const logStatus = scripts_echoLog({
  4517. type: 'addingFreeLicense',
  4518. text: ids
  4519. });
  4520. const {
  4521. result,
  4522. statusText,
  4523. status,
  4524. data
  4525. } = await tools_httpRequest({
  4526. ...this.#asfOptions,
  4527. data: JSON.stringify({
  4528. Command: `!addlicense ${this.#botName} app/${ids}`
  4529. })
  4530. });
  4531. if (result === 'Success') {
  4532. if (data?.status === 200 && [ 'AlreadyPurchased', 'OK' ].find(text => data.response?.Result?.includes(text))) {
  4533. logStatus.success();
  4534. return true;
  4535. }
  4536. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4537. return false;
  4538. }
  4539. logStatus.error(`${result}:${statusText}(${status})`);
  4540. return false;
  4541. } else if (type === 'subid') {
  4542. const idsArr = ids.split(',');
  4543. const logStatus = scripts_echoLog({
  4544. type: 'addingFreeLicenseSubid',
  4545. text: ids
  4546. });
  4547. const {
  4548. result,
  4549. statusText,
  4550. status,
  4551. data
  4552. } = await tools_httpRequest({
  4553. ...this.#asfOptions,
  4554. data: JSON.stringify({
  4555. Command: `!addlicense ${this.#botName} ${idsArr.map(id => `sub/${id}`).join(',')}`
  4556. })
  4557. });
  4558. if (result === 'Success') {
  4559. if (data?.status === 200 && data.response?.Result) {
  4560. const resultLines = data.response.Result.split('\n');
  4561. idsArr.forEach(subid => {
  4562. const targetLine = resultLines.find(text => text.includes(subid));
  4563. if (targetLine && [ '成功', 'Success', 'Успех' ].find(text => targetLine.includes(text))) {
  4564. scripts_echoLog({}).success(targetLine);
  4565. } else {
  4566. scripts_echoLog({}).error(targetLine);
  4567. }
  4568. });
  4569. return true;
  4570. }
  4571. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4572. return false;
  4573. }
  4574. logStatus.error(`${result}:${statusText}(${status})`);
  4575. return false;
  4576. }
  4577. return false;
  4578. } catch (error) {
  4579. throwError(error, 'SteamASF.addLicense');
  4580. return false;
  4581. }
  4582. }
  4583. async requestPlayTestAccess(id) {
  4584. try {
  4585. const logStatus = scripts_echoLog({
  4586. type: 'requestingPlayTestAccess',
  4587. text: id
  4588. });
  4589. const {
  4590. result,
  4591. statusText,
  4592. status,
  4593. data
  4594. } = await tools_httpRequest({
  4595. ...this.#asfOptions,
  4596. data: JSON.stringify({
  4597. Command: `!REQUESTACCESS ${this.#botName} ${id}`
  4598. })
  4599. });
  4600. if (result === 'Success') {
  4601. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4602. logStatus.success();
  4603. return true;
  4604. }
  4605. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4606. return false;
  4607. }
  4608. logStatus.error(`${result}:${statusText}(${status})`);
  4609. return false;
  4610. } catch (error) {
  4611. throwError(error, 'Steam.requestPlayTestAccess');
  4612. return false;
  4613. }
  4614. }
  4615. }
  4616. const social_SteamASF = SteamASF;
  4617. class Steam extends social_Social {
  4618. tasks;
  4619. whiteList;
  4620. #cache = {
  4621. ...{
  4622. group: {},
  4623. officialGroup: {},
  4624. forum: {},
  4625. workshop: {},
  4626. curator: {}
  4627. },
  4628. ...GM_getValue('steamCache')
  4629. };
  4630. #auth = {};
  4631. #storeInitialized = false;
  4632. #communityInitialized = false;
  4633. #area = 'CN';
  4634. #oldArea;
  4635. #areaStatus = 'end';
  4636. #ASF;
  4637. constructor() {
  4638. super();
  4639. const defaultTasksTemplate = {
  4640. groups: [],
  4641. officialGroups: [],
  4642. wishlists: [],
  4643. follows: [],
  4644. forums: [],
  4645. workshops: [],
  4646. workshopVotes: [],
  4647. curators: [],
  4648. curatorLikes: [],
  4649. announcements: [],
  4650. licenses: [],
  4651. playtests: []
  4652. };
  4653. this.tasks = defaultTasksTemplate;
  4654. this.whiteList = {
  4655. ...defaultTasksTemplate,
  4656. ...GM_getValue('whiteList')?.steam || {}
  4657. };
  4658. }
  4659. async init(type = 'all') {
  4660. try {
  4661. if (globalOptions.ASF.AsfEnabled && globalOptions.ASF.AsfIpcUrl && globalOptions.ASF.AsfIpcPassword) {
  4662. this.#ASF = new social_SteamASF();
  4663. if (await this.#ASF.init()) {
  4664. this.#storeInitialized = true;
  4665. this.#communityInitialized = true;
  4666. return true;
  4667. }
  4668. return false;
  4669. }
  4670. if (type === 'store') {
  4671. if (this.#storeInitialized) {
  4672. return true;
  4673. }
  4674. let storeInitialized = await this.#updateStoreAuth();
  4675. if (!storeInitialized) {
  4676. storeInitialized = await this.#updateStoreAuthTab();
  4677. }
  4678. this.#storeInitialized = storeInitialized;
  4679. if (!this.#storeInitialized) {
  4680. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4681. return false;
  4682. }
  4683. scripts_echoLog({}).success(i18n('initSuccess', 'SteamStore'));
  4684. return true;
  4685. }
  4686. if (type === 'community') {
  4687. if (this.#communityInitialized) {
  4688. return true;
  4689. }
  4690. let communityInitialized = await this.#updateCommunityAuth();
  4691. if (!communityInitialized) {
  4692. communityInitialized = await this.#updateCommunityAuthTab();
  4693. GM_setValue('steamCommunityAuth', null);
  4694. }
  4695. this.#communityInitialized = communityInitialized;
  4696. if (!this.#communityInitialized) {
  4697. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4698. return false;
  4699. }
  4700. scripts_echoLog({}).success(i18n('initSuccess', 'SteamCommunity'));
  4701. return true;
  4702. }
  4703. if (this.#storeInitialized && this.#communityInitialized) {
  4704. scripts_echoLog({}).success(i18n('initSuccess', 'Steam'));
  4705. return true;
  4706. }
  4707. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4708. return false;
  4709. } catch (error) {
  4710. throwError(error, 'Steam.init');
  4711. return false;
  4712. }
  4713. }
  4714. async #refreshToken(type = 'steamStore') {
  4715. try {
  4716. const host = {
  4717. steamStore: 'store.steampowered.com',
  4718. steamCommunity: 'steamcommunity.com'
  4719. };
  4720. const logStatus = scripts_echoLog({
  4721. text: i18n('refreshingToken', i18n(type))
  4722. });
  4723. const formData = new FormData();
  4724. formData.append('redir', `https://${host[type]}/`);
  4725. const {
  4726. result,
  4727. statusText,
  4728. status,
  4729. data
  4730. } = await tools_httpRequest({
  4731. url: 'https://login.steampowered.com/jwt/ajaxrefresh',
  4732. method: 'POST',
  4733. responseType: 'json',
  4734. headers: {
  4735. Host: 'login.steampowered.com',
  4736. Origin: `https://${host[type]}`,
  4737. Referer: `https://${host[type]}/`
  4738. },
  4739. data: formData
  4740. });
  4741. if (result === 'Success') {
  4742. if (data?.response?.success) {
  4743. if (await this.#setStoreToken(data.response, type)) {
  4744. logStatus.success();
  4745. return true;
  4746. }
  4747. logStatus.error('Error');
  4748. return false;
  4749. }
  4750. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4751. return false;
  4752. }
  4753. logStatus.error(`${result}:${statusText}(${status})`);
  4754. return false;
  4755. } catch (error) {
  4756. throwError(error, 'Steam.refreshToken');
  4757. return false;
  4758. }
  4759. }
  4760. async #setStoreToken(param, type) {
  4761. try {
  4762. const host = {
  4763. steamStore: 'store.steampowered.com',
  4764. steamCommunity: 'steamcommunity.com'
  4765. };
  4766. const logStatus = scripts_echoLog({
  4767. text: i18n('settingToken', i18n(type))
  4768. });
  4769. const formData = new FormData();
  4770. formData.append('steamID', param.steamID);
  4771. formData.append('nonce', param.nonce);
  4772. formData.append('redir', param.redir);
  4773. formData.append('auth', param.auth);
  4774. const {
  4775. result,
  4776. statusText,
  4777. status,
  4778. data
  4779. } = await tools_httpRequest({
  4780. url: `https://${host[type]}/login/settoken`,
  4781. method: 'POST',
  4782. headers: {
  4783. Accept: 'application/json, text/plain, */*',
  4784. Host: host[type],
  4785. Origin: `https://${host[type]}`
  4786. },
  4787. data: formData
  4788. });
  4789. if (result === 'Success') {
  4790. if (data?.status === 200) {
  4791. logStatus.success();
  4792. return true;
  4793. }
  4794. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4795. return false;
  4796. }
  4797. logStatus.error(`${result}:${statusText}(${status})`);
  4798. return false;
  4799. } catch (error) {
  4800. throwError(error, 'Steam.setStoreToken');
  4801. return false;
  4802. }
  4803. }
  4804. async #updateStoreAuth(retry = false) {
  4805. try {
  4806. const logStatus = scripts_echoLog({
  4807. text: i18n('updatingAuth', i18n('steamStore'))
  4808. });
  4809. const {
  4810. result,
  4811. statusText,
  4812. status,
  4813. data
  4814. } = await tools_httpRequest({
  4815. url: 'https://store.steampowered.com/',
  4816. method: 'GET',
  4817. headers: {
  4818. 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',
  4819. 'Sec-Fetch-Dest': 'document',
  4820. 'Sec-Fetch-Mode': 'navigate',
  4821. 'Upgrade-Insecure-Requests': '1'
  4822. },
  4823. fetch: false,
  4824. redirect: 'manual'
  4825. });
  4826. if (data?.status === 200) {
  4827. if (!data.responseText.includes('data-miniprofile=')) {
  4828. if (await this.#refreshToken('steamStore')) {
  4829. logStatus.warning(i18n('retry'));
  4830. if (retry) {
  4831. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4832. return false;
  4833. }
  4834. return this.#updateStoreAuth(true);
  4835. }
  4836. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4837. return false;
  4838. }
  4839. const storeSessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  4840. if (storeSessionID) {
  4841. this.#auth.storeSessionID = storeSessionID;
  4842. logStatus.success();
  4843. return true;
  4844. }
  4845. logStatus.error('Error: Get "sessionID" failed');
  4846. return false;
  4847. }
  4848. if ([ 301, 302 ].includes(data?.status)) {
  4849. if (await this.#refreshToken('steamStore')) {
  4850. logStatus.warning(i18n('retry'));
  4851. if (retry) {
  4852. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4853. return false;
  4854. }
  4855. return this.#updateStoreAuth(true);
  4856. }
  4857. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4858. return false;
  4859. }
  4860. logStatus.error(`${result}:${statusText}(${status})`);
  4861. return false;
  4862. } catch (error) {
  4863. throwError(error, 'Steam.updateStoreAuth');
  4864. return false;
  4865. }
  4866. }
  4867. async #updateStoreAuthTab() {
  4868. try {
  4869. const logStatus = scripts_echoLog({
  4870. text: i18n('updatingAuth', i18n('steamStoreTab'))
  4871. });
  4872. return await new Promise(resolve => {
  4873. GM_deleteValue('steamStoreAuth');
  4874. GM_setValue('ATv4_updateStoreAuth', true);
  4875. const newTab = GM_openInTab('https://store.steampowered.com/', {
  4876. active: true,
  4877. setParent: true
  4878. });
  4879. newTab.name = 'ATv4_updateStoreAuth';
  4880. const listenerId = GM_addValueChangeListener('steamStoreAuth', (key, oldValue, newValue) => {
  4881. GM_removeValueChangeListener(listenerId);
  4882. GM_deleteValue('ATv4_updateStoreAuth');
  4883. newTab?.close();
  4884. window.focus();
  4885. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  4886. this.#auth.storeSessionID = newValue.storeSessionID;
  4887. logStatus.success();
  4888. resolve(true);
  4889. return;
  4890. }
  4891. logStatus.error('Failed');
  4892. resolve(false);
  4893. });
  4894. newTab.onclose = () => {
  4895. GM_deleteValue('ATv4_updateStoreAuth');
  4896. };
  4897. });
  4898. } catch (error) {
  4899. throwError(error, 'Steam.updateStoreAuthTab');
  4900. return false;
  4901. }
  4902. }
  4903. async #updateCommunityAuthTab() {
  4904. try {
  4905. const logStatus = scripts_echoLog({
  4906. text: i18n('updatingAuth', i18n('steamCommunityTab'))
  4907. });
  4908. return await new Promise(resolve => {
  4909. GM_deleteValue('steamCommunityAuth');
  4910. GM_setValue('ATv4_updateCommunityAuth', true);
  4911. const newTab = GM_openInTab('https://steamcommunity.com/my', {
  4912. active: true,
  4913. setParent: true
  4914. });
  4915. newTab.name = 'ATv4_updateCommunityAuth';
  4916. const listenerId = GM_addValueChangeListener('steamCommunityAuth', (key, oldValue, newValue) => {
  4917. GM_removeValueChangeListener(listenerId);
  4918. GM_deleteValue('ATv4_updateCommunityAuth');
  4919. newTab?.close();
  4920. window.focus();
  4921. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  4922. this.#auth.steam64Id = newValue.steam64Id;
  4923. this.#auth.communitySessionID = newValue.communitySessionID;
  4924. logStatus.success();
  4925. resolve(true);
  4926. return;
  4927. }
  4928. logStatus.error('Failed');
  4929. resolve(false);
  4930. });
  4931. newTab.onclose = () => {
  4932. GM_deleteValue('ATv4_updateCommunityAuth');
  4933. };
  4934. });
  4935. } catch (error) {
  4936. throwError(error, 'Steam.updateCommunityAuthTab');
  4937. return false;
  4938. }
  4939. }
  4940. async #updateCommunityAuth() {
  4941. try {
  4942. const logStatus = scripts_echoLog({
  4943. text: i18n('gettingUserLink')
  4944. });
  4945. const {
  4946. result,
  4947. statusText,
  4948. status,
  4949. data
  4950. } = await tools_httpRequest({
  4951. url: 'https://steamcommunity.com/my',
  4952. method: 'GET',
  4953. headers: {
  4954. 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',
  4955. Host: 'steamcommunity.com',
  4956. 'Sec-Fetch-Dest': 'document',
  4957. 'Sec-Fetch-Mode': 'navigate'
  4958. },
  4959. fetch: false
  4960. });
  4961. if (data?.status === 200) {
  4962. if (data.finalUrl.includes('https://steamcommunity.com/login/home')) {
  4963. logStatus.error(`Error:${i18n('needLoginSteamCommunity')}`, true);
  4964. return false;
  4965. }
  4966. const steam64Id = data.responseText.match(/g_steamID = "(.+?)";/)?.[1];
  4967. const communitySessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  4968. if (steam64Id && communitySessionID) {
  4969. this.#auth.steam64Id = steam64Id;
  4970. this.#auth.communitySessionID = communitySessionID;
  4971. logStatus.success();
  4972. return true;
  4973. }
  4974. logStatus.error('Error: Get "sessionID" failed');
  4975. return false;
  4976. }
  4977. logStatus.error(`${result}:${statusText}(${status})`);
  4978. return false;
  4979. } catch (error) {
  4980. throwError(error, 'Steam.updateCommunityAuth');
  4981. return false;
  4982. }
  4983. }
  4984. async #getAreaInfo() {
  4985. try {
  4986. const logStatus = scripts_echoLog({
  4987. text: i18n('gettingAreaInfo')
  4988. });
  4989. const {
  4990. result,
  4991. statusText,
  4992. status,
  4993. data
  4994. } = await tools_httpRequest({
  4995. url: 'https://store.steampowered.com/cart/',
  4996. method: 'GET'
  4997. });
  4998. if (result === 'Success') {
  4999. if (data?.status === 200) {
  5000. const cartConfigRaw = data.responseText.match(/data-cart_config="(.*?)"/)?.[1];
  5001. const temp = document.createElement('div');
  5002. temp.innerHTML = cartConfigRaw || '{}';
  5003. const cartConfigStr = temp.textContent || temp.innerText;
  5004. let cartConfig;
  5005. try {
  5006. cartConfig = JSON.parse(cartConfigStr);
  5007. } catch (error) {
  5008. logStatus.error('Error: get country info filed');
  5009. console.error(error);
  5010. return {};
  5011. }
  5012. if (!cartConfig.rgUserCountryOptions) {
  5013. logStatus.warning('Warning: Area cannot be changed');
  5014. return {};
  5015. }
  5016. const userInfoRaw = data.responseText.match(/data-userinfo="(.*?)"/)?.[1];
  5017. const temp1 = document.createElement('div');
  5018. temp1.innerHTML = userInfoRaw || '{}';
  5019. const userInfoStr = temp1.textContent || temp1.innerText;
  5020. let userInfo;
  5021. try {
  5022. userInfo = JSON.parse(userInfoStr);
  5023. } catch (error) {
  5024. logStatus.error('Error: get country info filed');
  5025. console.error(error);
  5026. return {};
  5027. }
  5028. const currentArea = userInfo.country_code;
  5029. const areas = Object.keys(cartConfig.rgUserCountryOptions).filter(area => area !== 'help');
  5030. if (currentArea && areas.length > 0) {
  5031. this.#area = currentArea;
  5032. logStatus.success();
  5033. return {
  5034. currentArea: currentArea,
  5035. areas: areas
  5036. };
  5037. }
  5038. logStatus.error('Error: get country info filed');
  5039. return {};
  5040. }
  5041. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5042. return {};
  5043. }
  5044. logStatus.error(`${result}:${statusText}(${status})`);
  5045. return {};
  5046. } catch (error) {
  5047. throwError(error, 'Steam.getAreaInfo');
  5048. return {};
  5049. }
  5050. }
  5051. async #changeArea(area) {
  5052. try {
  5053. if (this.#areaStatus === 'waiting') {
  5054. await new Promise(resolve => {
  5055. const checker = setInterval(() => {
  5056. if (this.#areaStatus !== 'waiting') {
  5057. clearInterval(checker);
  5058. resolve(true);
  5059. }
  5060. });
  5061. });
  5062. }
  5063. if (this.#area === area || !area && this.#area !== 'CN') {
  5064. return true;
  5065. }
  5066. this.#areaStatus = 'waiting';
  5067. let aimedArea = area;
  5068. if (!aimedArea) {
  5069. const {
  5070. currentArea,
  5071. areas
  5072. } = await this.#getAreaInfo();
  5073. if (!currentArea || !areas) {
  5074. this.#areaStatus = 'error';
  5075. return false;
  5076. }
  5077. if (currentArea !== 'CN') {
  5078. this.#areaStatus = 'skip';
  5079. scripts_echoLog({
  5080. text: 'notNeededChangeArea'
  5081. });
  5082. return 'skip';
  5083. }
  5084. const anotherArea = areas.filter(area => area && area !== 'CN');
  5085. if (!anotherArea || anotherArea.length === 0) {
  5086. this.#areaStatus = 'noAnotherArea';
  5087. scripts_echoLog({
  5088. text: 'noAnotherArea'
  5089. });
  5090. return false;
  5091. }
  5092. [ aimedArea ] = anotherArea;
  5093. }
  5094. const logStatus = scripts_echoLog({
  5095. text: i18n('changingArea', aimedArea)
  5096. });
  5097. const {
  5098. result,
  5099. statusText,
  5100. status,
  5101. data
  5102. } = await tools_httpRequest({
  5103. url: 'https://store.steampowered.com/country/setcountry',
  5104. method: 'POST',
  5105. headers: {
  5106. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5107. },
  5108. data: $.param({
  5109. cc: aimedArea,
  5110. sessionid: this.#auth.storeSessionID
  5111. })
  5112. });
  5113. if (result === 'Success') {
  5114. if (data?.status === 200 && data.responseText === 'true') {
  5115. const {
  5116. currentArea
  5117. } = await this.#getAreaInfo();
  5118. if (currentArea) {
  5119. this.#area = currentArea;
  5120. if (!this.#oldArea) {
  5121. this.#oldArea = currentArea;
  5122. }
  5123. }
  5124. if (currentArea === aimedArea) {
  5125. this.#areaStatus = 'success';
  5126. logStatus.success();
  5127. return currentArea;
  5128. }
  5129. this.#areaStatus = 'error';
  5130. logStatus.error('Error: change country filed');
  5131. return 'CN';
  5132. }
  5133. this.#areaStatus = 'error';
  5134. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5135. return 'CN';
  5136. }
  5137. this.#areaStatus = 'error';
  5138. logStatus.error(`${result}:${statusText}(${status})`);
  5139. return 'CN';
  5140. } catch (error) {
  5141. this.#areaStatus = 'error';
  5142. throwError(error, 'Steam.changeArea');
  5143. return false;
  5144. }
  5145. }
  5146. async #joinGroup(groupName) {
  5147. try {
  5148. if (this.#ASF) {
  5149. if (await this.#ASF.joinGroup(groupName)) {
  5150. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5151. return true;
  5152. }
  5153. return false;
  5154. }
  5155. const logStatus = scripts_echoLog({
  5156. type: 'joiningSteamGroup',
  5157. text: groupName
  5158. });
  5159. const {
  5160. result,
  5161. statusText,
  5162. status,
  5163. data
  5164. } = await tools_httpRequest({
  5165. url: `https://steamcommunity.com/groups/${groupName}`,
  5166. method: 'POST',
  5167. headers: {
  5168. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5169. },
  5170. data: $.param({
  5171. action: 'join',
  5172. sessionID: this.#auth.communitySessionID
  5173. })
  5174. });
  5175. if (result === 'Success') {
  5176. if (data?.status === 200 && !data.responseText.includes('grouppage_join_area')) {
  5177. logStatus.success();
  5178. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5179. return true;
  5180. }
  5181. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5182. return false;
  5183. }
  5184. logStatus.error(`${result}:${statusText}(${status})`);
  5185. return false;
  5186. } catch (error) {
  5187. throwError(error, 'Steam.joinGroup');
  5188. return false;
  5189. }
  5190. }
  5191. async #leaveGroup(groupName) {
  5192. try {
  5193. if (this.whiteList.groups.includes(groupName)) {
  5194. scripts_echoLog({
  5195. type: 'whiteList',
  5196. text: 'Steam.leaveGroup',
  5197. id: groupName
  5198. });
  5199. return true;
  5200. }
  5201. if (this.#ASF) {
  5202. return await this.#ASF.leaveGroup(groupName);
  5203. }
  5204. const groupId = await this.#getGroupId(groupName);
  5205. if (!groupId) {
  5206. return false;
  5207. }
  5208. const logStatus = scripts_echoLog({
  5209. type: 'leavingSteamGroup',
  5210. text: groupName
  5211. });
  5212. const {
  5213. result,
  5214. statusText,
  5215. status,
  5216. data
  5217. } = await tools_httpRequest({
  5218. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5219. method: 'POST',
  5220. headers: {
  5221. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5222. },
  5223. data: $.param({
  5224. sessionID: this.#auth.communitySessionID,
  5225. action: 'leaveGroup',
  5226. groupId: groupId
  5227. })
  5228. });
  5229. if (result === 'Success') {
  5230. 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) {
  5231. logStatus.success();
  5232. return true;
  5233. }
  5234. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5235. return false;
  5236. }
  5237. logStatus.error(`${result}:${statusText}(${status})`);
  5238. return false;
  5239. } catch (error) {
  5240. throwError(error, 'Steam.leaveGroup');
  5241. return false;
  5242. }
  5243. }
  5244. async #getGroupId(groupName) {
  5245. try {
  5246. const logStatus = scripts_echoLog({
  5247. type: 'gettingSteamGroupId',
  5248. text: groupName
  5249. });
  5250. const groupId = this.#cache.group[groupName];
  5251. if (groupId) {
  5252. logStatus.success();
  5253. return groupId;
  5254. }
  5255. const {
  5256. result,
  5257. statusText,
  5258. status,
  5259. data
  5260. } = await tools_httpRequest({
  5261. url: `https://steamcommunity.com/groups/${groupName}`,
  5262. method: 'GET',
  5263. headers: {
  5264. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5265. }
  5266. });
  5267. if (result === 'Success') {
  5268. if (data?.status === 200) {
  5269. const groupId = data.responseText.match(/OpenGroupChat\( '([0-9]+)'/)?.[1];
  5270. if (groupId) {
  5271. this.#setCache('group', groupName, groupId);
  5272. logStatus.success();
  5273. return groupId;
  5274. }
  5275. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5276. return false;
  5277. }
  5278. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5279. return false;
  5280. }
  5281. logStatus.error(`${result}:${statusText}(${status})`);
  5282. return false;
  5283. } catch (error) {
  5284. throwError(error, 'Steam.getGroupID');
  5285. return false;
  5286. }
  5287. }
  5288. async #joinOfficialGroup(gameId) {
  5289. try {
  5290. if (this.#ASF) {
  5291. if (await this.#ASF.joinGroup(gameId)) {
  5292. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5293. return true;
  5294. }
  5295. return false;
  5296. }
  5297. const logStatus = scripts_echoLog({
  5298. type: 'joiningSteamOfficialGroup',
  5299. text: gameId
  5300. });
  5301. const {
  5302. result,
  5303. statusText,
  5304. status,
  5305. data
  5306. } = await tools_httpRequest({
  5307. url: `https://steamcommunity.com/games/${gameId}?action=join&sessionID=${this.#auth.communitySessionID}`,
  5308. method: 'GET',
  5309. headers: {
  5310. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5311. }
  5312. });
  5313. if (result === 'Success') {
  5314. if (data?.status === 200 && !data.responseText.includes('id="publicGroupJoin"')) {
  5315. logStatus.success();
  5316. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5317. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5318. if (groupId) {
  5319. this.#setCache('officialGroup', gameId, groupId);
  5320. }
  5321. return true;
  5322. }
  5323. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5324. return false;
  5325. }
  5326. logStatus.error(`${result}:${statusText}(${status})`);
  5327. return false;
  5328. } catch (error) {
  5329. throwError(error, 'Steam.joinOfficialGroup');
  5330. return false;
  5331. }
  5332. }
  5333. async #leaveOfficialGroup(gameId) {
  5334. try {
  5335. if (this.whiteList.officialGroups.includes(gameId)) {
  5336. scripts_echoLog({
  5337. type: 'whiteList',
  5338. text: 'Steam.leaveOfficialGroup',
  5339. id: gameId
  5340. });
  5341. return true;
  5342. }
  5343. if (this.#ASF) {
  5344. return await this.#ASF.leaveGroup(gameId);
  5345. }
  5346. const groupId = await this.#getOfficialGroupId(gameId);
  5347. if (!groupId) {
  5348. return false;
  5349. }
  5350. const logStatus = scripts_echoLog({
  5351. type: 'leavingSteamOfficialGroup',
  5352. text: gameId
  5353. });
  5354. const {
  5355. result,
  5356. statusText,
  5357. status,
  5358. data
  5359. } = await tools_httpRequest({
  5360. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5361. method: 'POST',
  5362. headers: {
  5363. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5364. },
  5365. data: $.param({
  5366. sessionID: this.#auth.communitySessionID,
  5367. action: 'leaveGroup',
  5368. groupId: groupId
  5369. })
  5370. });
  5371. if (result === 'Success') {
  5372. if (data?.status === 200) {
  5373. const {
  5374. result: resultR,
  5375. statusText: statusTextR,
  5376. status: statusR,
  5377. data: dataR
  5378. } = await tools_httpRequest({
  5379. url: `https://steamcommunity.com/games/${gameId}`,
  5380. method: 'GET',
  5381. headers: {
  5382. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5383. }
  5384. });
  5385. if (resultR === 'Success') {
  5386. if (dataR?.status === 200 && dataR.responseText.includes('id="publicGroupJoin"')) {
  5387. logStatus.success();
  5388. return true;
  5389. }
  5390. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5391. return false;
  5392. }
  5393. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5394. return false;
  5395. }
  5396. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5397. return false;
  5398. }
  5399. logStatus.error(`${result}:${statusText}(${status})`);
  5400. return false;
  5401. } catch (error) {
  5402. throwError(error, 'Steam.leaveOfficialGroup');
  5403. return false;
  5404. }
  5405. }
  5406. async #getOfficialGroupId(gameId) {
  5407. try {
  5408. const logStatus = scripts_echoLog({
  5409. type: 'gettingSteamOfficialGroupId',
  5410. text: gameId
  5411. });
  5412. const groupId = this.#cache.officialGroup[gameId];
  5413. if (groupId) {
  5414. logStatus.success();
  5415. return groupId;
  5416. }
  5417. const {
  5418. result,
  5419. statusText,
  5420. status,
  5421. data
  5422. } = await tools_httpRequest({
  5423. url: `https://steamcommunity.com/games/${gameId}`,
  5424. method: 'GET',
  5425. headers: {
  5426. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5427. }
  5428. });
  5429. if (result === 'Success') {
  5430. if (data?.status === 200) {
  5431. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5432. if (groupId) {
  5433. this.#setCache('officialGroup', gameId, groupId);
  5434. logStatus.success();
  5435. return groupId;
  5436. }
  5437. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5438. return false;
  5439. }
  5440. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5441. return false;
  5442. }
  5443. logStatus.error(`${result}:${statusText}(${status})`);
  5444. return false;
  5445. } catch (error) {
  5446. throwError(error, 'Steam.getGroupID');
  5447. return false;
  5448. }
  5449. }
  5450. async #addToWishlist(gameId) {
  5451. try {
  5452. if (this.#ASF) {
  5453. if (await this.#ASF.addToWishlist(gameId)) {
  5454. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5455. return true;
  5456. }
  5457. return false;
  5458. }
  5459. const logStatus = scripts_echoLog({
  5460. type: 'addingToWishlist',
  5461. text: gameId
  5462. });
  5463. const {
  5464. result,
  5465. data
  5466. } = await tools_httpRequest({
  5467. url: 'https://store.steampowered.com/api/addtowishlist',
  5468. method: 'POST',
  5469. headers: {
  5470. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5471. },
  5472. data: $.param({
  5473. sessionid: this.#auth.storeSessionID,
  5474. appid: gameId
  5475. }),
  5476. dataType: 'json'
  5477. });
  5478. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  5479. logStatus.success();
  5480. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5481. return true;
  5482. }
  5483. const {
  5484. result: resultR,
  5485. statusText: statusTextR,
  5486. status: statusR,
  5487. data: dataR
  5488. } = await tools_httpRequest({
  5489. url: `https://store.steampowered.com/app/${gameId}`,
  5490. method: 'GET'
  5491. });
  5492. if (resultR === 'Success') {
  5493. if (dataR?.status === 200) {
  5494. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  5495. logStatus.warning(i18n('changeAreaNotice'));
  5496. if (!await this.#changeArea()) {
  5497. return false;
  5498. }
  5499. return await this.#addToWishlist(gameId);
  5500. }
  5501. if (dataR.responseText.includes('class="queue_actions_ctn"') && dataR.responseText.includes('class="already_in_library"')) {
  5502. logStatus.success();
  5503. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5504. return true;
  5505. } 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"')) {
  5506. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  5507. return false;
  5508. }
  5509. logStatus.success();
  5510. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5511. return true;
  5512. }
  5513. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5514. return false;
  5515. }
  5516. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5517. return false;
  5518. } catch (error) {
  5519. throwError(error, 'Steam.addToWishlist');
  5520. return false;
  5521. }
  5522. }
  5523. async #removeFromWishlist(gameId) {
  5524. try {
  5525. if (this.whiteList.wishlists.includes(gameId)) {
  5526. scripts_echoLog({
  5527. type: 'whiteList',
  5528. text: 'Steam.removeFromWishlist',
  5529. id: gameId
  5530. });
  5531. return true;
  5532. }
  5533. if (this.#ASF) {
  5534. return await this.#ASF.removeFromWishlist(gameId);
  5535. }
  5536. const logStatus = scripts_echoLog({
  5537. type: 'removingFromWishlist',
  5538. text: gameId
  5539. });
  5540. const {
  5541. result,
  5542. data
  5543. } = await tools_httpRequest({
  5544. url: 'https://store.steampowered.com/api/removefromwishlist',
  5545. method: 'POST',
  5546. headers: {
  5547. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5548. },
  5549. data: $.param({
  5550. sessionid: this.#auth.storeSessionID,
  5551. appid: gameId
  5552. }),
  5553. dataType: 'json'
  5554. });
  5555. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  5556. logStatus.success();
  5557. return true;
  5558. }
  5559. const {
  5560. result: resultR,
  5561. statusText: statusTextR,
  5562. status: statusR,
  5563. data: dataR
  5564. } = await tools_httpRequest({
  5565. url: `https://store.steampowered.com/app/${gameId}`,
  5566. method: 'GET'
  5567. });
  5568. if (resultR === 'Success') {
  5569. if (dataR?.status === 200) {
  5570. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  5571. logStatus.warning(i18n('changeAreaNotice'));
  5572. const result = await this.#changeArea();
  5573. if (!result || result === 'CN' || result === 'skip') {
  5574. return false;
  5575. }
  5576. return await this.#removeFromWishlist(gameId);
  5577. }
  5578. if (dataR.responseText.includes('class="queue_actions_ctn"') && (dataR.responseText.includes('ds_owned_flag ds_flag') || dataR.responseText.includes('add_to_wishlist_area'))) {
  5579. logStatus.success();
  5580. return true;
  5581. }
  5582. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  5583. return false;
  5584. }
  5585. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5586. return false;
  5587. }
  5588. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5589. return false;
  5590. } catch (error) {
  5591. throwError(error, 'Steam.removeFromWishlist');
  5592. return false;
  5593. }
  5594. }
  5595. async #toggleFollowGame(gameId, doTask) {
  5596. try {
  5597. if (!doTask && this.whiteList.follows.includes(gameId)) {
  5598. scripts_echoLog({
  5599. type: 'whiteList',
  5600. text: 'Steam.unfollowGame',
  5601. id: gameId
  5602. });
  5603. return true;
  5604. }
  5605. if (this.#ASF) {
  5606. if (await this.#ASF.toggleFollowGame(gameId, doTask)) {
  5607. if (doTask) {
  5608. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  5609. }
  5610. return true;
  5611. }
  5612. return false;
  5613. }
  5614. const logStatus = scripts_echoLog({
  5615. type: `${doTask ? '' : 'un'}followingGame`,
  5616. text: gameId
  5617. });
  5618. const requestData = {
  5619. sessionid: this.#auth.storeSessionID,
  5620. appid: gameId
  5621. };
  5622. if (!doTask) {
  5623. requestData.unfollow = '1';
  5624. }
  5625. const {
  5626. result,
  5627. data
  5628. } = await tools_httpRequest({
  5629. url: 'https://store.steampowered.com/explore/followgame/',
  5630. method: 'POST',
  5631. headers: {
  5632. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5633. },
  5634. data: $.param(requestData)
  5635. });
  5636. if (result === 'Success' && data?.status === 200 && data.responseText === 'true') {
  5637. logStatus.success();
  5638. return true;
  5639. }
  5640. const followed = await this.#isFollowedGame(gameId);
  5641. if (this.#area === 'CN' && followed === 'areaLocked') {
  5642. logStatus.warning(i18n('changeAreaNotice'));
  5643. if (!await this.#changeArea()) {
  5644. return false;
  5645. }
  5646. return await this.#toggleFollowGame(gameId, doTask);
  5647. }
  5648. if (doTask === followed) {
  5649. logStatus.success();
  5650. if (doTask) {
  5651. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  5652. }
  5653. return true;
  5654. }
  5655. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5656. return false;
  5657. } catch (error) {
  5658. throwError(error, 'Steam.toggleFollowGame');
  5659. return false;
  5660. }
  5661. }
  5662. async #isFollowedGame(gameId) {
  5663. try {
  5664. const {
  5665. result,
  5666. data
  5667. } = await tools_httpRequest({
  5668. url: `https://store.steampowered.com/app/${gameId}`,
  5669. method: 'GET'
  5670. });
  5671. if (result === 'Success') {
  5672. if (data?.status === 200) {
  5673. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  5674. return 'areaLocked';
  5675. }
  5676. if ($(data.responseText.replace(/<img.*?>/g, '')).find('.queue_control_button.queue_btn_follow>.btnv6_blue_hoverfade.btn_medium.queue_btn_active').css('display') !== 'none') {
  5677. return true;
  5678. }
  5679. return false;
  5680. }
  5681. return false;
  5682. }
  5683. return false;
  5684. } catch (error) {
  5685. throwError(error, 'Steam.isFollowedGame');
  5686. return false;
  5687. }
  5688. }
  5689. async #toggleForum(gameId, doTask = true) {
  5690. try {
  5691. if (!doTask && this.whiteList.forums.includes(gameId)) {
  5692. scripts_echoLog({
  5693. type: 'whiteList',
  5694. text: 'Steam.unsubscribeForum',
  5695. id: gameId
  5696. });
  5697. return true;
  5698. }
  5699. const forumId = await this.#getForumId(gameId);
  5700. if (!forumId) {
  5701. return false;
  5702. }
  5703. const logStatus = scripts_echoLog({
  5704. type: `${doTask ? '' : 'un'}subscribingForum`,
  5705. text: gameId
  5706. });
  5707. const [ id, feature ] = forumId.split('_');
  5708. const {
  5709. result,
  5710. statusText,
  5711. status,
  5712. data
  5713. } = await tools_httpRequest({
  5714. url: `https://steamcommunity.com/forum/${id}/General/${doTask ? '' : 'un'}subscribe/${feature || '0'}/`,
  5715. method: 'POST',
  5716. responseType: 'json',
  5717. headers: {
  5718. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5719. },
  5720. data: $.param({
  5721. sessionid: this.#auth.communitySessionID
  5722. })
  5723. });
  5724. if (result === 'Success') {
  5725. if (data?.status === 200 && (data.response?.success === 1 || data.response?.success === 29)) {
  5726. if (doTask) {
  5727. this.tasks.forums = unique([ ...this.tasks.forums, gameId ]);
  5728. }
  5729. logStatus.success();
  5730. return true;
  5731. }
  5732. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5733. return true;
  5734. }
  5735. logStatus.error(`${result}:${statusText}(${status})`);
  5736. return true;
  5737. } catch (error) {
  5738. throwError(error, 'Steam.toggleForum');
  5739. return true;
  5740. }
  5741. }
  5742. async #getForumId(gameId) {
  5743. try {
  5744. const logStatus = scripts_echoLog({
  5745. type: 'gettingForumId',
  5746. text: gameId
  5747. });
  5748. const forumId = this.#cache.forum[gameId];
  5749. if (forumId) {
  5750. logStatus.success();
  5751. return forumId;
  5752. }
  5753. const {
  5754. result,
  5755. statusText,
  5756. status,
  5757. data
  5758. } = await tools_httpRequest({
  5759. url: `https://steamcommunity.com/app/${gameId}/discussions/`,
  5760. method: 'GET'
  5761. });
  5762. if (result === 'Success') {
  5763. if (data?.status === 200) {
  5764. const forumId = data.responseText?.match(/General_([\d]+(_[\d]+)?)/)?.[1];
  5765. if (forumId) {
  5766. this.#setCache('forum', gameId, forumId);
  5767. logStatus.success();
  5768. return forumId;
  5769. }
  5770. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5771. return false;
  5772. }
  5773. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5774. return false;
  5775. }
  5776. logStatus.error(`${result}:${statusText}(${status})`);
  5777. return false;
  5778. } catch (error) {
  5779. throwError(error, 'Steam.getForumId');
  5780. return false;
  5781. }
  5782. }
  5783. async #toggleFavoriteWorkshop(id, doTask = true) {
  5784. try {
  5785. if (!doTask && this.whiteList.workshops.includes(id)) {
  5786. scripts_echoLog({
  5787. type: 'whiteList',
  5788. text: 'Steam.unfavoriteWorkshop',
  5789. id: id
  5790. });
  5791. return true;
  5792. }
  5793. const appid = await this.#getWorkshopAppId(id);
  5794. if (!appid) {
  5795. return false;
  5796. }
  5797. const logStatus = scripts_echoLog({
  5798. type: doTask ? 'favoritingWorkshop' : 'unfavoritingWorkshop',
  5799. text: id
  5800. });
  5801. const {
  5802. result,
  5803. statusText,
  5804. status,
  5805. data
  5806. } = await tools_httpRequest({
  5807. url: `https://steamcommunity.com/sharedfiles/${doTask ? '' : 'un'}favorite`,
  5808. method: 'POST',
  5809. headers: {
  5810. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5811. },
  5812. data: $.param({
  5813. id: id,
  5814. appid: appid,
  5815. sessionid: this.#auth.communitySessionID
  5816. })
  5817. });
  5818. if (result === 'Success') {
  5819. if (data?.status === 200 && !data.responseText) {
  5820. if (doTask) {
  5821. this.tasks.workshops = unique([ ...this.tasks.workshops, id ]);
  5822. }
  5823. logStatus.success();
  5824. return true;
  5825. }
  5826. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5827. return false;
  5828. }
  5829. logStatus.error(`${result}:${statusText}(${status})`);
  5830. return false;
  5831. } catch (error) {
  5832. throwError(error, 'Steam.toggleFavoriteWorkshop');
  5833. return false;
  5834. }
  5835. }
  5836. async #getWorkshopAppId(id) {
  5837. try {
  5838. const logStatus = scripts_echoLog({
  5839. type: 'gettingWorkshopAppId',
  5840. text: id
  5841. });
  5842. const appId = this.#cache.workshop[id];
  5843. if (appId) {
  5844. logStatus.success();
  5845. return appId;
  5846. }
  5847. const {
  5848. result,
  5849. statusText,
  5850. status,
  5851. data
  5852. } = await tools_httpRequest({
  5853. url: `https://steamcommunity.com/sharedfiles/filedetails/?id=${id}`,
  5854. method: 'GET'
  5855. });
  5856. if (result === 'Success') {
  5857. if (data?.status === 200) {
  5858. const appId = data.responseText.match(/<input type="hidden" name="appid" value="([\d]+?)" \/>/)?.[1];
  5859. if (appId) {
  5860. this.#setCache('workshop', id, appId);
  5861. logStatus.success();
  5862. return appId;
  5863. }
  5864. logStatus.error('Error: getWorkshopAppId failed');
  5865. return false;
  5866. }
  5867. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5868. return false;
  5869. }
  5870. logStatus.error(`${result}:${statusText}(${status})`);
  5871. return false;
  5872. } catch (error) {
  5873. throwError(error, 'Steam.getWorkshopAppId');
  5874. return false;
  5875. }
  5876. }
  5877. async #voteUpWorkshop(id) {
  5878. try {
  5879. const logStatus = scripts_echoLog({
  5880. type: 'votingUpWorkshop',
  5881. text: id
  5882. });
  5883. const {
  5884. result,
  5885. statusText,
  5886. status,
  5887. data
  5888. } = await tools_httpRequest({
  5889. url: 'https://steamcommunity.com/sharedfiles/voteup',
  5890. method: 'POST',
  5891. responseType: 'json',
  5892. headers: {
  5893. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5894. },
  5895. data: $.param({
  5896. id: id,
  5897. sessionid: this.#auth.communitySessionID
  5898. })
  5899. });
  5900. if (result === 'Success') {
  5901. if (data?.status === 200 && data.response?.success === 1) {
  5902. logStatus.success();
  5903. return true;
  5904. }
  5905. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5906. return true;
  5907. }
  5908. logStatus.error(`${result}:${statusText}(${status})`);
  5909. return true;
  5910. } catch (error) {
  5911. throwError(error, 'Steam.voteupWorkshop');
  5912. return true;
  5913. }
  5914. }
  5915. async #toggleCurator(curatorId, doTask = true) {
  5916. try {
  5917. if (!doTask && this.whiteList.curators.includes(curatorId)) {
  5918. scripts_echoLog({
  5919. type: 'whiteList',
  5920. text: 'Steam.unfollowCurator',
  5921. id: curatorId
  5922. });
  5923. return true;
  5924. }
  5925. if (this.#ASF) {
  5926. return await this.#ASF.toggleCurator(curatorId, doTask);
  5927. }
  5928. const logStatus = scripts_echoLog({
  5929. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  5930. text: curatorId
  5931. });
  5932. const {
  5933. result,
  5934. statusText,
  5935. status,
  5936. data
  5937. } = await tools_httpRequest({
  5938. url: 'https://store.steampowered.com/curators/ajaxfollow',
  5939. method: 'POST',
  5940. headers: {
  5941. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5942. },
  5943. data: $.param({
  5944. clanid: curatorId,
  5945. sessionid: this.#auth.storeSessionID,
  5946. follow: doTask
  5947. }),
  5948. dataType: 'json'
  5949. });
  5950. if (result === 'Success') {
  5951. if (data?.status === 200 && data.response?.success?.success === 1) {
  5952. logStatus.success();
  5953. return true;
  5954. }
  5955. logStatus.error(`Error:${data?.statusText}(${data?.response?.success}` || `${data?.status})`);
  5956. return false;
  5957. }
  5958. logStatus.error(`${result}:${statusText}(${status})`);
  5959. return false;
  5960. } catch (error) {
  5961. throwError(error, 'Steam.toggleCurator');
  5962. return false;
  5963. }
  5964. }
  5965. async getCuratorId(path, name) {
  5966. try {
  5967. const logStatus = scripts_echoLog({
  5968. type: 'gettingCuratorId',
  5969. text: `${path}/${name}`
  5970. });
  5971. const curatorId = this.#cache.curator[`${path}/${name}`];
  5972. if (curatorId) {
  5973. logStatus.success();
  5974. return curatorId;
  5975. }
  5976. const {
  5977. result,
  5978. statusText,
  5979. status,
  5980. data
  5981. } = await tools_httpRequest({
  5982. url: `https://store.steampowered.com/${path}/${name}`,
  5983. method: 'GET',
  5984. headers: {
  5985. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5986. }
  5987. });
  5988. if (result === 'Success') {
  5989. if (data?.status === 200) {
  5990. const curatorId = data.responseText.match(/g_pagingData.*?"clanid":([\d]+)/)?.[1];
  5991. if (curatorId) {
  5992. this.#setCache('curator', `${path}/${name}`, curatorId);
  5993. logStatus.success();
  5994. return curatorId;
  5995. }
  5996. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5997. return false;
  5998. }
  5999. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6000. return false;
  6001. }
  6002. logStatus.error(`${result}:${statusText}(${status})`);
  6003. return false;
  6004. } catch (error) {
  6005. throwError(error, 'Steam.getCuratorID');
  6006. return false;
  6007. }
  6008. }
  6009. async #toggleCuratorLike(link, doTask = true) {
  6010. try {
  6011. const [ path, name ] = link.split('/');
  6012. if (!(path && name)) {
  6013. scripts_echoLog({
  6014. text: i18n('errorLink', link)
  6015. });
  6016. return false;
  6017. }
  6018. const curatorId = await this.getCuratorId(path, name);
  6019. if (curatorId) {
  6020. return await this.#toggleCurator(curatorId, doTask);
  6021. }
  6022. return false;
  6023. } catch (error) {
  6024. throwError(error, 'Steam.toggleCuratorLike');
  6025. return false;
  6026. }
  6027. }
  6028. async #getAnnouncementParams(appId, viewId) {
  6029. try {
  6030. const logStatus = scripts_echoLog({
  6031. type: 'gettingAnnouncementParams',
  6032. text: appId,
  6033. id: viewId
  6034. });
  6035. const {
  6036. result,
  6037. statusText,
  6038. status,
  6039. data
  6040. } = await tools_httpRequest({
  6041. 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`,
  6042. method: 'GET',
  6043. responseType: 'json',
  6044. headers: {
  6045. Host: 'store.steampowered.com',
  6046. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6047. }
  6048. });
  6049. if (result === 'Success') {
  6050. if (data?.status === 200 && data?.response?.success === 1) {
  6051. const {
  6052. clanid,
  6053. gid
  6054. } = data.response.event?.announcement_body || {};
  6055. if (clanid) {
  6056. logStatus.success();
  6057. return {
  6058. clanId: clanid,
  6059. gid: gid
  6060. };
  6061. }
  6062. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6063. return {};
  6064. }
  6065. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6066. return {};
  6067. }
  6068. logStatus.error(`${result}:${statusText}(${status})`);
  6069. return {};
  6070. } catch (error) {
  6071. throwError(error, 'Steam.likeAnnouncement');
  6072. return {};
  6073. }
  6074. }
  6075. async #likeAnnouncement(id) {
  6076. try {
  6077. const [ appId, viewId ] = id.split('/');
  6078. if (!(appId && viewId)) {
  6079. scripts_echoLog({}).error(`${i18n('missParams')}(id)`);
  6080. return false;
  6081. }
  6082. const {
  6083. clanId,
  6084. gid
  6085. } = await this.#getAnnouncementParams(appId, viewId);
  6086. if (!clanId) {
  6087. return false;
  6088. }
  6089. const logStatus = scripts_echoLog({
  6090. type: 'likingAnnouncement',
  6091. text: appId,
  6092. id: viewId
  6093. });
  6094. const {
  6095. result,
  6096. statusText,
  6097. status,
  6098. data
  6099. } = await tools_httpRequest({
  6100. url: `https://store.steampowered.com/updated/ajaxrateupdate/${gid || viewId}`,
  6101. method: 'POST',
  6102. headers: {
  6103. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6104. Host: 'store.steampowered.com',
  6105. Origin: 'https://store.steampowered.com',
  6106. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6107. },
  6108. data: $.param({
  6109. sessionid: this.#auth.storeSessionID,
  6110. voteup: 1,
  6111. clanid: clanId,
  6112. ajax: 1
  6113. }),
  6114. dataType: 'json'
  6115. });
  6116. if (result === 'Success') {
  6117. if (data?.status === 200 && data.response.success === 1) {
  6118. logStatus.success();
  6119. return true;
  6120. }
  6121. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6122. return false;
  6123. }
  6124. logStatus.error(`${result}:${statusText}(${status})`);
  6125. return false;
  6126. } catch (error) {
  6127. throwError(error, 'Steam.likeAnnouncement');
  6128. return false;
  6129. }
  6130. }
  6131. async #appid2subid(id) {
  6132. try {
  6133. const logStatus = scripts_echoLog({
  6134. type: 'gettingSubid',
  6135. text: id
  6136. });
  6137. const {
  6138. result,
  6139. statusText,
  6140. status,
  6141. data
  6142. } = await tools_httpRequest({
  6143. url: `https://store.steampowered.com/app/${id}`,
  6144. method: 'GET',
  6145. headers: {
  6146. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6147. }
  6148. });
  6149. if (result === 'Success') {
  6150. if (data?.status === 200) {
  6151. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6152. logStatus.success(i18n('owned'));
  6153. return false;
  6154. }
  6155. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6156. logStatus.warning(i18n('changeAreaNotice'));
  6157. const result = await this.#changeArea();
  6158. if (!result || result === 'CN' || result === 'skip') {
  6159. return false;
  6160. }
  6161. return await this.#appid2subid(id);
  6162. }
  6163. let subid = data.responseText.match(/name="subid" value="([\d]+?)"/)?.[1];
  6164. if (subid) {
  6165. logStatus.success();
  6166. return subid;
  6167. }
  6168. subid = data.responseText.match(/AddFreeLicense\(\s*(\d+)/)?.[1];
  6169. if (subid) {
  6170. logStatus.success();
  6171. return subid;
  6172. }
  6173. logStatus.error(`Error:${i18n('noSubid')}`);
  6174. return false;
  6175. }
  6176. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6177. return false;
  6178. }
  6179. logStatus.error(`${result}:${statusText}(${status})`);
  6180. return false;
  6181. } catch (error) {
  6182. throwError(error, 'Steam.appid2subid');
  6183. return false;
  6184. }
  6185. }
  6186. async #getLicenses() {
  6187. try {
  6188. const logStatus = scripts_echoLog({
  6189. text: i18n('gettingLicenses')
  6190. });
  6191. const {
  6192. result,
  6193. statusText,
  6194. status,
  6195. data
  6196. } = await tools_httpRequest({
  6197. url: `https://store.steampowered.com/dynamicstore/userdata/?t=${new Date().getTime()}`,
  6198. method: 'GET',
  6199. responseType: 'json'
  6200. });
  6201. if (result === 'Success') {
  6202. if (data?.status === 200) {
  6203. logStatus.success();
  6204. return data.response?.rgOwnedPackages;
  6205. }
  6206. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6207. return false;
  6208. }
  6209. logStatus.error(`${result}:${statusText}(${status})`);
  6210. return false;
  6211. } catch (error) {
  6212. throwError(error, 'Steam.getLicenses');
  6213. return false;
  6214. }
  6215. }
  6216. async #addLicense(id) {
  6217. try {
  6218. if (this.#ASF) {
  6219. return await this.#ASF.addLicense(id);
  6220. }
  6221. const [ type, ids ] = id.split('-');
  6222. if (type === 'appid') {
  6223. const subid = await this.#appid2subid(ids);
  6224. if (!subid) {
  6225. return false;
  6226. }
  6227. const logStatus = scripts_echoLog({
  6228. type: 'addingFreeLicense',
  6229. text: ids
  6230. });
  6231. if (!await this.#addFreeLicense(subid, logStatus)) {
  6232. return false;
  6233. }
  6234. const {
  6235. result,
  6236. statusText,
  6237. status,
  6238. data
  6239. } = await tools_httpRequest({
  6240. url: `https://store.steampowered.com/app/${ids}`,
  6241. method: 'GET'
  6242. });
  6243. if (result === 'Success') {
  6244. if (data?.status === 200) {
  6245. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6246. logStatus.success();
  6247. return true;
  6248. }
  6249. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6250. return false;
  6251. }
  6252. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6253. return false;
  6254. }
  6255. logStatus.error(`${result}:${statusText}(${status})`);
  6256. return false;
  6257. } else if (type === 'subid') {
  6258. if (this.#area === 'CN') {
  6259. scripts_echoLog({}).success(i18n('tryChangeAreaNotice'));
  6260. await this.#changeArea();
  6261. }
  6262. const logStatusArr = {};
  6263. const idsArr = ids.split(',');
  6264. for (const subid of idsArr) {
  6265. const logStatus = scripts_echoLog({
  6266. type: 'addingFreeLicenseSubid',
  6267. text: subid
  6268. });
  6269. if (!await this.#addFreeLicense(subid, logStatus)) {
  6270. return false;
  6271. }
  6272. logStatusArr[subid] = logStatus;
  6273. }
  6274. const licenses = await this.#getLicenses();
  6275. if (!licenses) {
  6276. return false;
  6277. }
  6278. for (const subid of idsArr) {
  6279. if (licenses.includes(parseInt(subid, 10))) {
  6280. logStatusArr[subid].success();
  6281. } else {
  6282. logStatusArr[subid].error();
  6283. }
  6284. }
  6285. return true;
  6286. }
  6287. return false;
  6288. } catch (error) {
  6289. throwError(error, 'Steam.addLicense');
  6290. return false;
  6291. }
  6292. }
  6293. async #addFreeLicense(id, logStatusPre) {
  6294. try {
  6295. const logStatus = logStatusPre || scripts_echoLog({
  6296. type: 'addingFreeLicenseSubid',
  6297. text: id
  6298. });
  6299. const {
  6300. result,
  6301. statusText,
  6302. status,
  6303. data
  6304. } = await tools_httpRequest({
  6305. url: `https://store.steampowered.com/freelicense/addfreelicense/${id}`,
  6306. method: 'POST',
  6307. headers: {
  6308. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6309. Host: 'store.steampowered.com',
  6310. Origin: 'https://store.steampowered.com',
  6311. Referer: 'https://store.steampowered.com/account/licenses/'
  6312. },
  6313. data: $.param({
  6314. ajax: true,
  6315. sessionid: this.#auth.storeSessionID
  6316. }),
  6317. dataType: 'json'
  6318. });
  6319. if (result === 'Success') {
  6320. if (data?.status === 200) {
  6321. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6322. logStatus.warning(i18n('changeAreaNotice'));
  6323. const result = await this.#changeArea();
  6324. if (!result || [ 'CN', 'skip' ].includes(result)) {
  6325. return false;
  6326. }
  6327. return await this.#addFreeLicense(id);
  6328. }
  6329. logStatus.success();
  6330. return true;
  6331. }
  6332. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6333. return false;
  6334. }
  6335. logStatus.error(`${result}:${statusText}(${status})`);
  6336. return false;
  6337. } catch (error) {
  6338. throwError(error, 'Steam.addFreeLicense');
  6339. return false;
  6340. }
  6341. }
  6342. async #requestPlayTestAccess(id) {
  6343. try {
  6344. if (this.#ASF) {
  6345. return await this.#ASF.requestPlayTestAccess(id);
  6346. }
  6347. const logStatus = scripts_echoLog({
  6348. type: 'requestingPlayTestAccess',
  6349. text: id
  6350. });
  6351. const {
  6352. result,
  6353. statusText,
  6354. status,
  6355. data
  6356. } = await tools_httpRequest({
  6357. url: `https://store.steampowered.com/ajaxrequestplaytestaccess/${id}`,
  6358. method: 'POST',
  6359. headers: {
  6360. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6361. Host: 'store.steampowered.com',
  6362. Origin: 'https://store.steampowered.com',
  6363. Referer: `https://store.steampowered.com/app/${id}`
  6364. },
  6365. data: $.param({
  6366. sessionid: this.#auth.storeSessionID
  6367. }),
  6368. dataType: 'json'
  6369. });
  6370. if (result === 'Success') {
  6371. if (data?.status === 200 && data?.response?.success === 1) {
  6372. logStatus.success();
  6373. return true;
  6374. }
  6375. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6376. return false;
  6377. }
  6378. logStatus.error(`${result}:${statusText}(${status})`);
  6379. return false;
  6380. } catch (error) {
  6381. throwError(error, 'Steam.requestPlayTestAccess');
  6382. return false;
  6383. }
  6384. }
  6385. async toggle({
  6386. doTask = true,
  6387. groupLinks = [],
  6388. officialGroupLinks = [],
  6389. wishlistLinks = [],
  6390. followLinks = [],
  6391. forumLinks = [],
  6392. workshopLinks = [],
  6393. workshopVoteLinks = [],
  6394. curatorLinks = [],
  6395. curatorLikeLinks = [],
  6396. announcementLinks = [],
  6397. licenseLinks = [],
  6398. playtestLinks = []
  6399. }) {
  6400. try {
  6401. if ([ ...groupLinks, ...officialGroupLinks, ...forumLinks, ...workshopLinks, ...workshopVoteLinks ].length > 0 && !this.#communityInitialized) {
  6402. scripts_echoLog({
  6403. text: i18n('needInit')
  6404. });
  6405. return false;
  6406. }
  6407. if ([ ...wishlistLinks, ...followLinks, ...curatorLinks, ...curatorLikeLinks, ...announcementLinks, ...licenseLinks, ...playtestLinks ].length > 0 && !this.#storeInitialized) {
  6408. scripts_echoLog({
  6409. text: i18n('needInit')
  6410. });
  6411. return false;
  6412. }
  6413. const prom = [];
  6414. if (doTask && !globalOptions.doTask.steam.groups || !doTask && !globalOptions.undoTask.steam.groups) {
  6415. scripts_echoLog({
  6416. type: 'globalOptionsSkip',
  6417. text: 'steam.groups'
  6418. });
  6419. } else {
  6420. const realGroups = this.getRealParams('groups', groupLinks, doTask, link => link.match(/groups\/(.+)\/?/)?.[1]);
  6421. if (realGroups.length > 0) {
  6422. for (const group of realGroups) {
  6423. if (doTask) {
  6424. prom.push(this.#joinGroup(group));
  6425. } else {
  6426. prom.push(this.#leaveGroup(group));
  6427. }
  6428. await delay(1e3);
  6429. }
  6430. }
  6431. }
  6432. if (doTask && !globalOptions.doTask.steam.officialGroups || !doTask && !globalOptions.undoTask.steam.officialGroups) {
  6433. scripts_echoLog({
  6434. type: 'globalOptionsSkip',
  6435. text: 'steam.officialGroups'
  6436. });
  6437. } else {
  6438. const realOfficialGroups = this.getRealParams('officialGroups', officialGroupLinks, doTask, link => link.match(/games\/(.+)\/?/)?.[1]);
  6439. if (realOfficialGroups.length > 0) {
  6440. for (const officialGroup of realOfficialGroups) {
  6441. if (doTask) {
  6442. prom.push(this.#joinOfficialGroup(officialGroup));
  6443. } else {
  6444. prom.push(this.#leaveOfficialGroup(officialGroup));
  6445. }
  6446. await delay(1e3);
  6447. }
  6448. }
  6449. }
  6450. if (doTask && !globalOptions.doTask.steam.wishlists || !doTask && !globalOptions.undoTask.steam.wishlists) {
  6451. scripts_echoLog({
  6452. type: 'globalOptionsSkip',
  6453. text: 'steam.wishlists'
  6454. });
  6455. } else {
  6456. const realWishlists = this.getRealParams('wishlists', wishlistLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6457. if (realWishlists.length > 0) {
  6458. for (const game of realWishlists) {
  6459. if (doTask) {
  6460. prom.push(this.#addToWishlist(game));
  6461. } else {
  6462. prom.push(this.#removeFromWishlist(game));
  6463. }
  6464. await delay(1e3);
  6465. }
  6466. }
  6467. }
  6468. if (doTask && !globalOptions.doTask.steam.follows || !doTask && !globalOptions.undoTask.steam.follows) {
  6469. scripts_echoLog({
  6470. type: 'globalOptionsSkip',
  6471. text: 'steam.follows'
  6472. });
  6473. } else {
  6474. const realFollows = this.getRealParams('follows', followLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6475. if (realFollows.length > 0) {
  6476. for (const game of realFollows) {
  6477. prom.push(this.#toggleFollowGame(game, doTask));
  6478. await delay(1e3);
  6479. }
  6480. }
  6481. }
  6482. if (doTask && !globalOptions.doTask.steam.forums || !doTask && !globalOptions.undoTask.steam.forums) {
  6483. scripts_echoLog({
  6484. type: 'globalOptionsSkip',
  6485. text: 'steam.forums'
  6486. });
  6487. } else {
  6488. const realForums = this.getRealParams('forums', forumLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6489. if (realForums.length > 0) {
  6490. for (const forum of realForums) {
  6491. prom.push(this.#toggleForum(forum, doTask));
  6492. await delay(1e3);
  6493. }
  6494. }
  6495. }
  6496. if (doTask && !globalOptions.doTask.steam.workshops || !doTask && !globalOptions.undoTask.steam.workshops) {
  6497. scripts_echoLog({
  6498. type: 'globalOptionsSkip',
  6499. text: 'steam.workshops'
  6500. });
  6501. } else {
  6502. const realWorkshops = this.getRealParams('workshops', workshopLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  6503. if (realWorkshops.length > 0) {
  6504. for (const workshop of realWorkshops) {
  6505. prom.push(this.#toggleFavoriteWorkshop(workshop, doTask));
  6506. await delay(1e3);
  6507. }
  6508. }
  6509. }
  6510. if (doTask && !globalOptions.doTask.steam.workshopVotes) {
  6511. scripts_echoLog({
  6512. type: 'globalOptionsSkip',
  6513. text: 'steam.workshopVotes'
  6514. });
  6515. } else {
  6516. const realworkshopVotes = this.getRealParams('workshopVotes', workshopVoteLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  6517. if (doTask && realworkshopVotes.length > 0) {
  6518. for (const workshop of realworkshopVotes) {
  6519. prom.push(this.#voteUpWorkshop(workshop));
  6520. await delay(1e3);
  6521. }
  6522. }
  6523. }
  6524. if (doTask && !globalOptions.doTask.steam.curators || !doTask && !globalOptions.undoTask.steam.curators) {
  6525. scripts_echoLog({
  6526. type: 'globalOptionsSkip',
  6527. text: 'steam.curators'
  6528. });
  6529. } else {
  6530. const realCurators = this.getRealParams('curators', curatorLinks, doTask, link => link.match(/curator\/([\d]+)/)?.[1]);
  6531. const realCuratorLikes = this.getRealParams('curatorLikes', curatorLikeLinks, doTask, link => link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3).join('/'));
  6532. if (realCurators.length > 0) {
  6533. for (const curator of realCurators) {
  6534. prom.push(this.#toggleCurator(curator, doTask));
  6535. await delay(1e3);
  6536. }
  6537. }
  6538. if (realCuratorLikes.length > 0) {
  6539. for (const curatorLike of realCuratorLikes) {
  6540. prom.push(this.#toggleCuratorLike(curatorLike, doTask));
  6541. await delay(1e3);
  6542. }
  6543. }
  6544. }
  6545. if (doTask && !globalOptions.doTask.steam.announcements) {
  6546. scripts_echoLog({
  6547. type: 'globalOptionsSkip',
  6548. text: 'steam.announcements'
  6549. });
  6550. } else {
  6551. const realAnnouncements = this.getRealParams('announcements', announcementLinks, doTask, link => {
  6552. if (link.includes('store.steampowered.com')) {
  6553. return link.match(/store\.steampowered\.com\/news\/app\/([\d]+)\/view\/([\d]+)/)?.slice(1, 3).join('/');
  6554. }
  6555. return link.match(/steamcommunity\.com\/games\/([\d]+)\/announcements\/detail\/([\d]+)/)?.slice(1, 3).join('/');
  6556. });
  6557. if (doTask && realAnnouncements.length > 0) {
  6558. for (const id of realAnnouncements) {
  6559. prom.push(this.#likeAnnouncement(id));
  6560. await delay(1e3);
  6561. }
  6562. }
  6563. }
  6564. if (doTask && !globalOptions.doTask.steam.licenses) {
  6565. scripts_echoLog({
  6566. type: 'globalOptionsSkip',
  6567. text: 'steam.licenses'
  6568. });
  6569. } else if (doTask && globalOptions.doTask.steam.licenses && licenseLinks.length > 0) {
  6570. for (const ids of licenseLinks) {
  6571. const [ type, idsStr ] = ids.split('-');
  6572. const idsArr = idsStr.split(',');
  6573. for (const id of idsArr) {
  6574. prom.push(this.#addLicense(`${type}-${id}`));
  6575. await delay(1e3);
  6576. }
  6577. }
  6578. }
  6579. if (doTask && !globalOptions.doTask.steam.playtests) {
  6580. scripts_echoLog({
  6581. type: 'globalOptionsSkip',
  6582. text: 'steam.playtests'
  6583. });
  6584. } else {
  6585. const realPlaytests = this.getRealParams('playtests', playtestLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6586. if (doTask && globalOptions.doTask.steam.playtests && realPlaytests.length > 0) {
  6587. for (const id of realPlaytests) {
  6588. prom.push(this.#requestPlayTestAccess(id));
  6589. await delay(1e3);
  6590. }
  6591. }
  6592. }
  6593. return Promise.all(prom).then(async () => {
  6594. if (this.#oldArea && this.#area !== this.#oldArea) {
  6595. scripts_echoLog({}).warning(i18n('steamFinishNotice') + this.#oldArea);
  6596. await this.#changeArea(this.#oldArea);
  6597. }
  6598. return true;
  6599. });
  6600. } catch (error) {
  6601. throwError(error, 'Steam.toggle');
  6602. return false;
  6603. }
  6604. }
  6605. #setCache(type, name, id) {
  6606. try {
  6607. this.#cache[type][name] = id;
  6608. GM_setValue('steamCache', this.#cache);
  6609. } catch (error) {
  6610. throwError(error, 'Steam.setCache');
  6611. }
  6612. }
  6613. }
  6614. const social_Steam = Steam;
  6615. class Website {
  6616. undoneTasks;
  6617. socialTasks;
  6618. giveawayId;
  6619. socialInitialized = {
  6620. discord: false,
  6621. instagram: false,
  6622. reddit: false,
  6623. twitch: false,
  6624. twitter: false,
  6625. vk: false,
  6626. youtube: false,
  6627. steamStore: false,
  6628. steamCommunity: false
  6629. };
  6630. initialized = false;
  6631. steamTaskType = {
  6632. steamStore: false,
  6633. steamCommunity: false
  6634. };
  6635. social = {};
  6636. async #bind(name, init) {
  6637. try {
  6638. return {
  6639. name: name,
  6640. result: await init
  6641. };
  6642. } catch (error) {
  6643. throwError(error, 'Website.bind');
  6644. return {
  6645. name: name,
  6646. result: false
  6647. };
  6648. }
  6649. }
  6650. async initSocial(action) {
  6651. try {
  6652. const pro = [];
  6653. const tasks = action === 'do' ? this.undoneTasks : this.socialTasks;
  6654. if (tasks.discord) {
  6655. const hasDiscord = Object.values(tasks.discord).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6656. if (hasDiscord && (!this.socialInitialized.discord || !this.social.discord)) {
  6657. this.social.discord = new social_Discord();
  6658. pro.push(this.#bind('discord', this.social.discord.init(action)));
  6659. }
  6660. }
  6661. if (tasks.instagram) {
  6662. const hasInstagram = Object.values(tasks.instagram).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6663. if (hasInstagram && (!this.socialInitialized.instagram || !this.social.instagram)) {
  6664. this.social.instagram = new social_Instagram();
  6665. pro.push(this.#bind('instagram', this.social.instagram.init()));
  6666. }
  6667. }
  6668. if (tasks.reddit) {
  6669. const hasReddit = Object.values(tasks.reddit).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6670. if (hasReddit && (!this.socialInitialized.reddit || !this.social.reddit)) {
  6671. this.social.reddit = new social_Reddit();
  6672. pro.push(this.#bind('reddit', this.social.reddit.init()));
  6673. }
  6674. }
  6675. if (tasks.twitch) {
  6676. const hasTwitch = Object.values(tasks.twitch).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6677. if (hasTwitch && (!this.socialInitialized.twitch || !this.social.twitch)) {
  6678. this.social.twitch = new social_Twitch();
  6679. pro.push(this.#bind('twitch', this.social.twitch.init()));
  6680. }
  6681. }
  6682. if (tasks.twitter) {
  6683. const hasTwitter = Object.values(tasks.twitter).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6684. if (hasTwitter && (!this.socialInitialized.twitter || !this.social.twitter)) {
  6685. this.social.twitter = new social_Twitter();
  6686. pro.push(this.#bind('twitter', this.social.twitter.init()));
  6687. }
  6688. }
  6689. if (tasks.vk) {
  6690. const hasVk = Object.values(tasks.vk).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6691. if (hasVk && (!this.socialInitialized.vk || !this.social.vk)) {
  6692. this.social.vk = new social_Vk();
  6693. pro.push(this.#bind('vk', this.social.vk.init()));
  6694. }
  6695. }
  6696. if (tasks.youtube) {
  6697. const hasYoutube = Object.values(tasks.youtube).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6698. if (hasYoutube && (!this.socialInitialized.youtube || !this.social.youtube)) {
  6699. this.social.youtube = new Youtube();
  6700. pro.push(this.#bind('youtube', this.social.youtube.init()));
  6701. }
  6702. }
  6703. if (tasks.steam) {
  6704. const steamLength = Object.values(tasks.steam).reduce((total, arr) => [ ...total, ...arr ]).length;
  6705. if (steamLength > 0) {
  6706. if (!this.social.steam) {
  6707. this.social.steam = new social_Steam();
  6708. }
  6709. 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);
  6710. if (steamLength - steamCommunityLength > 0) {
  6711. this.steamTaskType.steamStore = true;
  6712. if (!this.socialInitialized.steamStore) {
  6713. pro.push(this.#bind('steamStore', this.social.steam.init('store')));
  6714. }
  6715. }
  6716. if (steamCommunityLength > 0) {
  6717. if (!this.socialInitialized.steamCommunity) {
  6718. this.steamTaskType.steamCommunity = true;
  6719. pro.push(this.#bind('steamCommunity', this.social.steam.init('community')));
  6720. }
  6721. }
  6722. }
  6723. }
  6724. if (tasks.links && tasks.links.length > 0) {
  6725. this.social.visitLink = visitLink;
  6726. }
  6727. return await Promise.all(pro).then(result => {
  6728. let checked = true;
  6729. for (const data of result) {
  6730. if (data.result) {
  6731. this.socialInitialized[data.name] = data.result;
  6732. } else {
  6733. checked = false;
  6734. }
  6735. }
  6736. return checked;
  6737. });
  6738. } catch (error) {
  6739. throwError(error, 'Website.initSocial');
  6740. return false;
  6741. }
  6742. }
  6743. uniqueTasks(allTasks) {
  6744. try {
  6745. const result = {};
  6746. for (const [ social, types ] of Object.entries(allTasks)) {
  6747. result[social] = {};
  6748. for (const [ type, tasks ] of Object.entries(types)) {
  6749. result[social][type] = unique(tasks);
  6750. }
  6751. }
  6752. return result;
  6753. } catch (error) {
  6754. throwError(error, 'Website.uniqueTasks');
  6755. return allTasks;
  6756. }
  6757. }
  6758. async toggleTask(action) {
  6759. try {
  6760. if (!this.initialized && !this.init()) {
  6761. return false;
  6762. }
  6763. if (!await this.classifyTask(action)) {
  6764. return false;
  6765. }
  6766. await this.initSocial(action);
  6767. const pro = [];
  6768. const doTask = action === 'do';
  6769. const tasks = doTask ? this.undoneTasks : this.socialTasks;
  6770. if (this.socialInitialized.discord === true && this.social.discord) {
  6771. pro.push(this.social.discord.toggle({
  6772. doTask: doTask,
  6773. ...tasks.discord
  6774. }));
  6775. }
  6776. if (this.socialInitialized.instagram === true && this.social.instagram) {
  6777. pro.push(this.social.instagram.toggle({
  6778. doTask: doTask,
  6779. ...tasks.instagram
  6780. }));
  6781. }
  6782. if (this.socialInitialized.reddit === true && this.social.reddit) {
  6783. pro.push(this.social.reddit.toggle({
  6784. doTask: doTask,
  6785. ...tasks.reddit
  6786. }));
  6787. }
  6788. if (this.socialInitialized.twitch === true && this.social.twitch) {
  6789. pro.push(this.social.twitch.toggle({
  6790. doTask: doTask,
  6791. ...tasks.twitch
  6792. }));
  6793. }
  6794. if (this.socialInitialized.twitter === true && this.social.twitter) {
  6795. pro.push(this.social.twitter.toggle({
  6796. doTask: doTask,
  6797. ...tasks.twitter
  6798. }));
  6799. }
  6800. if (this.socialInitialized.vk === true && this.social.vk) {
  6801. pro.push(this.social.vk.toggle({
  6802. doTask: doTask,
  6803. ...tasks.vk
  6804. }));
  6805. }
  6806. if (this.socialInitialized.youtube === true && this.social.youtube) {
  6807. pro.push(this.social.youtube.toggle({
  6808. doTask: doTask,
  6809. ...tasks.youtube
  6810. }));
  6811. }
  6812. if ((this.steamTaskType.steamCommunity ? this.socialInitialized.steamCommunity === true : true) && (this.steamTaskType.steamStore ? this.socialInitialized.steamStore === true : true) && this.social.steam) {
  6813. pro.push(this.social.steam.toggle({
  6814. doTask: doTask,
  6815. ...tasks.steam
  6816. }));
  6817. }
  6818. if (this.social.visitLink && tasks.links && doTask) {
  6819. for (const link of tasks.links) {
  6820. pro.push(this.social.visitLink(link));
  6821. }
  6822. }
  6823. if (doTask && tasks.extra && this.extraDoTask) {
  6824. const hasExtra = Object.values(tasks.extra).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6825. if (hasExtra) {
  6826. pro.push(this.extraDoTask(tasks.extra));
  6827. }
  6828. }
  6829. await Promise.all(pro);
  6830. scripts_echoLog({}).success(i18n('allTasksComplete'));
  6831. return true;
  6832. } catch (error) {
  6833. throwError(error, 'Website.toggleTask');
  6834. return false;
  6835. }
  6836. }
  6837. async doTask() {
  6838. try {
  6839. return await this.toggleTask('do');
  6840. } catch (error) {
  6841. throwError(error, 'Website.doTask');
  6842. return false;
  6843. }
  6844. }
  6845. async undoTask() {
  6846. try {
  6847. return await this.toggleTask('undo');
  6848. } catch (error) {
  6849. throwError(error, 'Website.undoTask');
  6850. return false;
  6851. }
  6852. }
  6853. }
  6854. const website_Website = Website;
  6855. const defaultTasksTemplate = {
  6856. steam: {
  6857. groupLinks: [],
  6858. wishlistLinks: [],
  6859. curatorLinks: [],
  6860. followLinks: []
  6861. },
  6862. vk: {
  6863. nameLinks: []
  6864. }
  6865. };
  6866. const defaultTasks = JSON.stringify(defaultTasksTemplate);
  6867. class FreeAnyWhere extends website_Website {
  6868. name = 'FreeAnyWhere';
  6869. tasks = [];
  6870. socialTasks = JSON.parse(defaultTasks);
  6871. undoneTasks = JSON.parse(defaultTasks);
  6872. buttons = [ 'doTask', 'undoTask', 'verifyTask', 'getKey' ];
  6873. static test() {
  6874. return window.location.host === 'freeanywhere.net';
  6875. }
  6876. async init() {
  6877. try {
  6878. const logStatus = scripts_echoLog({
  6879. text: i18n('initing')
  6880. });
  6881. if ($('a[href="#/login"]').length > 0) {
  6882. window.open('/#/login', '_self');
  6883. logStatus.warning(i18n('needLogin'));
  6884. return false;
  6885. }
  6886. if (window.location.href.includes('/login')) {
  6887. logStatus.warning(i18n('needLogin'));
  6888. return false;
  6889. }
  6890. if (!/^https?:\/\/freeanywhere\.net\/#\/giveaway\/[\d]+/.test(window.location.href)) {
  6891. const id = window.location.href.match(/https?:\/\/freeanywhere\.net\/.*?#\/giveaway\/([\d]+)/)?.[1];
  6892. if (!id) {
  6893. logStatus.error(i18n('getFailed', 'Id'));
  6894. return false;
  6895. }
  6896. window.location.href = `https://freeanywhere.net/#/giveaway/${id}`;
  6897. }
  6898. if (!this.#getGiveawayId()) {
  6899. return false;
  6900. }
  6901. if (!await this.#checkLeftKey()) {
  6902. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  6903. }
  6904. this.initialized = true;
  6905. logStatus.success();
  6906. return true;
  6907. } catch (error) {
  6908. throwError(error, 'Freeanywhere.init');
  6909. return false;
  6910. }
  6911. }
  6912. async classifyTask(action) {
  6913. try {
  6914. const logStatus = scripts_echoLog({
  6915. text: i18n('getTasksInfo')
  6916. });
  6917. if (action === 'undo') {
  6918. this.socialTasks = GM_getValue(`fawTasks-${this.giveawayId}`)?.tasks || JSON.parse(defaultTasks);
  6919. }
  6920. const {
  6921. result,
  6922. statusText,
  6923. status,
  6924. data
  6925. } = await tools_httpRequest({
  6926. url: `https://freeanywhere.net/api/v1/giveaway/${this.giveawayId}/?format=json`,
  6927. method: 'GET',
  6928. headers: {
  6929. authorization: `Token ${window.localStorage.getItem('token')}`,
  6930. 'x-csrftoken': external_Cookies_default().get('csrftoken')
  6931. },
  6932. responseType: 'json'
  6933. });
  6934. if (result === 'Success') {
  6935. const tasks = data?.response?.challenges;
  6936. if (tasks) {
  6937. if (action === 'verify') {
  6938. this.tasks = [];
  6939. }
  6940. for (const task of tasks) {
  6941. const type = task.challenge;
  6942. const social = task.challenge_provider;
  6943. const taskInfo = {
  6944. id: task.id,
  6945. title: task.title
  6946. };
  6947. if (action === 'verify' && !task.is_success) {
  6948. this.tasks.push(taskInfo);
  6949. continue;
  6950. }
  6951. switch (social) {
  6952. case 'steam':
  6953. taskInfo.social = 'steam';
  6954. switch (type) {
  6955. case 'WL':
  6956. if (action === 'undo') {
  6957. this.socialTasks.steam.wishlistLinks.push(task.link);
  6958. }
  6959. if (action === 'do' && !task.is_success) {
  6960. this.undoneTasks.steam.wishlistLinks.push(task.link);
  6961. }
  6962. break;
  6963.  
  6964. case 'JTG':
  6965. if (action === 'undo') {
  6966. this.socialTasks.steam.groupLinks.push(task.link);
  6967. }
  6968. if (action === 'do' && !task.is_success) {
  6969. this.undoneTasks.steam.groupLinks.push(task.link);
  6970. }
  6971. break;
  6972.  
  6973. case 'STC':
  6974. if (action === 'undo') {
  6975. this.socialTasks.steam.curatorLinks.push(task.link);
  6976. }
  6977. if (action === 'do' && !task.is_success) {
  6978. this.undoneTasks.steam.curatorLinks.push(task.link);
  6979. }
  6980. break;
  6981.  
  6982. case 'GF':
  6983. if (action === 'undo') {
  6984. this.socialTasks.steam.followLinks.push(task.link);
  6985. }
  6986. if (action === 'do' && !task.is_success) {
  6987. this.undoneTasks.steam.followLinks.push(task.link);
  6988. }
  6989. break;
  6990. }
  6991. break;
  6992.  
  6993. case 'vk-oauth2':
  6994. if (action === 'undo') {
  6995. this.socialTasks.vk.nameLinks.push(task.link);
  6996. }
  6997. if (action === 'do' && !task.is_success) {
  6998. this.undoneTasks.vk.nameLinks.push(task.link);
  6999. }
  7000. break;
  7001.  
  7002. case 'website':
  7003. break;
  7004.  
  7005. default:
  7006. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${social}`);
  7007. break;
  7008. }
  7009. }
  7010. logStatus.success();
  7011. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7012. this.socialTasks = this.uniqueTasks(this.socialTasks);
  7013. if (window.DEBUG) {
  7014. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7015. }
  7016. GM_setValue(`fawTasks-${this.giveawayId}`, {
  7017. tasks: this.socialTasks,
  7018. time: new Date().getTime()
  7019. });
  7020. return true;
  7021. }
  7022. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7023. return false;
  7024. }
  7025. logStatus.error(`${result}:${statusText}(${status})`);
  7026. return false;
  7027. } catch (error) {
  7028. throwError(error, 'Freeanywhere.classifyTask');
  7029. return false;
  7030. }
  7031. }
  7032. async verifyTask() {
  7033. try {
  7034. if (!this.initialized && !this.init()) {
  7035. return false;
  7036. }
  7037. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  7038. return false;
  7039. }
  7040. const pro = [];
  7041. for (const task of this.tasks) {
  7042. pro.push(this.#verify(task));
  7043. await delay(1e3);
  7044. }
  7045. await Promise.all(pro);
  7046. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7047. return !!await this.getKey(true);
  7048. } catch (error) {
  7049. throwError(error, 'Freeanywhere.verifyTask');
  7050. return false;
  7051. }
  7052. }
  7053. async getKey(initialized) {
  7054. try {
  7055. if (!initialized && !this.initialized && !this.init()) {
  7056. return false;
  7057. }
  7058. const logStatus = scripts_echoLog({
  7059. text: i18n('gettingKey')
  7060. });
  7061. const {
  7062. result,
  7063. statusText,
  7064. status,
  7065. data
  7066. } = await tools_httpRequest({
  7067. url: `https://freeanywhere.net/api/v1/giveaway/${this.giveawayId}/reward/?format=json`,
  7068. method: 'GET',
  7069. dataType: 'json',
  7070. headers: {
  7071. authorization: `Token ${window.localStorage.getItem('token')}`
  7072. }
  7073. });
  7074. if (result === 'Success') {
  7075. if (data?.response?.reward) {
  7076. logStatus.success();
  7077. scripts_echoLog({}).success(data.response.reward);
  7078. return data.response.reward;
  7079. }
  7080. if (data?.response?.completed === false) {
  7081. logStatus.error(i18n('tasksNotCompleted'));
  7082. return false;
  7083. }
  7084. if (data?.response?.completed === true) {
  7085. await this.#checkLeftKey();
  7086. }
  7087. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7088. return false;
  7089. }
  7090. logStatus.error(`${result}:${statusText}(${status})`);
  7091. return false;
  7092. } catch (error) {
  7093. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7094. return false;
  7095. }
  7096. }
  7097. #getGiveawayId() {
  7098. try {
  7099. const giveawayId = window.location.href.match(/\/giveaway\/([\d]+)/)?.[1];
  7100. if (giveawayId) {
  7101. this.giveawayId = giveawayId;
  7102. return true;
  7103. }
  7104. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  7105. return false;
  7106. } catch (error) {
  7107. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7108. return false;
  7109. }
  7110. }
  7111. async #verify(task) {
  7112. try {
  7113. const logStatus = scripts_echoLog({
  7114. html: `<li>${i18n('verifyingTask')}${task.title.trim()}...<font></font></li>`
  7115. });
  7116. const {
  7117. result,
  7118. statusText,
  7119. status,
  7120. data
  7121. } = await tools_httpRequest({
  7122. url: `https://freeanywhere.net/api/v1/giveaway/${this.giveawayId}/challenge-status/${task.id}/?format=json`,
  7123. method: 'GET',
  7124. dataType: 'json',
  7125. headers: {
  7126. authorization: `Token ${window.localStorage.getItem('token')}`,
  7127. 'x-csrftoken': external_Cookies_default().get('csrftoken')
  7128. }
  7129. });
  7130. if (result === 'Success') {
  7131. if (data?.response?.status) {
  7132. logStatus.success();
  7133. return true;
  7134. }
  7135. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7136. return false;
  7137. }
  7138. logStatus.error(`${result}:${statusText}(${status})`);
  7139. return false;
  7140. } catch (error) {
  7141. throwError(error, 'Freeanywhere.verify');
  7142. return false;
  7143. }
  7144. }
  7145. async #checkLeftKey() {
  7146. try {
  7147. if (!globalOptions.other.checkLeftKey) {
  7148. return true;
  7149. }
  7150. const {
  7151. data
  7152. } = await tools_httpRequest({
  7153. url: 'https://freeanywhere.net/api/v1/widget/?format=json',
  7154. method: 'GET',
  7155. dataType: 'json',
  7156. headers: {
  7157. authorization: `Token ${window.localStorage.getItem('token')}`
  7158. }
  7159. });
  7160. if (data?.response?.giveaways.find(giveaway => `${giveaway?.id}` === this.giveawayId)) {
  7161. return true;
  7162. }
  7163. await external_Swal_default().fire({
  7164. icon: 'warning',
  7165. title: i18n('notice'),
  7166. text: i18n('noKeysLeft'),
  7167. confirmButtonText: i18n('confirm'),
  7168. cancelButtonText: i18n('cancel'),
  7169. showCancelButton: true
  7170. }).then(({
  7171. value
  7172. }) => {
  7173. if (value) {
  7174. window.close();
  7175. }
  7176. });
  7177. return true;
  7178. } catch (error) {
  7179. throwError(error, 'Giveawaysu.checkLeftKey');
  7180. return false;
  7181. }
  7182. }
  7183. }
  7184. const Freeanywhere = FreeAnyWhere;
  7185. const Giveawaysu_defaultTasks = {
  7186. steam: {
  7187. groupLinks: [],
  7188. wishlistLinks: [],
  7189. curatorLinks: [],
  7190. curatorLikeLinks: [],
  7191. followLinks: [],
  7192. forumLinks: [],
  7193. announcementLinks: [],
  7194. workshopVoteLinks: [],
  7195. playtestLinks: []
  7196. },
  7197. discord: {
  7198. serverLinks: []
  7199. },
  7200. instagram: {
  7201. userLinks: []
  7202. },
  7203. vk: {
  7204. nameLinks: []
  7205. },
  7206. twitch: {
  7207. channelLinks: []
  7208. },
  7209. reddit: {
  7210. redditLinks: []
  7211. },
  7212. youtube: {
  7213. channelLinks: [],
  7214. likeLinks: []
  7215. },
  7216. twitter: {
  7217. userLinks: [],
  7218. retweetLinks: []
  7219. }
  7220. };
  7221. class GiveawaySu extends website_Website {
  7222. name = 'GiveawaySu';
  7223. socialTasks = Giveawaysu_defaultTasks;
  7224. undoneTasks = Giveawaysu_defaultTasks;
  7225. buttons = [ 'doTask', 'undoTask' ];
  7226. static test() {
  7227. return /^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(window.location.href);
  7228. }
  7229. async after() {
  7230. try {
  7231. if (!this.#checkLogin()) {
  7232. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7233. }
  7234. if (!await this.#checkLeftKey()) {
  7235. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7236. }
  7237. scripts_echoLog({}).warning(i18n('gsNotice'));
  7238. } catch (error) {
  7239. throwError(error, 'Giveawaysu.after');
  7240. }
  7241. }
  7242. init() {
  7243. try {
  7244. const logStatus = scripts_echoLog({
  7245. text: i18n('initing')
  7246. });
  7247. if ($('a.steam-login').length > 0) {
  7248. window.open('/steam/redirect', '_self');
  7249. logStatus.warning(i18n('needLogin'));
  7250. return false;
  7251. }
  7252. if (!this.#getGiveawayId()) {
  7253. return false;
  7254. }
  7255. this.initialized = true;
  7256. logStatus.success();
  7257. return true;
  7258. } catch (error) {
  7259. throwError(error, 'Giveawaysu.init');
  7260. return false;
  7261. }
  7262. }
  7263. async classifyTask(action) {
  7264. try {
  7265. const logStatus = scripts_echoLog({
  7266. text: i18n('getTasksInfo')
  7267. });
  7268. if (action === 'undo') {
  7269. this.socialTasks = GM_getValue(`gasTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  7270. return true;
  7271. }
  7272. const pro = [];
  7273. const tasks = $('#actions tr');
  7274. if ($('div.bind-discord').is(':visible')) {
  7275. $('div.bind-discord a')[0].click();
  7276. }
  7277. if ($('div.bind-twitch').is(':visible')) {
  7278. $('div.bind-twitch a')[0].click();
  7279. }
  7280. for (const task of tasks) {
  7281. pro.push(new Promise(resolve => {
  7282. const td = $(task).find('td:not(".hidden")');
  7283. const colorfulTask = td.eq(1).find('a:not([data-trigger="link"])');
  7284. const colorlessTask = td.eq(2).find('a:not([data-trigger="link"])');
  7285. const taskDes = colorfulTask.length > 0 ? colorfulTask : colorlessTask;
  7286. const taskIcon = td.eq(0).find('i').attr('class') || '';
  7287. const taskName = taskDes.text().trim();
  7288. if (taskIcon.includes('ban') || /disable adblock/gi.test(taskName)) {
  7289. return resolve(true);
  7290. }
  7291. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  7292. if (!taskLink) {
  7293. return resolve(false);
  7294. }
  7295. if (taskIcon.includes('steam') && /join/gi.test(taskName)) {
  7296. this.undoneTasks.steam.groupLinks.push(taskLink);
  7297. } else if (/like.*announcement/gi.test(taskName)) {
  7298. this.undoneTasks.steam.announcementLinks.push(taskLink);
  7299. } else if (/(follow|subscribe).*curator/gim.test(taskName) && /^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  7300. this.undoneTasks.steam.curatorLinks.push(taskLink);
  7301. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  7302. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  7303. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  7304. this.undoneTasks.steam.forumLinks.push(taskLink);
  7305. } else if (taskIcon.includes('thumbs-up') && /^https?:\/\/steamcommunity\.com\/sharedfiles\/filedetails\/\?id=[\d]+/.test(taskLink)) {
  7306. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7307. } else if (taskIcon.includes('plus') && /request.*playtest/gim.test(taskName)) {
  7308. this.undoneTasks.steam.playtestLinks.push(taskLink);
  7309. } else if (taskIcon.includes('discord') || /join.*discord/gim.test(taskName)) {
  7310. this.undoneTasks.discord.serverLinks.push(taskLink);
  7311. } else if (taskIcon.includes('instagram') || /follow.*instagram/gim.test(taskName)) {
  7312. this.undoneTasks.instagram.userLinks.push(taskLink);
  7313. } else if (taskIcon.includes('twitch') || /follow.*twitch.*channel/gim.test(taskName)) {
  7314. this.undoneTasks.twitch.channelLinks.push(taskLink);
  7315. } else if (taskIcon.includes('reddit') || /subscribe.*subreddit/gim.test(taskName) || /follow.*reddit/gim.test(taskName)) {
  7316. this.undoneTasks.reddit.redditLinks.push(taskLink);
  7317. } else if (/watch.*art/gim.test(taskName)) {
  7318. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7319. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  7320. this.undoneTasks.youtube.channelLinks.push(taskLink);
  7321. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  7322. this.undoneTasks.youtube.likeLinks.push(taskLink);
  7323. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  7324. this.undoneTasks.vk.nameLinks.push(taskLink);
  7325. } else {
  7326. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  7327. if (/wishlist.*game|add.*wishlist/gim.test(taskName)) {
  7328. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  7329. }
  7330. if (/follow.*button/gim.test(taskName)) {
  7331. this.undoneTasks.steam.followLinks.push(taskLink);
  7332. }
  7333. }
  7334. }
  7335. resolve(true);
  7336. }).catch(error => {
  7337. throwError(error, 'Giveawaysu.classifyTask->getRedirectLink');
  7338. return false;
  7339. });
  7340. }));
  7341. }
  7342. await Promise.all(pro);
  7343. logStatus.success();
  7344. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7345. this.socialTasks = this.undoneTasks;
  7346. if (window.DEBUG) {
  7347. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7348. }
  7349. GM_setValue(`gasTasks-${this.giveawayId}`, {
  7350. tasks: this.socialTasks,
  7351. time: new Date().getTime()
  7352. });
  7353. return true;
  7354. } catch (error) {
  7355. throwError(error, 'Giveawaysu.classifyTask');
  7356. return false;
  7357. }
  7358. }
  7359. #checkLogin() {
  7360. try {
  7361. if (!globalOptions.other.checkLogin) {
  7362. return true;
  7363. }
  7364. if ($('a.steam-login').length > 0) {
  7365. window.open('/steam/redirect', '_self');
  7366. }
  7367. return true;
  7368. } catch (error) {
  7369. throwError(error, 'Giveawaysu.checkLogin');
  7370. return false;
  7371. }
  7372. }
  7373. async #checkLeftKey() {
  7374. try {
  7375. if (!globalOptions.other.checkLeftKey) {
  7376. return true;
  7377. }
  7378. if ($('.giveaway-ended').length > 0 && $('.giveaway-key').length === 0) {
  7379. await external_Swal_default().fire({
  7380. icon: 'warning',
  7381. title: i18n('notice'),
  7382. text: i18n('noKeysLeft'),
  7383. confirmButtonText: i18n('confirm'),
  7384. cancelButtonText: i18n('cancel'),
  7385. showCancelButton: true
  7386. }).then(({
  7387. value
  7388. }) => {
  7389. if (value) {
  7390. window.close();
  7391. }
  7392. });
  7393. }
  7394. return true;
  7395. } catch (error) {
  7396. throwError(error, 'Giveawaysu.checkLeftKey');
  7397. return false;
  7398. }
  7399. }
  7400. #getGiveawayId() {
  7401. try {
  7402. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  7403. if (giveawayId) {
  7404. this.giveawayId = giveawayId;
  7405. return true;
  7406. }
  7407. scripts_echoLog({
  7408. text: i18n('getFailed', 'GiveawayId')
  7409. });
  7410. return false;
  7411. } catch (error) {
  7412. throwError(error, 'Giveawaysu.getGiveawayId');
  7413. return false;
  7414. }
  7415. }
  7416. }
  7417. class Indiedb {
  7418. name = 'Indiedb';
  7419. buttons = [ 'doTask' ];
  7420. static test() {
  7421. return window.location.host === 'www.indiedb.com';
  7422. }
  7423. async after() {
  7424. try {
  7425. if (!this.#checkLogin()) {
  7426. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7427. }
  7428. if (!await this.#checkLeftKey()) {
  7429. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7430. }
  7431. } catch (error) {
  7432. throwError(error, 'Indiedb.after');
  7433. }
  7434. }
  7435. async doTask() {
  7436. try {
  7437. if (!await this.#join()) {
  7438. return false;
  7439. }
  7440. return await this.#do();
  7441. } catch (error) {
  7442. throwError(error, 'Indiedb.doTask');
  7443. return false;
  7444. }
  7445. }
  7446. async #join() {
  7447. try {
  7448. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7449. scripts_echoLog({}).error(i18n('needLogin'));
  7450. return false;
  7451. }
  7452. const currentoption = $('a.buttonenter.buttongiveaway');
  7453. if (/join giveaway/gim.test(currentoption.text())) {
  7454. const logStatus = scripts_echoLog({
  7455. text: `${i18n('joiningGiveaway')}...`
  7456. });
  7457. const {
  7458. result,
  7459. statusText,
  7460. status,
  7461. data
  7462. } = await tools_httpRequest({
  7463. url: currentoption.attr('href'),
  7464. method: 'POST',
  7465. data: 'ajax=t',
  7466. dataType: 'json',
  7467. headers: {
  7468. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  7469. Accept: 'application/json, text/javascript, */*; q=0.01',
  7470. Origin: window.location.origin,
  7471. referer: window.location.href
  7472. }
  7473. });
  7474. if (result === 'Success') {
  7475. if (data?.status === 200) {
  7476. if (data.response?.success) {
  7477. currentoption.addClass('buttonentered').text('Success - Giveaway joined');
  7478. $('#giveawaysjoined').slideDown();
  7479. $('#giveawaysrecommend').slideDown();
  7480. logStatus.success(`Success${data.response?.text ? `:${data.response?.text}` : ''}`);
  7481. return true;
  7482. }
  7483. logStatus.error(`Error${data.response?.text ? `:${data.response?.text}` : ''}`);
  7484. return false;
  7485. }
  7486. if (await this.#join2()) {
  7487. logStatus.success('Success');
  7488. return true;
  7489. }
  7490. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7491. return false;
  7492. }
  7493. logStatus.error(`${result}:${statusText}(${status})`);
  7494. return false;
  7495. } else if (/success/gim.test($('a.buttonenter.buttongiveaway').text())) {
  7496. return true;
  7497. }
  7498. scripts_echoLog({}).warning(i18n('needJoinGiveaway'));
  7499. return false;
  7500. } catch (error) {
  7501. throwError(error, 'Indiedb.join');
  7502. return false;
  7503. }
  7504. }
  7505. async #join2() {
  7506. try {
  7507. return await new Promise(resolve => {
  7508. const targetNode = document.getElementById('giveawaysjoined');
  7509. const config = {
  7510. attributes: true
  7511. };
  7512. const observer = new MutationObserver(() => {
  7513. if ($('#giveawaysjoined').is(':visible')) {
  7514. resolve(true);
  7515. observer.disconnect();
  7516. }
  7517. });
  7518. observer.observe(targetNode, config);
  7519. $('a.buttonenter.buttongiveaway')[0]?.click();
  7520. setTimeout(() => {
  7521. resolve(false);
  7522. observer.disconnect();
  7523. }, 3e4);
  7524. });
  7525. } catch (error) {
  7526. throwError(error, 'Indiedb.join2');
  7527. return false;
  7528. }
  7529. }
  7530. async #do() {
  7531. try {
  7532. const id = $('script').map((index, script) => {
  7533. if (/\$\(document\)/gim.test(script.innerHTML)) {
  7534. return [ script.innerHTML.match(/"\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0], script.innerHTML.match(/"\/newsletter\/ajax\/subscribeprofile\/optin\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0] ];
  7535. }
  7536. return null;
  7537. });
  7538. if (id.length === 2) {
  7539. const pro = [];
  7540. const tasks = $('#giveawaysjoined a[class*=promo]');
  7541. for (const task of tasks) {
  7542. const promo = $(task);
  7543. if (!promo.hasClass('buttonentered')) {
  7544. const status = scripts_echoLog({
  7545. text: `${i18n('doing')}:${promo.parents('p').text()}...`
  7546. });
  7547. if (/facebookpromo|twitterpromo|visitpromo/gim.test(task.className)) {
  7548. let text = '';
  7549. if (promo.hasClass('facebookpromo')) {
  7550. text = 'facebookpromo';
  7551. } else if (promo.hasClass('twitterpromo')) {
  7552. text = 'twitterpromo';
  7553. } else {
  7554. text = 'visitpromo';
  7555. }
  7556. pro.push(new Promise(resolve => {
  7557. $.ajax({
  7558. type: 'POST',
  7559. url: urlPath(`/giveaways/ajax/${text}/${id[0]}`),
  7560. timeout: 6e4,
  7561. dataType: 'json',
  7562. data: {
  7563. ajax: 't'
  7564. },
  7565. error(response, error, exception) {
  7566. if (window.DEBUG) {
  7567. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7568. response: response,
  7569. error: error,
  7570. exception: exception
  7571. });
  7572. }
  7573. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7574. resolve(true);
  7575. },
  7576. success(response) {
  7577. if (response.success) {
  7578. status.success(`Success:${response.text}`);
  7579. promo.addClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7580. resolve(true);
  7581. } else {
  7582. status.error(`Error:${response.text}`);
  7583. resolve(true);
  7584. }
  7585. }
  7586. });
  7587. }));
  7588. } else if (promo.hasClass('emailoptinpromo')) {
  7589. pro.push(new Promise(resolve => {
  7590. $.ajax({
  7591. type: 'POST',
  7592. url: urlPath(`/newsletter/ajax/subscribeprofile/optin/${id[1]}`),
  7593. timeout: 6e4,
  7594. dataType: 'json',
  7595. data: {
  7596. ajax: 't',
  7597. emailsystoggle: 4
  7598. },
  7599. error(response, error, exception) {
  7600. if (window.DEBUG) {
  7601. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7602. response: response,
  7603. error: error,
  7604. exception: exception
  7605. });
  7606. }
  7607. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7608. resolve(true);
  7609. },
  7610. success(response) {
  7611. if (response.success) {
  7612. status.success(`Success:${response.text}`);
  7613. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7614. resolve(true);
  7615. } else {
  7616. status.error(`Error:${response.text}`);
  7617. resolve(true);
  7618. }
  7619. }
  7620. });
  7621. }));
  7622. } else if (promo.hasClass('watchingpromo')) {
  7623. pro.push(new Promise(resolve => {
  7624. const data = getUrlQuery(promo.attr('href'));
  7625. data.ajax = 't';
  7626. $.ajax({
  7627. type: 'POST',
  7628. url: urlPath(promo.attr('href')?.split(/[?#]/)[0]),
  7629. timeout: 6e4,
  7630. dataType: 'json',
  7631. data: data,
  7632. error(response, error, exception) {
  7633. if (window.DEBUG) {
  7634. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7635. response: response,
  7636. error: error,
  7637. exception: exception
  7638. });
  7639. }
  7640. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7641. resolve(true);
  7642. },
  7643. success(response) {
  7644. if (response.success) {
  7645. status.success(`Success:${response.text}`);
  7646. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7647. resolve(true);
  7648. } else {
  7649. status.error(`Error:${response.text}`);
  7650. resolve(true);
  7651. }
  7652. }
  7653. });
  7654. }));
  7655. } else if (!/the-challenge-of-adblock/gim.test(promo.attr('href'))) {
  7656. pro.push(new Promise(resolve => {
  7657. $.ajax({
  7658. type: 'POST',
  7659. url: urlPath(promo.attr('href')),
  7660. timeout: 6e4,
  7661. dataType: 'json',
  7662. data: {
  7663. ajax: 't'
  7664. },
  7665. error(response, error, exception) {
  7666. if (window.DEBUG) {
  7667. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7668. response: response,
  7669. error: error,
  7670. exception: exception
  7671. });
  7672. }
  7673. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7674. resolve(true);
  7675. },
  7676. success(response) {
  7677. if (response.success) {
  7678. status.success(`Success:${response.text}`);
  7679. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7680. resolve(true);
  7681. } else {
  7682. status.error(`Error:${response.text}`);
  7683. resolve(true);
  7684. }
  7685. }
  7686. });
  7687. }));
  7688. } else {
  7689. status.error(`Error:${i18n('unKnownTaskType')}`);
  7690. }
  7691. }
  7692. }
  7693. await Promise.all(pro);
  7694. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7695. return true;
  7696. }
  7697. scripts_echoLog({}).error(i18n('getFailed', 'TaskId'));
  7698. return false;
  7699. } catch (error) {
  7700. throwError(error, 'Indiedb.classifyTask');
  7701. return false;
  7702. }
  7703. }
  7704. #checkLogin() {
  7705. try {
  7706. if (!globalOptions.other.checkLogin) {
  7707. return true;
  7708. }
  7709. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7710. window.open('/members/login', '_self');
  7711. }
  7712. return true;
  7713. } catch (error) {
  7714. throwError(error, 'Indiedb.checkLogin');
  7715. return false;
  7716. }
  7717. }
  7718. async #checkLeftKey() {
  7719. try {
  7720. if (!globalOptions.other.checkLeftKey) {
  7721. return true;
  7722. }
  7723. if ($('a.buttonenter:contains("next time"), a.buttonenter:contains("Giveaway is closed")').length > 0) {
  7724. await external_Swal_default().fire({
  7725. icon: 'warning',
  7726. title: i18n('notice'),
  7727. text: i18n('giveawayEnded'),
  7728. confirmButtonText: i18n('confirm'),
  7729. cancelButtonText: i18n('cancel'),
  7730. showCancelButton: true
  7731. }).then(({
  7732. value
  7733. }) => {
  7734. if (value) {
  7735. window.close();
  7736. }
  7737. });
  7738. }
  7739. return true;
  7740. } catch (error) {
  7741. throwError(error, 'Indiedb.checkLeftKey');
  7742. return false;
  7743. }
  7744. }
  7745. }
  7746. const website_Indiedb = Indiedb;
  7747. const Keyhub_defaultTasksTemplate = {
  7748. steam: {
  7749. groupLinks: [],
  7750. officialGroupLinks: [],
  7751. wishlistLinks: [],
  7752. curatorLinks: []
  7753. },
  7754. discord: {
  7755. serverLinks: []
  7756. },
  7757. extra: {
  7758. videoTasks: []
  7759. },
  7760. links: []
  7761. };
  7762. const Keyhub_defaultTasks = JSON.stringify(Keyhub_defaultTasksTemplate);
  7763. class Keyhub extends website_Website {
  7764. name = 'Keyhub';
  7765. socialTasks = JSON.parse(Keyhub_defaultTasks);
  7766. undoneTasks = JSON.parse(Keyhub_defaultTasks);
  7767. buttons = [ 'doTask', 'undoTask' ];
  7768. static test() {
  7769. return window.location.host === 'key-hub.eu';
  7770. }
  7771. async after() {
  7772. try {
  7773. if (!this.#checkLogin()) {
  7774. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7775. }
  7776. if (!await this.#checkLeftKey()) {
  7777. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7778. }
  7779. $('.NSFW').hide();
  7780. } catch (error) {
  7781. throwError(error, 'Keyhub.after');
  7782. }
  7783. }
  7784. init() {
  7785. try {
  7786. const logStatus = scripts_echoLog({
  7787. text: i18n('initing')
  7788. });
  7789. if ($('a[href*="/connect/steam"]').length > 0) {
  7790. window.open('/connect/steam', '_self');
  7791. logStatus.warning(i18n('needLogin'));
  7792. return false;
  7793. }
  7794. if (!this.#getGiveawayId()) {
  7795. return false;
  7796. }
  7797. $('#VPNoverlay').hide();
  7798. $('#mainArticleSection').show();
  7799. this.initialized = true;
  7800. logStatus.success();
  7801. return true;
  7802. } catch (error) {
  7803. throwError(error, 'Keyhub.init');
  7804. return false;
  7805. }
  7806. }
  7807. async classifyTask(action) {
  7808. try {
  7809. const logStatus = scripts_echoLog({
  7810. text: i18n('getTasksInfo')
  7811. });
  7812. if (action === 'undo') {
  7813. this.socialTasks = GM_getValue(`khTasks-${this.giveawayId}`)?.tasks || JSON.parse(Keyhub_defaultTasks);
  7814. }
  7815. const tasks = $('.task:not(".googleads")').filter((index, element) => action === 'do' ? $(element).find('i.fa-check-circle:visible').length === 0 : true).find('a');
  7816. for (const task of tasks) {
  7817. let link = $(task).attr('href');
  7818. const taskDes = $(task).text().trim();
  7819. if (!link) {
  7820. continue;
  7821. }
  7822. if (/\/away\?data=/.test(link) || /steamcommunity\.com\/gid\//.test(link)) {
  7823. link = await getRedirectLink(link) || link;
  7824. }
  7825. if (/https?:\/\/key-hub\.eu\/connect\/discord/.test(link)) {
  7826. GM_openInTab(link, {
  7827. active: true
  7828. });
  7829. } else if (/steamcommunity\.com\/groups\//.test(link)) {
  7830. if (action === 'undo') {
  7831. this.socialTasks.steam.groupLinks.push(link);
  7832. }
  7833. if (action === 'do') {
  7834. this.undoneTasks.steam.groupLinks.push(link);
  7835. }
  7836. } else if (/steamcommunity\.com\/games\/[\d]+/.test(link)) {
  7837. if (action === 'undo') {
  7838. this.socialTasks.steam.officialGroupLinks.push(link);
  7839. }
  7840. if (action === 'do') {
  7841. this.undoneTasks.steam.officialGroupLinks.push(link);
  7842. }
  7843. } else if (/store\.steampowered\.com\/app\//.test(link) && /wishlist/gim.test(taskDes)) {
  7844. if (action === 'undo') {
  7845. this.socialTasks.steam.wishlistLinks.push(link);
  7846. }
  7847. if (action === 'do') {
  7848. this.undoneTasks.steam.wishlistLinks.push(link);
  7849. }
  7850. } else if (/store\.steampowered\.com\/curator\//.test(link)) {
  7851. if (action === 'undo') {
  7852. this.socialTasks.steam.curatorLinks.push(link);
  7853. }
  7854. if (action === 'do') {
  7855. this.undoneTasks.steam.curatorLinks.push(link);
  7856. }
  7857. } else if (/^https?:\/\/discord\.com\/invite\//.test(link)) {
  7858. if (action === 'undo') {
  7859. this.socialTasks.discord.serverLinks.push(link);
  7860. }
  7861. if (action === 'do') {
  7862. this.undoneTasks.discord.serverLinks.push(link);
  7863. }
  7864. } else if (/^javascript:videoTask.+/.test(link)) {
  7865. if (action === 'do') {
  7866. const taskData = link.match(/javascript:videoTask\('.+?','(.+?)'/)?.[1];
  7867. if (taskData) {
  7868. this.undoneTasks.extra.videoTasks.push(taskData);
  7869. }
  7870. }
  7871. } 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 {
  7872. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  7873. }
  7874. }
  7875. logStatus.success();
  7876. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7877. this.socialTasks = this.uniqueTasks(this.socialTasks);
  7878. if (window.DEBUG) {
  7879. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7880. }
  7881. GM_setValue(`khTasks-${this.giveawayId}`, {
  7882. tasks: this.socialTasks,
  7883. time: new Date().getTime()
  7884. });
  7885. return true;
  7886. } catch (error) {
  7887. throwError(error, 'Keyhub.classifyTask');
  7888. return false;
  7889. }
  7890. }
  7891. async #doScriptTask(data) {
  7892. try {
  7893. const logStatus = scripts_echoLog({
  7894. text: i18n('doingKeyhubTask')
  7895. });
  7896. const {
  7897. result,
  7898. statusText,
  7899. status,
  7900. data: response
  7901. } = await tools_httpRequest({
  7902. url: `/away?data=${data}`,
  7903. method: 'GET',
  7904. headers: {
  7905. origin: 'https://key-hub.eu',
  7906. referer: 'https://key-hub.eu/'
  7907. }
  7908. });
  7909. if (result === 'Success') {
  7910. if (response?.status === 200) {
  7911. logStatus.success();
  7912. return true;
  7913. }
  7914. logStatus.error(`Error:${response?.statusText}(${response?.status})`);
  7915. return false;
  7916. }
  7917. logStatus.error(`${result}:${statusText}(${status})`);
  7918. return false;
  7919. } catch (error) {
  7920. throwError(error, 'Keyhub.doScriptTask');
  7921. return false;
  7922. }
  7923. }
  7924. async extraDoTask({
  7925. videoTasks
  7926. }) {
  7927. try {
  7928. const pro = [];
  7929. for (const data of videoTasks) {
  7930. pro.push(this.#doScriptTask(data));
  7931. }
  7932. return Promise.all(pro).then(() => true);
  7933. } catch (error) {
  7934. throwError(error, 'Keyhub.extraDoTask');
  7935. return false;
  7936. }
  7937. }
  7938. #getGiveawayId() {
  7939. try {
  7940. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  7941. if (giveawayId) {
  7942. this.giveawayId = giveawayId;
  7943. return true;
  7944. }
  7945. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  7946. return false;
  7947. } catch (error) {
  7948. throwError(error, 'Keyhub.getGiveawayId');
  7949. return false;
  7950. }
  7951. }
  7952. async #checkLeftKey() {
  7953. try {
  7954. if (!globalOptions.other.checkLeftKey) {
  7955. return true;
  7956. }
  7957. const leftKey = $('#keysleft').text().trim();
  7958. if (leftKey === '0') {
  7959. await external_Swal_default().fire({
  7960. icon: 'warning',
  7961. title: i18n('notice'),
  7962. text: i18n('noKeysLeft'),
  7963. confirmButtonText: i18n('confirm'),
  7964. cancelButtonText: i18n('cancel'),
  7965. showCancelButton: true
  7966. }).then(({
  7967. value
  7968. }) => {
  7969. if (value) {
  7970. window.close();
  7971. }
  7972. });
  7973. }
  7974. return true;
  7975. } catch (error) {
  7976. throwError(error, 'Keyhub.checkLeftKey');
  7977. return false;
  7978. }
  7979. }
  7980. #checkLogin() {
  7981. try {
  7982. if (!globalOptions.other.checkLogin) {
  7983. return true;
  7984. }
  7985. if ($('a[href*="/connect/steam"]').length > 0) {
  7986. window.open('/connect/steam', '_self');
  7987. }
  7988. return true;
  7989. } catch (error) {
  7990. throwError(error, 'Keyhub.checkLogin');
  7991. return false;
  7992. }
  7993. }
  7994. }
  7995. const website_Keyhub = Keyhub;
  7996. const Givekey_defaultTasksTemplate = {
  7997. steam: {
  7998. groupLinks: [],
  7999. wishlistLinks: [],
  8000. curatorLinks: [],
  8001. curatorLikeLinks: []
  8002. },
  8003. twitter: {
  8004. userLinks: []
  8005. },
  8006. vk: {
  8007. nameLinks: []
  8008. },
  8009. discord: {
  8010. serverLinks: []
  8011. }
  8012. };
  8013. const Givekey_defaultTasks = JSON.stringify(Givekey_defaultTasksTemplate);
  8014. class Givekey extends website_Website {
  8015. name = 'Givekey';
  8016. tasks = [];
  8017. socialTasks = JSON.parse(Givekey_defaultTasks);
  8018. undoneTasks = JSON.parse(Givekey_defaultTasks);
  8019. userId;
  8020. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8021. static test() {
  8022. return window.location.host === 'givekey.ru';
  8023. }
  8024. async after() {
  8025. try {
  8026. await new Promise(resolve => {
  8027. const checker = setInterval(() => {
  8028. if ($('#navbarDropdown').length > 0) {
  8029. clearInterval(checker);
  8030. resolve(true);
  8031. }
  8032. }, 500);
  8033. });
  8034. if (!await this.#checkLeftKey()) {
  8035. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8036. }
  8037. } catch (error) {
  8038. throwError(error, 'Givekey.after');
  8039. }
  8040. }
  8041. init() {
  8042. try {
  8043. const logStatus = scripts_echoLog({
  8044. text: i18n('initing')
  8045. });
  8046. if ($('a[href*="/auth/steam"]').length > 0) {
  8047. window.open('/auth/steam', '_self');
  8048. logStatus.warning(i18n('needLogin'));
  8049. return false;
  8050. }
  8051. if (!this.#getGiveawayId()) {
  8052. return false;
  8053. }
  8054. const userId = $('meta[name="user-id"]').attr('content');
  8055. if (!userId) {
  8056. logStatus.error(i18n('getFailed', i18n('userId')));
  8057. return false;
  8058. }
  8059. this.userId = userId;
  8060. this.initialized = true;
  8061. logStatus.success();
  8062. return true;
  8063. } catch (error) {
  8064. throwError(error, 'Givekey.init');
  8065. return false;
  8066. }
  8067. }
  8068. async classifyTask(action) {
  8069. try {
  8070. const logStatus = scripts_echoLog({
  8071. text: i18n('getTasksInfo')
  8072. });
  8073. if (action === 'undo') {
  8074. this.socialTasks = GM_getValue(`gkTasks-${this.giveawayId}`)?.tasks || JSON.parse(Givekey_defaultTasks);
  8075. }
  8076. const tasks = $('.card-body:has("button") .row');
  8077. for (const task of tasks) {
  8078. const taskEle = $(task);
  8079. const isSuccess = /Complete/i.test(taskEle.find('button').text().trim());
  8080. if (isSuccess && action !== 'undo') {
  8081. continue;
  8082. }
  8083. const checkButton = taskEle.find('#task_check');
  8084. const taskId = checkButton.attr('data-id');
  8085. if (taskId) {
  8086. this.tasks.push(taskId);
  8087. }
  8088. if (action === 'verify') {
  8089. continue;
  8090. }
  8091. let href = taskEle.find('a').attr('href') || null;
  8092. const text = taskEle.find('a').text().trim();
  8093. const icon = taskEle.find('i');
  8094. if (!href || !text) {
  8095. continue;
  8096. }
  8097. if (/^https?:\/\/givekey\.ru\/giveaway\/[\d]+\/execution_task/.test(href)) {
  8098. href = await getRedirectLink(href);
  8099. }
  8100. if (!href) {
  8101. continue;
  8102. }
  8103. if (/^https?:\/\/vk\.com\//.test(href)) {
  8104. this.socialTasks.vk.nameLinks.push(href);
  8105. if (action === 'do' && !isSuccess) {
  8106. this.undoneTasks.vk.nameLinks.push(href);
  8107. }
  8108. } else if (/^https?:\/\/steamcommunity\.com\/groups/.test(href)) {
  8109. this.socialTasks.steam.groupLinks.push(href);
  8110. if (action === 'do' && !isSuccess) {
  8111. this.undoneTasks.steam.groupLinks.push(href);
  8112. }
  8113. } else if (/^https?:\/\/store\.steampowered\.com\/app\//.test(href)) {
  8114. this.socialTasks.steam.wishlistLinks.push(href);
  8115. if (action === 'do' && !isSuccess) {
  8116. this.undoneTasks.steam.wishlistLinks.push(href);
  8117. }
  8118. } else if (/Subscribe/gi.test(text) && icon.hasClass('fa-steam-square')) {
  8119. if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(href)) {
  8120. this.socialTasks.steam.curatorLinks.push(href);
  8121. if (action === 'do' && !isSuccess) {
  8122. this.undoneTasks.steam.curatorLinks.push(href);
  8123. }
  8124. } else {
  8125. this.socialTasks.steam.curatorLikeLinks.push(href);
  8126. if (action === 'do' && !isSuccess) {
  8127. this.undoneTasks.steam.curatorLikeLinks.push(href);
  8128. }
  8129. }
  8130. } else if (/^https?:\/\/twitter\.com\//.test(href) && /Subscribe/gi.test(text)) {
  8131. this.socialTasks.twitter.userLinks.push(href);
  8132. if (action === 'do' && !isSuccess) {
  8133. this.undoneTasks.twitter.userLinks.push(href);
  8134. }
  8135. } else if (icon.hasClass('fa-discord') || /^https?:\/\/discord\.com\/invite\//.test(href)) {
  8136. this.socialTasks.discord.serverLinks.push(href);
  8137. if (action === 'do' && !isSuccess) {
  8138. this.undoneTasks.discord.serverLinks.push(href);
  8139. }
  8140. } else {
  8141. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${text}(${href})`);
  8142. }
  8143. }
  8144. logStatus.success();
  8145. this.tasks = unique(this.tasks);
  8146. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8147. this.socialTasks = this.uniqueTasks(this.socialTasks);
  8148. if (window.DEBUG) {
  8149. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8150. }
  8151. GM_setValue(`gkTasks-${this.giveawayId}`, {
  8152. tasks: this.socialTasks,
  8153. time: new Date().getTime()
  8154. });
  8155. return true;
  8156. } catch (error) {
  8157. throwError(error, 'Givekey.classifyTask');
  8158. return false;
  8159. }
  8160. }
  8161. async verifyTask() {
  8162. try {
  8163. if (!this.initialized && !this.init()) {
  8164. return false;
  8165. }
  8166. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  8167. return false;
  8168. }
  8169. scripts_echoLog({}).warning(i18n('giveKeyNoticeBefore'));
  8170. const taskLength = this.tasks.length;
  8171. for (let i = 0; i < taskLength; i++) {
  8172. await this.#verify(this.tasks[i]);
  8173. if (i < taskLength - 1) {
  8174. await delay(15e3);
  8175. }
  8176. }
  8177. scripts_echoLog({}).success(i18n('allTasksComplete'));
  8178. scripts_echoLog({
  8179. html: `<li><font class="warning">${i18n('giveKeyNoticeAfter')}</font></li>`
  8180. });
  8181. return true;
  8182. } catch (error) {
  8183. throwError(error, 'Givekey.verifyTask');
  8184. return false;
  8185. }
  8186. }
  8187. async #verify(task) {
  8188. try {
  8189. const logStatus = scripts_echoLog({
  8190. html: `<li>${i18n('verifyingTask')}${task}...<font></font></li>`
  8191. });
  8192. return await new Promise(resolve => {
  8193. $.ajax({
  8194. url: 'https://givekey.ru/giveaway/task',
  8195. method: 'POST',
  8196. data: `id=${task}&user_id=${this.userId}`,
  8197. dataType: 'json',
  8198. headers: {
  8199. 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  8200. },
  8201. success: data => {
  8202. if (data.btn) {
  8203. $(`button[data-id=${this.userId}]`).html(data.btn);
  8204. }
  8205. if (data.status === 'ok') {
  8206. $(`.task_check_${data.id}`).html(`<button class="btn btn-success mb-2 btn-block" disabled>${data.btn}</button>`);
  8207. logStatus.success();
  8208. resolve(true);
  8209. } else if (data.status === 'end') {
  8210. logStatus.success();
  8211. scripts_echoLog({}).success(data.key);
  8212. resolve(true);
  8213. } else {
  8214. logStatus.error(`Error:${data.msg}`);
  8215. resolve(false);
  8216. }
  8217. },
  8218. error: xhr => {
  8219. logStatus.error(`Error:${xhr.statusText}(${xhr.status})`);
  8220. resolve(false);
  8221. }
  8222. });
  8223. });
  8224. } catch (error) {
  8225. throwError(error, 'Givekey.verify');
  8226. return false;
  8227. }
  8228. }
  8229. #getGiveawayId() {
  8230. try {
  8231. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  8232. if (giveawayId) {
  8233. this.giveawayId = giveawayId;
  8234. return true;
  8235. }
  8236. scripts_echoLog({
  8237. text: i18n('getFailed', 'GiveawayId')
  8238. });
  8239. return false;
  8240. } catch (error) {
  8241. throwError(error, 'Givekey.getGiveawayId');
  8242. return false;
  8243. }
  8244. }
  8245. async #checkLeftKey() {
  8246. try {
  8247. if (!globalOptions.other.checkLeftKey) {
  8248. return true;
  8249. }
  8250. if (!$('#keys_count').text()) {
  8251. await external_Swal_default().fire({
  8252. icon: 'warning',
  8253. title: i18n('notice'),
  8254. text: i18n('noKeysLeft'),
  8255. confirmButtonText: i18n('confirm'),
  8256. cancelButtonText: i18n('cancel'),
  8257. showCancelButton: true
  8258. }).then(({
  8259. value
  8260. }) => {
  8261. if (value) {
  8262. window.close();
  8263. }
  8264. });
  8265. }
  8266. return true;
  8267. } catch (error) {
  8268. throwError(error, 'Givekey.checkLeftKey');
  8269. return false;
  8270. }
  8271. }
  8272. }
  8273. const website_Givekey = Givekey;
  8274. class GiveeClub extends GiveawaySu {
  8275. name = 'GiveeClub';
  8276. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8277. static test() {
  8278. return /^https?:\/\/givee\.club\/.*?\/event\/[\d]+/.test(window.location.href);
  8279. }
  8280. async after() {
  8281. try {
  8282. if (!this.#checkLogin()) {
  8283. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8284. }
  8285. if (!await this.#checkLeftKey()) {
  8286. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8287. }
  8288. } catch (error) {
  8289. throwError(error, 'GiveeClub.after');
  8290. }
  8291. }
  8292. init() {
  8293. try {
  8294. const logStatus = scripts_echoLog({
  8295. text: i18n('initing')
  8296. });
  8297. if (!this.#checkLogin()) {
  8298. logStatus.warning(i18n('needLogin'));
  8299. return false;
  8300. }
  8301. if (!this.#getGiveawayId()) {
  8302. return false;
  8303. }
  8304. this.initialized = true;
  8305. logStatus.success();
  8306. return true;
  8307. } catch (error) {
  8308. throwError(error, 'GiveeClub.init');
  8309. return false;
  8310. }
  8311. }
  8312. async classifyTask(action) {
  8313. try {
  8314. const logStatus = scripts_echoLog({
  8315. text: i18n('getTasksInfo')
  8316. });
  8317. if (action === 'undo') {
  8318. this.socialTasks = GM_getValue(`gcTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  8319. return true;
  8320. }
  8321. this.undoneTasks = Giveawaysu_defaultTasks;
  8322. const pro = [];
  8323. const tasks = $('.event-actions tr');
  8324. for (const task of tasks) {
  8325. pro.push(new Promise(resolve => {
  8326. const taskDes = $(task).find('.event-action-label a');
  8327. const taskIcon = $(task).find('.event-action-icon i').attr('class') || '';
  8328. const taskName = taskDes.text().trim();
  8329. const taskType = $(task).find('button[data-type]')?.attr('data-type');
  8330. const taskFinished = $(task).find('.event-action-buttons .btn-success')?.length;
  8331. if (taskIcon.includes('ban') || /AdBlock/i.test(taskName) || taskIcon.includes('envelope') || taskFinished) {
  8332. return resolve(true);
  8333. }
  8334. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  8335. if (!taskLink) {
  8336. return resolve(false);
  8337. }
  8338. if (taskType === 'steam.group.join' && /^https?:\/\/steamcommunity\.com\/groups/.test(taskLink)) {
  8339. this.undoneTasks.steam.groupLinks.push(taskLink);
  8340. } else if (/like.*announcement/gi.test(taskName)) {
  8341. this.undoneTasks.steam.announcementLinks.push(taskLink);
  8342. } else if (taskType === 'steam.game.wishlist' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8343. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  8344. } else if (taskType === 'steam.game.wishlist' && taskDes.attr('data-steam-wishlist-appid')) {
  8345. this.undoneTasks.steam.wishlistLinks.push(`https://store.steampowered.com/app/${taskDes.attr('data-steam-wishlist-appid')}`);
  8346. } else if (taskType === 'steam.game.follow' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8347. this.undoneTasks.steam.followLinks.push(taskLink);
  8348. } else if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  8349. this.undoneTasks.steam.curatorLinks.push(taskLink);
  8350. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  8351. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  8352. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  8353. this.undoneTasks.steam.forumLinks.push(taskLink);
  8354. } else if (taskIcon.includes('discord')) {
  8355. this.undoneTasks.discord.serverLinks.push(taskLink);
  8356. } else if (taskIcon.includes('instagram')) {
  8357. this.undoneTasks.instagram.userLinks.push(taskLink);
  8358. } else if (taskIcon.includes('twitch')) {
  8359. this.undoneTasks.twitch.channelLinks.push(taskLink);
  8360. } else if (taskIcon.includes('reddit')) {
  8361. this.undoneTasks.reddit.redditLinks.push(taskLink);
  8362. } else if (/watch.*art/gim.test(taskName)) {
  8363. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  8364. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  8365. this.undoneTasks.youtube.channelLinks.push(taskLink);
  8366. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  8367. this.undoneTasks.youtube.likeLinks.push(taskLink);
  8368. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  8369. this.undoneTasks.vk.nameLinks.push(taskLink);
  8370. } else if (taskIcon.includes('twitter')) {
  8371. if (/https?:\/\/(twitter|x)\.com\/[^/]+\/?$/gim.test(taskLink)) {
  8372. this.undoneTasks.twitter.userLinks.push(taskLink);
  8373. } else if (/https?:\/\/(twitter|x)\.com\/[^/]+?\/status\/[\d]+/gim.test(taskLink)) {
  8374. this.undoneTasks.twitter.retweetLinks.push(taskLink);
  8375. }
  8376. } else {
  8377. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  8378. if (/follow.*button/gim.test(taskName)) {
  8379. this.undoneTasks.steam.followLinks.push(taskLink);
  8380. }
  8381. }
  8382. }
  8383. resolve(true);
  8384. }).catch(error => {
  8385. throwError(error, 'GiveeClub.classifyTask->getRedirectLink');
  8386. return false;
  8387. });
  8388. }));
  8389. }
  8390. await Promise.all(pro);
  8391. logStatus.success();
  8392. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8393. this.socialTasks = this.undoneTasks;
  8394. if (window.DEBUG) {
  8395. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8396. }
  8397. GM_setValue(`gcTasks-${this.giveawayId}`, {
  8398. tasks: this.socialTasks,
  8399. time: new Date().getTime()
  8400. });
  8401. return true;
  8402. } catch (error) {
  8403. throwError(error, 'GiveeClub.classifyTask');
  8404. return false;
  8405. }
  8406. }
  8407. async verifyTask() {
  8408. try {
  8409. const logStatus = scripts_echoLog({
  8410. text: i18n('giveeClubVerifyNotice')
  8411. });
  8412. const taskButtons = $('.event-actions tr button').has('i.glyphicon-refresh').not('[data-type="user.adblock"]');
  8413. for (const button of taskButtons) {
  8414. button.click();
  8415. if ($(button).attr('data-type') !== 'steam.game.wishlist') {
  8416. await delay(1e3);
  8417. }
  8418. }
  8419. logStatus.warning(i18n('giveeClubVerifyFinished'));
  8420. return true;
  8421. } catch (error) {
  8422. throwError(error, 'Givekey.verifyTask');
  8423. return false;
  8424. }
  8425. }
  8426. #checkLogin() {
  8427. try {
  8428. if (!globalOptions.other.checkLogin) {
  8429. return true;
  8430. }
  8431. if ($('a[href*="/account/auth"]').length > 0) {
  8432. window.open($('a[href*="/account/auth"]').attr('href'), '_self');
  8433. }
  8434. return true;
  8435. } catch (error) {
  8436. throwError(error, 'GiveeClub.checkLogin');
  8437. return false;
  8438. }
  8439. }
  8440. #getGiveawayId() {
  8441. const giveawayId = window.location.href.match(/\/event\/([\d]+)/)?.[1];
  8442. if (giveawayId) {
  8443. this.giveawayId = giveawayId;
  8444. return true;
  8445. }
  8446. scripts_echoLog({
  8447. text: i18n('getFailed', 'GiveawayId')
  8448. });
  8449. return false;
  8450. }
  8451. async #checkLeftKey() {
  8452. try {
  8453. if (!globalOptions.other.checkLeftKey) {
  8454. return true;
  8455. }
  8456. if ($('.event-ended').length > 0 && $('.event-winner').length === 0) {
  8457. await external_Swal_default().fire({
  8458. icon: 'warning',
  8459. title: i18n('notice'),
  8460. text: i18n('giveawayEnded'),
  8461. confirmButtonText: i18n('confirm'),
  8462. cancelButtonText: i18n('cancel'),
  8463. showCancelButton: true
  8464. }).then(({
  8465. value
  8466. }) => {
  8467. if (value) {
  8468. window.close();
  8469. }
  8470. });
  8471. }
  8472. return true;
  8473. } catch (error) {
  8474. throwError(error, 'Giveawaysu.checkLeftKey');
  8475. return false;
  8476. }
  8477. }
  8478. }
  8479. const website_GiveeClub = GiveeClub;
  8480. const defaultOptions = {
  8481. maxPoint: '99999999'
  8482. };
  8483. class OpiumPulses {
  8484. name = 'OpiumPulses';
  8485. options = {
  8486. ...defaultOptions,
  8487. ...GM_getValue('OpiumPulsesOptions')
  8488. };
  8489. maxPoints = 99999999;
  8490. myPoints = 0;
  8491. buttons = [ 'doFreeTask', 'doPointTask' ];
  8492. static test() {
  8493. return window.location.host === 'www.opiumpulses.com';
  8494. }
  8495. async after() {
  8496. try {
  8497. if (!this.#checkLogin()) {
  8498. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8499. }
  8500. this.maxPoints = parseInt(this.options.maxPoint, 10);
  8501. } catch (error) {
  8502. throwError(error, 'OpiumPulses.after');
  8503. }
  8504. }
  8505. async doFreeTask() {
  8506. try {
  8507. this.#toggleTask('FREE');
  8508. } catch (error) {
  8509. throwError(error, 'OpiumPulses.doFreeTask');
  8510. }
  8511. }
  8512. async doPointTask() {
  8513. try {
  8514. this.myPoints = parseInt($('.page-header__nav-func-user-nav-items.points-items').text().match(/[\d]+/gim)?.[0] || '0', 10);
  8515. this.#toggleTask('points');
  8516. } catch (error) {
  8517. throwError(error, 'OpiumPulses.doPointTask');
  8518. }
  8519. }
  8520. async #toggleTask(type) {
  8521. try {
  8522. const items = $(`.giveaways-page-item:contains('${type}'):not(:contains('ENTERED'))`);
  8523. for (const item of items) {
  8524. const needPoints = parseInt($(item).find('.giveaways-page-item-header-points').text().match(/[\d]+/gim)?.[0] || '999999', 10);
  8525. const name = $(item).find('.giveaways-page-item-footer-name').text().trim();
  8526. if (type === 'points' && needPoints > this.myPoints) {
  8527. scripts_echoLog({}).warning(`${i18n('noPoints')}: ${name}`);
  8528. } else if (type === 'points' && !needPoints) {
  8529. scripts_echoLog({}).warning(`${i18n('getNeedPointsFailed')}: ${name}`);
  8530. } else if (!(type === 'points' && needPoints > this.maxPoints)) {
  8531. const logStatus = scripts_echoLog({
  8532. text: `${i18n('joiningLottery')}<a href="${$(item).find('a.giveaways-page-item-img-btn-more').attr('href')}" target="_blank">${name}</a>...`
  8533. });
  8534. const aElement = $(item).find('a.giveaways-page-item-img-btn-enter:contains(\'enter\')');
  8535. if (aElement?.attr('onclick')?.includes('checkUser')) {
  8536. const giveawayId = aElement.attr('onclick')?.match(/[\d]+/)?.[0];
  8537. if (giveawayId) {
  8538. checkUser(giveawayId);
  8539. }
  8540. }
  8541. if (!aElement.attr('href')) {
  8542. logStatus.error('Error: No "href".');
  8543. continue;
  8544. }
  8545. const {
  8546. result,
  8547. statusText,
  8548. status,
  8549. data
  8550. } = await tools_httpRequest({
  8551. url: aElement.attr('href'),
  8552. method: 'GET'
  8553. });
  8554. if (result === 'Success') {
  8555. const {
  8556. result: result0,
  8557. statusText: statusText0,
  8558. status: status0,
  8559. data: data0
  8560. } = await tools_httpRequest({
  8561. url: data?.finalUrl,
  8562. method: 'GET'
  8563. });
  8564. if (data0?.responseText && /You've entered this giveaway/gim.test(data0.responseText)) {
  8565. logStatus.success();
  8566. const points = data0.responseText.match(/Points:[\s]*?([\d]+)/)?.[1];
  8567. if (type === 'points' && points) {
  8568. this.myPoints = parseInt(points, 10);
  8569. }
  8570. } else if (data0?.responseText && /You're not eligible to enter/gim.test(data0.responseText)) {
  8571. logStatus.error('You\'re not eligible to enter');
  8572. } else {
  8573. logStatus.error(`${result0}:${statusText0}(${status0})`);
  8574. }
  8575. } else {
  8576. logStatus.error(`${result}:${statusText}(${status})`);
  8577. }
  8578. }
  8579. }
  8580. scripts_echoLog({
  8581. text: '-----END-----'
  8582. });
  8583. } catch (error) {
  8584. throwError(error, 'OpiumPulses.toggleTask');
  8585. }
  8586. }
  8587. init() {
  8588. return true;
  8589. }
  8590. classifyTask() {
  8591. return true;
  8592. }
  8593. #checkLogin() {
  8594. try {
  8595. if (!globalOptions.other.checkLogin) {
  8596. return true;
  8597. }
  8598. if ($('a[href*="/site/login"]').length > 1) {
  8599. window.open('/site/login', '_self');
  8600. }
  8601. return true;
  8602. } catch (error) {
  8603. throwError(error, 'OpiumPulses.checkLogin');
  8604. return false;
  8605. }
  8606. }
  8607. }
  8608. const website_OpiumPulses = OpiumPulses;
  8609. const external_dayjs_namespaceObject = dayjs;
  8610. var external_dayjs_default = __webpack_require__.n(external_dayjs_namespaceObject);
  8611. const leftKeyChecker = {
  8612. async classify(link) {
  8613. try {
  8614. if (/^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(link)) {
  8615. return await this.giveawaySu(link);
  8616. }
  8617. if (/^https?:\/\/givee\.club\/[\w]+?\/event\/[\d]+/.test(link)) {
  8618. return await this.giveeClub(link);
  8619. }
  8620. if (/^https?:\/\/gleam\.io\/.+?\/.+/.test(link)) {
  8621. return await this.gleam(link);
  8622. }
  8623. if (/^https?:\/\/www\.indiedb\.com\/giveaways\/.+/.test(link)) {
  8624. return await this.indieDb(link);
  8625. }
  8626. if (/^https?:\/\/key-hub\.eu\/giveaway\/[\d]+/.test(link)) {
  8627. return await this.keyhub(link);
  8628. }
  8629. if (/^https?:\/\/opquests\.com\/quests\/[\d]+/.test(link)) {
  8630. return await this.opquests(link);
  8631. }
  8632. if (/^https?:\/\/itch\.io\/s\/[\d]+?\/.*/.test(link)) {
  8633. return await this.itch(link);
  8634. }
  8635. return false;
  8636. } catch (error) {
  8637. throwError(error, 'leftKeyChecker.classify');
  8638. return false;
  8639. }
  8640. },
  8641. async giveawaySu(link) {
  8642. try {
  8643. const {
  8644. result,
  8645. data
  8646. } = await tools_httpRequest({
  8647. url: link,
  8648. method: 'GET'
  8649. });
  8650. if (result === 'Success' && data?.status === 200) {
  8651. if (data.responseText.includes('class="steam-login"')) {
  8652. return false;
  8653. }
  8654. if (data.responseText.includes('class="giveaway-ended"')) {
  8655. return 'Ended';
  8656. }
  8657. return 'Active';
  8658. }
  8659. return false;
  8660. } catch (error) {
  8661. throwError(error, 'leftKeyChecker.giveawaySu');
  8662. return false;
  8663. }
  8664. },
  8665. async giveeClub(link) {
  8666. try {
  8667. const {
  8668. result,
  8669. data
  8670. } = await tools_httpRequest({
  8671. url: link,
  8672. method: 'GET'
  8673. });
  8674. if (result === 'Success' && data?.status === 200) {
  8675. if (data.responseText.includes('class="event-winner"')) {
  8676. return 'Won';
  8677. }
  8678. if (data.responseText.includes('class="event-ended"')) {
  8679. return 'Ended';
  8680. }
  8681. return 'Active';
  8682. }
  8683. return false;
  8684. } catch (error) {
  8685. throwError(error, 'leftKeyChecker.giveeClub');
  8686. return false;
  8687. }
  8688. },
  8689. async gleam(link) {
  8690. try {
  8691. const {
  8692. result,
  8693. data
  8694. } = await tools_httpRequest({
  8695. url: link,
  8696. method: 'GET'
  8697. });
  8698. if (result === 'Success' && data?.status === 200) {
  8699. if (/incentives&quot;:{&quot;[\d]+?&quot;:\[&quot;.+?&quot;\]/.test(data.responseText)) {
  8700. return 'Won';
  8701. }
  8702. const campaignDiv = data.responseText.match(/<div class='popup-blocks-container'[\w\W]+?'>/)?.[0];
  8703. if (!campaignDiv) {
  8704. return false;
  8705. }
  8706. const campaignString = $(campaignDiv).attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  8707. if (!campaignString) {
  8708. return false;
  8709. }
  8710. const {
  8711. campaign
  8712. } = JSON.parse(campaignString);
  8713. if (campaign.banned) {
  8714. return 'Banned';
  8715. }
  8716. if (campaign.finished) {
  8717. return 'Ended';
  8718. }
  8719. if (campaign.paused) {
  8720. return 'Paused';
  8721. }
  8722. if (new Date().getTime() < campaign.starts_at * 1e3) {
  8723. return 'NotStart';
  8724. }
  8725. return 'Active';
  8726. }
  8727. return false;
  8728. } catch (error) {
  8729. throwError(error, 'leftKeyChecker.gleam');
  8730. return false;
  8731. }
  8732. },
  8733. async indieDb(link) {
  8734. try {
  8735. const {
  8736. result,
  8737. data
  8738. } = await tools_httpRequest({
  8739. url: link,
  8740. method: 'GET'
  8741. });
  8742. if (result === 'Success' && data?.status === 200) {
  8743. if (data.responseText.includes('Congrats you WON')) {
  8744. return 'Won';
  8745. }
  8746. if (data.responseText.includes('Giveaway is closed') || data.responseText.includes('next time')) {
  8747. return 'Ended';
  8748. }
  8749. return 'Active';
  8750. }
  8751. return false;
  8752. } catch (error) {
  8753. throwError(error, 'leftKeyChecker.indieDb');
  8754. return false;
  8755. }
  8756. },
  8757. async keyhub(link) {
  8758. try {
  8759. const {
  8760. result,
  8761. data
  8762. } = await tools_httpRequest({
  8763. url: link,
  8764. method: 'GET'
  8765. });
  8766. if (result === 'Success' && data?.status === 200) {
  8767. const keysleft = data.responseText.match(/<span id="keysleft">([\d]+?)<\/span>/)?.[1];
  8768. if (!keysleft) {
  8769. return false;
  8770. }
  8771. if (keysleft === '0') {
  8772. return 'Ended';
  8773. }
  8774. return `Active(${keysleft})`;
  8775. }
  8776. return false;
  8777. } catch (error) {
  8778. throwError(error, 'leftKeyChecker.keyhub');
  8779. return false;
  8780. }
  8781. },
  8782. async opquests(link) {
  8783. try {
  8784. const {
  8785. result,
  8786. data
  8787. } = await tools_httpRequest({
  8788. url: link,
  8789. method: 'GET'
  8790. });
  8791. if (result === 'Success' && data?.status === 200) {
  8792. const keysleft = data.responseText.match(/<div class="">[\s]*?([\d]+?)[\s]*?of/)?.[1];
  8793. if (!keysleft) {
  8794. return false;
  8795. }
  8796. if (keysleft === '0') {
  8797. return 'Ended';
  8798. }
  8799. return `Active(${keysleft})`;
  8800. } else if (data?.status === 404) {
  8801. return 'Ended';
  8802. }
  8803. return false;
  8804. } catch (error) {
  8805. throwError(error, 'leftKeyChecker.opquests');
  8806. return false;
  8807. }
  8808. },
  8809. async itch(link) {
  8810. try {
  8811. const {
  8812. result,
  8813. data
  8814. } = await tools_httpRequest({
  8815. url: link,
  8816. method: 'GET'
  8817. });
  8818. if (result === 'Success' && data?.status === 200) {
  8819. const endDate = data.responseText.match(/{"start_date":"[0-9A-Z-:]+?".*?"end_date":"([0-9A-Z-:]+?)".*?}/)?.[1];
  8820. if (!endDate) {
  8821. return false;
  8822. }
  8823. if (new Date().getTime() > new Date(endDate).getTime()) {
  8824. return 'Ended';
  8825. }
  8826. return `Active(${external_dayjs_default()(endDate).format('YYYY-MM-DD HH:mm:ss')})`;
  8827. }
  8828. return false;
  8829. } catch (error) {
  8830. throwError(error, 'leftKeyChecker.itch');
  8831. return false;
  8832. }
  8833. }
  8834. };
  8835. const website_leftKeyChecker = leftKeyChecker;
  8836. const Keylol_defaultTasksTemplate = {
  8837. steam: {
  8838. groupLinks: [],
  8839. wishlistLinks: [],
  8840. curatorLinks: [],
  8841. curatorLikeLinks: [],
  8842. followLinks: [],
  8843. forumLinks: [],
  8844. announcementLinks: [],
  8845. workshopVoteLinks: [],
  8846. licenseLinks: []
  8847. },
  8848. discord: {
  8849. serverLinks: []
  8850. },
  8851. instagram: {
  8852. userLinks: []
  8853. },
  8854. vk: {
  8855. nameLinks: []
  8856. },
  8857. twitch: {
  8858. channelLinks: []
  8859. },
  8860. reddit: {
  8861. redditLinks: []
  8862. },
  8863. twitter: {
  8864. userLinks: [],
  8865. retweetLinks: []
  8866. },
  8867. youtube: {
  8868. channelLinks: [],
  8869. likeLinks: []
  8870. }
  8871. };
  8872. const Keylol_defaultTasks = JSON.stringify(Keylol_defaultTasksTemplate);
  8873. class Keylol extends website_Website {
  8874. name = 'Keylol';
  8875. socialTasks = JSON.parse(Keylol_defaultTasks);
  8876. undoneTasks = JSON.parse(Keylol_defaultTasks);
  8877. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect' ];
  8878. static test() {
  8879. 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'));
  8880. }
  8881. init() {
  8882. return true;
  8883. }
  8884. after() {
  8885. try {
  8886. const selector = this.name === 'Keylol' ? '#postlist>div[id^="post_"]:first' : 'div.container';
  8887. const mainPost = $(selector);
  8888. const discordLinks = mainPost.find('a[href*="discord.com"]:visible');
  8889. const redditLinks = mainPost.find('a[href*="reddit.com"]:visible');
  8890. const insLinks = mainPost.find('a[href*="instagram.com"]:visible');
  8891. const twitterLinks = mainPost.find('a[href*="twitter.com"]:visible,a[href*="x.com"]:visible');
  8892. const twitchLinks = mainPost.find('a[href*="twitch.tv"]:visible');
  8893. const vkLinks = mainPost.find('a[href*="vk.com"]:visible');
  8894. const steamStoreLinks = mainPost.find('a[href*="store.steampowered.com"]:visible');
  8895. const steamCommunityLinks = mainPost.find('a[href*="steamcommunity.com"]:visible');
  8896. const ytbLinks = mainPost.find('a[href*="youtube.com"]:visible');
  8897. if (discordLinks.length > 0) {
  8898. for (const discordLink of discordLinks) {
  8899. const link = $(discordLink).attr('href');
  8900. if (!(link && /^https?:\/\/discord\.com\/invite\/.+/.test(link))) {
  8901. continue;
  8902. }
  8903. this.#addBtn(discordLink, 'discord', 'serverLinks', link);
  8904. }
  8905. }
  8906. if (redditLinks.length > 0) {
  8907. for (const redditLink of redditLinks) {
  8908. const link = $(redditLink).attr('href');
  8909. if (!(link && /^https?:\/\/www\.reddit\.com\/(r|user)\/.+/.test(link))) {
  8910. continue;
  8911. }
  8912. this.#addBtn(redditLink, 'reddit', 'redditLinks', link);
  8913. }
  8914. }
  8915. if (insLinks.length > 0) {
  8916. for (const insLink of insLinks) {
  8917. const link = $(insLink).attr('href');
  8918. if (!(link && /^https:\/\/www\.instagram\.com\/.+/.test(link))) {
  8919. continue;
  8920. }
  8921. this.#addBtn(insLink, 'instagram', 'userLinks', link);
  8922. }
  8923. }
  8924. if (twitterLinks.length > 0) {
  8925. for (const twitterLink of twitterLinks) {
  8926. const link = $(twitterLink).attr('href');
  8927. if (!(link && /^https:\/\/twitter\.com\/.+/.test(link))) {
  8928. continue;
  8929. }
  8930. if (/https:\/\/twitter\.com\/.*?\/status\/[\d]+/.test(link)) {
  8931. this.#addBtn(twitterLink, 'twitter', 'retweetLinks', link);
  8932. } else {
  8933. this.#addBtn(twitterLink, 'twitter', 'userLinks', link);
  8934. }
  8935. }
  8936. }
  8937. if (twitchLinks.length > 0) {
  8938. for (const twitchLink of twitchLinks) {
  8939. const link = $(twitchLink).attr('href');
  8940. if (!(link && /^https:\/\/(www\.)?twitch\.tv\/.+/.test(link))) {
  8941. continue;
  8942. }
  8943. this.#addBtn(twitchLink, 'twitch', 'channelLinks', link);
  8944. }
  8945. }
  8946. if (vkLinks.length > 0) {
  8947. for (const vkLink of vkLinks) {
  8948. const link = $(vkLink).attr('href');
  8949. if (!(link && /^https:\/\/vk\.com\/.+/.test(link))) {
  8950. continue;
  8951. }
  8952. this.#addBtn(vkLink, 'vk', 'nameLinks', link);
  8953. }
  8954. }
  8955. if (steamStoreLinks.length > 0) {
  8956. for (const steamStoreLink of steamStoreLinks) {
  8957. const link = $(steamStoreLink).attr('href');
  8958. if (!link) {
  8959. continue;
  8960. }
  8961. if (/curator\/[\d]+/.test(link)) {
  8962. this.#addBtn(steamStoreLink, 'steam', 'curatorLinks', link);
  8963. } else if (/(publisher|developer|franchise)\/.+/.test(link)) {
  8964. this.#addBtn(steamStoreLink, 'steam', 'curatorLikeLinks', link);
  8965. } else if (/news(hub)?\/app\/[\d]+\/view\/[\d]+/.test(link)) {
  8966. this.#addBtn(steamStoreLink, 'steam', 'announcementLinks', link);
  8967. } else if (/app\/[\d]+/.test(link)) {
  8968. this.#addBtn(steamStoreLink, 'steam', 'followLinks', link);
  8969. this.#addBtn(steamStoreLink, 'steam', 'wishlistLinks', link);
  8970. }
  8971. }
  8972. }
  8973. if (steamCommunityLinks.length > 0) {
  8974. for (const steamCommunityLink of steamCommunityLinks) {
  8975. const link = $(steamCommunityLink).attr('href');
  8976. if (!link) {
  8977. continue;
  8978. }
  8979. if (/groups\/.+/.test(link)) {
  8980. this.#addBtn(steamCommunityLink, 'steam', 'groupLinks', link);
  8981. } else if (/announcements\/detail\/[\d]+/.test(link)) {
  8982. this.#addBtn(steamCommunityLink, 'steam', 'announcementLinks', link);
  8983. }
  8984. }
  8985. }
  8986. if (ytbLinks.length > 0) {
  8987. for (const ytbLink of ytbLinks) {
  8988. const link = $(ytbLink).attr('href');
  8989. if (!link) {
  8990. continue;
  8991. }
  8992. this.#addBtn(ytbLink, 'youtube', 'channelLinks', link);
  8993. this.#addBtn(ytbLink, 'youtube', 'likeLinks', link);
  8994. }
  8995. }
  8996. 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');
  8997. if (giveawayLinks.length > 0) {
  8998. for (const giveawayLink of giveawayLinks) {
  8999. const link = $(giveawayLink).attr('href');
  9000. if (!link) {
  9001. continue;
  9002. }
  9003. website_leftKeyChecker.classify(link).then(status => {
  9004. if (!status) {
  9005. return;
  9006. }
  9007. if (/^Active/.test(status)) {
  9008. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status active" title="${i18n('Active')}">${status}</font>`);
  9009. return;
  9010. }
  9011. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status not-active" title="${i18n(status)}">${status}</font>`);
  9012. }).catch(error => {
  9013. throwError(error, 'keylol.after -> leftKeyChecker');
  9014. });
  9015. }
  9016. }
  9017. if (this.name === 'Keylol') {
  9018. const asfLinks = mainPost.find('a[href^="#asf"]:visible');
  9019. if (asfLinks.length > 0) {
  9020. for (const asfLink of asfLinks) {
  9021. const link = $(asfLink).attr('href');
  9022. if (!link) {
  9023. continue;
  9024. }
  9025. this.#addBtn($(`a[href="${link}"]`).after('<span style="color: #ccc; margin: 0 -5px 0 5px"> | </span>').next()[0], 'steam', 'licenseLinks', `appid-${link.replace('#asf', '')}`);
  9026. }
  9027. }
  9028. const subLinks = mainPost.find('a[href*="steamdb.info/sub/"]:visible');
  9029. if (subLinks.length > 0) {
  9030. for (const subLink of subLinks) {
  9031. const link = $(subLink).attr('href');
  9032. if (!link) {
  9033. continue;
  9034. }
  9035. const subid = link.match(/^https:\/\/steamdb\.info\/sub\/([\d]+)/)?.[1];
  9036. if (!subid) {
  9037. continue;
  9038. }
  9039. this.#addBtn(subLink, 'steam', 'licenseLinks', `subid-${subid}`);
  9040. }
  9041. }
  9042. const asfLinks2 = mainPost.find('.blockcode:contains("addlicense"):visible');
  9043. if (asfLinks2.length > 0) {
  9044. for (const asfLink of asfLinks2) {
  9045. const appid = [ ...asfLink.innerText.matchAll(/a(pp)?\/([\d]+)/g) ].map(matched => matched?.[2]).filter(id => id) || [];
  9046. if (appid.length > 0) {
  9047. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `appid-${appid.join(',')}`);
  9048. }
  9049. const subid = asfLink.innerText.match(/[\d]+/g)?.filter(matched => !appid.includes(matched));
  9050. if (!subid || subid.length === 0) {
  9051. continue;
  9052. }
  9053. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `subid-${subid.join(',')}`);
  9054. }
  9055. }
  9056. }
  9057. if ($('#threadindex').length > 0) {
  9058. const [ targetNode ] = $('#postlist').children('div[id^="post_"]');
  9059. const config = {
  9060. childList: true
  9061. };
  9062. const observer = new MutationObserver(() => {
  9063. observer.disconnect();
  9064. this.after();
  9065. });
  9066. observer.observe(targetNode, config);
  9067. }
  9068. } catch (error) {
  9069. throwError(error, 'keylol.after');
  9070. }
  9071. }
  9072. classifyTask(action) {
  9073. try {
  9074. this.socialTasks = JSON.parse(Keylol_defaultTasks);
  9075. this.undoneTasks = JSON.parse(Keylol_defaultTasks);
  9076. const selectedBtns = $('.auto-task-keylol[selected="selected"]:visible');
  9077. for (const btn of selectedBtns) {
  9078. const button = $(btn);
  9079. const social = button.attr('data-social');
  9080. const type = button.attr('data-type');
  9081. const link = button.attr('data-link');
  9082. if (!(social && type && link)) {
  9083. continue;
  9084. }
  9085. if (action === 'do') {
  9086. this.undoneTasks[social][type].push(link);
  9087. }
  9088. if (action === 'undo') {
  9089. this.socialTasks[social][type].push(link);
  9090. }
  9091. }
  9092. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9093. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9094. if (window.DEBUG) {
  9095. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9096. }
  9097. return true;
  9098. } catch (error) {
  9099. throwError(error, 'Keylol.classifyTask');
  9100. return false;
  9101. }
  9102. }
  9103. selectAll() {
  9104. try {
  9105. $('.auto-task-keylol:visible').attr('selected', 'selected');
  9106. } catch (error) {
  9107. throwError(error, 'Keylol.selectAll');
  9108. }
  9109. }
  9110. selectNone() {
  9111. try {
  9112. $('.auto-task-keylol:visible').removeAttr('selected');
  9113. } catch (error) {
  9114. throwError(error, 'Keylol.selectNone');
  9115. }
  9116. }
  9117. invertSelect() {
  9118. try {
  9119. $('.auto-task-keylol:visible').each((index, element) => {
  9120. element.getAttribute('selected') ? element.removeAttribute('selected') : element.setAttribute('selected', 'selected');
  9121. });
  9122. } catch (error) {
  9123. throwError(error, 'Keylol.invertSelect');
  9124. }
  9125. }
  9126. #addBtn(before, social, linkType, link) {
  9127. try {
  9128. $(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>`);
  9129. } catch (error) {
  9130. throwError(error, 'keylol.addBtn');
  9131. }
  9132. }
  9133. }
  9134. const website_Keylol = Keylol;
  9135. const Opquests_defaultTasks = {
  9136. steam: {
  9137. groupLinks: [],
  9138. wishlistLinks: [],
  9139. followLinks: [],
  9140. curatorLikeLinks: []
  9141. }
  9142. };
  9143. class Opquests extends website_Website {
  9144. name = 'Opquests';
  9145. undoneTasks = {
  9146. ...Opquests_defaultTasks
  9147. };
  9148. buttons = [ 'doTask', 'verifyTask', 'getKey' ];
  9149. static test() {
  9150. return window.location.host === 'opquests.com';
  9151. }
  9152. async before() {
  9153. try {
  9154. const opquestsVerifyTasks = GM_getValue('opquestsVerifyTasks') || [];
  9155. if (opquestsVerifyTasks.length > 0) {
  9156. const taskId = opquestsVerifyTasks.pop();
  9157. GM_setValue('opquestsVerifyTasks', opquestsVerifyTasks);
  9158. const [ verifyBtn ] = $(`#task_id[value="${taskId}"]`).parent().find('button[type="button"]').has('i.fa-check');
  9159. if (verifyBtn) {
  9160. verifyBtn.click();
  9161. return;
  9162. }
  9163. this.before();
  9164. return;
  9165. }
  9166. if (GM_getValue('opquestsVerifyTasks')) {
  9167. GM_deleteValue('opquestsVerifyTasks');
  9168. }
  9169. } catch (error) {
  9170. throwError(error, 'Opquests.before');
  9171. }
  9172. }
  9173. async after() {
  9174. try {
  9175. if (!this.#checkLogin()) {
  9176. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9177. }
  9178. } catch (error) {
  9179. throwError(error, 'Opquests.after');
  9180. }
  9181. }
  9182. init() {
  9183. try {
  9184. const logStatus = scripts_echoLog({
  9185. text: i18n('initing')
  9186. });
  9187. if ($('a[href*="/auth/redirect"]').length > 0) {
  9188. window.open('/auth/redirect', '_self');
  9189. logStatus.warning(i18n('needLogin'));
  9190. return false;
  9191. }
  9192. if (!this.#getGiveawayId()) {
  9193. return false;
  9194. }
  9195. this.initialized = true;
  9196. logStatus.success();
  9197. return true;
  9198. } catch (error) {
  9199. throwError(error, 'Opquests.init');
  9200. return false;
  9201. }
  9202. }
  9203. async classifyTask(action) {
  9204. try {
  9205. if (action === 'undo') {
  9206. scripts_echoLog({
  9207. text: i18n('cannotUndo')
  9208. });
  9209. return false;
  9210. }
  9211. const logStatus = scripts_echoLog({
  9212. text: i18n('getTasksInfo')
  9213. });
  9214. const tasks = $('.w-full:contains("Validate") .items-center');
  9215. for (const task of tasks) {
  9216. const link = $(task).find('a:contains("Open")').attr('href');
  9217. const taskDes = $(task).find('div').eq(1).text().trim();
  9218. if (!link) {
  9219. continue;
  9220. }
  9221. if (/steamcommunity\.com\/groups\//.test(link)) {
  9222. this.undoneTasks.steam.groupLinks.push(link);
  9223. } else if (/store\.steampowered\.com\/app\//.test(link)) {
  9224. if (/wishlist/gim.test(taskDes)) {
  9225. this.undoneTasks.steam.wishlistLinks.push(link);
  9226. } else if (/follow/gim.test(taskDes)) {
  9227. this.undoneTasks.steam.followLinks.push(link);
  9228. }
  9229. } else if (/store\.steampowered\.com\/(publisher|developer|curator)\//.test(link) && /follow/gim.test(taskDes)) {
  9230. this.undoneTasks.steam.curatorLikeLinks.push(link);
  9231. } else {
  9232. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  9233. }
  9234. }
  9235. logStatus.success();
  9236. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9237. if (window.DEBUG) {
  9238. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9239. }
  9240. return true;
  9241. } catch (error) {
  9242. throwError(error, 'Opquests.classifyTask');
  9243. return false;
  9244. }
  9245. }
  9246. async verifyTask() {
  9247. try {
  9248. if (!this.initialized) {
  9249. this.init();
  9250. }
  9251. const tasks = $.makeArray($('.items-center').has('input[name="task_id"]')).map(ele => $(ele).find('input[name="task_id"]').val());
  9252. GM_setValue('opquestsVerifyTasks', tasks);
  9253. await this.#confirm();
  9254. this.before();
  9255. return true;
  9256. } catch (error) {
  9257. throwError(error, 'Opquests.verifyTask');
  9258. return false;
  9259. }
  9260. }
  9261. async #confirm() {
  9262. try {
  9263. const logStatus = scripts_echoLog({
  9264. html: `<li>${i18n('confirmingTask')}...<font></font></li>`
  9265. });
  9266. const {
  9267. result,
  9268. statusText,
  9269. status,
  9270. data
  9271. } = await tools_httpRequest({
  9272. url: `https://opquests.com/quests/${this.giveawayId}?confirm=1`,
  9273. method: 'GET',
  9274. nochche: true,
  9275. headers: {
  9276. origin: 'https://opquests.com',
  9277. referer: `https://opquests.com/warning?id=${this.giveawayId}`
  9278. }
  9279. });
  9280. if (result === 'Success') {
  9281. if (data?.status === 200) {
  9282. logStatus.success();
  9283. return true;
  9284. }
  9285. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9286. return false;
  9287. }
  9288. logStatus.error(`${result}:${statusText}(${status})`);
  9289. return false;
  9290. } catch (error) {
  9291. throwError(error, 'Opquests.confirm');
  9292. return false;
  9293. }
  9294. }
  9295. async getKey(isButton) {
  9296. try {
  9297. const logStatus = scripts_echoLog({
  9298. text: i18n('gettingKey')
  9299. });
  9300. const {
  9301. result,
  9302. statusText,
  9303. status,
  9304. data
  9305. } = await tools_httpRequest({
  9306. url: 'https://opquests.com/keys',
  9307. method: 'GET'
  9308. });
  9309. if (result === 'Success') {
  9310. if (data?.responseText) {
  9311. const key = $(data?.responseText).find(`div.items-center:contains("${$('h1.font-bold').text().trim().replace(' Quest', '')}")`).find('div.font-bold').next().text();
  9312. if (!key) {
  9313. logStatus.error('Error: Key was not found');
  9314. if (isButton) {
  9315. window.open('https://opquests.com/keys', '_self');
  9316. }
  9317. return false;
  9318. }
  9319. logStatus.success();
  9320. scripts_echoLog({}).success(key);
  9321. return true;
  9322. }
  9323. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9324. return false;
  9325. }
  9326. logStatus.error(`${result}:${statusText}(${status})`);
  9327. return false;
  9328. } catch (error) {
  9329. throwError(error, 'Opquests.getGiveawayId');
  9330. return false;
  9331. }
  9332. }
  9333. #getGiveawayId() {
  9334. try {
  9335. const giveawayId = window.location.href.match(/quests\/([\d]+)/)?.[1];
  9336. if (giveawayId) {
  9337. this.giveawayId = giveawayId;
  9338. return true;
  9339. }
  9340. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  9341. return false;
  9342. } catch (error) {
  9343. throwError(error, 'Opquests.getGiveawayId');
  9344. return false;
  9345. }
  9346. }
  9347. #checkLogin() {
  9348. try {
  9349. if (!globalOptions.other.checkLogin) {
  9350. return true;
  9351. }
  9352. if ($('a[href*="/auth/redirect"]').length > 0) {
  9353. window.open('/auth/redirect', '_self');
  9354. }
  9355. return true;
  9356. } catch (error) {
  9357. throwError(error, 'Opquests.checkLogin');
  9358. return false;
  9359. }
  9360. }
  9361. }
  9362. const website_Opquests = Opquests;
  9363. const Gleam_defaultTasksTemplate = {
  9364. steam: {
  9365. groupLinks: [],
  9366. wishlistLinks: [],
  9367. followLinks: [],
  9368. curatorLinks: [],
  9369. curatorLikeLinks: []
  9370. },
  9371. twitter: {
  9372. userLinks: [],
  9373. retweetLinks: []
  9374. },
  9375. twitch: {
  9376. channelLinks: []
  9377. },
  9378. discord: {
  9379. serverLinks: []
  9380. },
  9381. youtube: {
  9382. channelLinks: []
  9383. },
  9384. extra: {
  9385. gleam: []
  9386. }
  9387. };
  9388. const Gleam_defaultTasks = JSON.stringify(Gleam_defaultTasksTemplate);
  9389. class Gleam extends website_Website {
  9390. name = 'Gleam';
  9391. undoneTasks = JSON.parse(Gleam_defaultTasks);
  9392. socialTasks = JSON.parse(Gleam_defaultTasks);
  9393. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  9394. static test() {
  9395. return window.location.host === 'gleam.io';
  9396. }
  9397. before() {
  9398. try {
  9399. unsafeWindow.confirm = () => {};
  9400. unsafeWindow.alert = () => {};
  9401. unsafeWindow.prompt = () => {};
  9402. } catch (error) {
  9403. throwError(error, 'Gleam.before');
  9404. }
  9405. }
  9406. async after() {
  9407. try {
  9408. if (window.location.search.includes('8b07d23f4bfa65f9')) {
  9409. const checkComplete = setInterval(() => {
  9410. if ($('.entry-content .entry-method i.fa-check').length > 0) {
  9411. clearInterval(checkComplete);
  9412. window.close();
  9413. }
  9414. });
  9415. for (const task of $('.entry-content .entry-method')) {
  9416. const taskInfo = $(task).find('.user-links');
  9417. const expandInfo = $(task).find('.expandable');
  9418. const aElements = expandInfo.find('a.btn,a:contains(Continue),button:contains(Continue)');
  9419. if (aElements.length > 0) {
  9420. for (const element of aElements) {
  9421. const $element = $(element);
  9422. const href = $element.attr('href');
  9423. $element.removeAttr('href')[0].click();
  9424. $element.attr('href', href);
  9425. await delay(1e3);
  9426. }
  9427. }
  9428. taskInfo[0].click();
  9429. await delay(1e3);
  9430. }
  9431. scripts_echoLog({}).warning(i18n('gleamTaskNotice'));
  9432. } else if (!await this.#checkLeftKey()) {
  9433. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  9434. }
  9435. } catch (error) {
  9436. throwError(error, 'Gleam.after');
  9437. }
  9438. }
  9439. init() {
  9440. try {
  9441. const logStatus = scripts_echoLog({
  9442. text: i18n('initing')
  9443. });
  9444. if (!this.#getGiveawayId()) {
  9445. return false;
  9446. }
  9447. this.initialized = true;
  9448. logStatus.success();
  9449. return true;
  9450. } catch (error) {
  9451. throwError(error, 'Gleam.init');
  9452. return false;
  9453. }
  9454. }
  9455. async classifyTask(action) {
  9456. try {
  9457. const logStatus = scripts_echoLog({
  9458. text: i18n('getTasksInfo')
  9459. });
  9460. if (action === 'undo') {
  9461. this.socialTasks = GM_getValue(`gleamTasks-${this.giveawayId}`)?.tasks || JSON.parse(Gleam_defaultTasks);
  9462. }
  9463. const tasks = $('.entry-content .entry-method');
  9464. for (const task of tasks) {
  9465. const $task = $(task);
  9466. if (action === 'do' && $task.find('i.fa-question').length === 0) {
  9467. continue;
  9468. }
  9469. const socialIcon = $task.find('.icon-wrapper i');
  9470. const taskInfo = $task.find('.user-links');
  9471. const taskText = taskInfo.text().trim();
  9472. const expandInfo = $task.find('.expandable');
  9473. const aElements = expandInfo.find('a.btn');
  9474. if (aElements.length > 0) {
  9475. for (const element of aElements) {
  9476. const $element = $(element);
  9477. const href = $element.attr('href');
  9478. $element.removeAttr('href')[0].click();
  9479. $element.attr('href', href);
  9480. }
  9481. }
  9482. if (socialIcon.hasClass('fa-twitter') || socialIcon.hasClass('fa-x-twitter')) {
  9483. const link = $task.find('a[href^="https://twitter.com/"],a[href^="https://x.com/"]').attr('href');
  9484. if (!link) {
  9485. continue;
  9486. }
  9487. if (/follow/gi.test(taskText)) {
  9488. if (action === 'undo') {
  9489. this.socialTasks.twitter.userLinks.push(link);
  9490. }
  9491. if (action === 'do') {
  9492. this.undoneTasks.twitter.userLinks.push(link);
  9493. }
  9494. } else if (/retweet/gim.test(taskText)) {
  9495. if (action === 'undo') {
  9496. this.socialTasks.twitter.retweetLinks.push(link);
  9497. }
  9498. if (action === 'do') {
  9499. this.undoneTasks.twitter.retweetLinks.push(link);
  9500. }
  9501. }
  9502. } else if (socialIcon.hasClass('fa-twitch')) {
  9503. if (/follow/gim.test(taskText)) {
  9504. const link = $task.find('a[href^="https://twitch.tv/"]').attr('href');
  9505. if (!link) {
  9506. continue;
  9507. }
  9508. if (action === 'undo') {
  9509. this.socialTasks.twitch.channelLinks.push(link);
  9510. }
  9511. if (action === 'do') {
  9512. this.undoneTasks.twitch.channelLinks.push(link);
  9513. }
  9514. }
  9515. } else if (socialIcon.hasClass('fa-discord')) {
  9516. if (/join/gim.test(taskText)) {
  9517. let link = $task.find('a[href^="https://discord.com/invite/"]').attr('href');
  9518. if (!link) {
  9519. const ggLink = $task.find('a[href^="https://discord.gg/"]').attr('href')?.match(/discord\.gg\/([^/]+)/)?.[1];
  9520. if (!ggLink) {
  9521. continue;
  9522. }
  9523. link = `https://discord.com/invite/${ggLink}`;
  9524. }
  9525. if (action === 'undo') {
  9526. this.socialTasks.discord.serverLinks.push(link);
  9527. }
  9528. if (action === 'do') {
  9529. this.undoneTasks.discord.serverLinks.push(link);
  9530. }
  9531. }
  9532. } else if (socialIcon.hasClass('fa-external-link-square-alt')) {
  9533. continue;
  9534. } else if (socialIcon.hasClass('fa-youtube')) {
  9535. if (/subscribe/gim.test(taskText)) {
  9536. const link = $task.find('a[href^="https://www.youtube.com/channel/"]').attr('href');
  9537. if (!link) {
  9538. continue;
  9539. }
  9540. if (action === 'undo') {
  9541. this.socialTasks.youtube.channelLinks.push(link);
  9542. }
  9543. if (action === 'do') {
  9544. this.undoneTasks.youtube.channelLinks.push(link);
  9545. }
  9546. }
  9547. } else if (socialIcon.attr('class')?.includes('steam')) {
  9548. if (/join.*group/gi.test(taskText)) {
  9549. const link = $task.find('a[href^="https://steamcommunity.com/groups/"]').attr('href');
  9550. if (!link) {
  9551. continue;
  9552. }
  9553. if (action === 'undo') {
  9554. this.socialTasks.steam.groupLinks.push(link);
  9555. }
  9556. if (action === 'do') {
  9557. this.undoneTasks.steam.groupLinks.push(link);
  9558. }
  9559. } else if (/follow.*curator/gi.test(taskText)) {
  9560. const link = $task.find('a[href^="https://store.steampowered.com/curator/"]').attr('href');
  9561. if (!link) {
  9562. continue;
  9563. }
  9564. if (action === 'undo') {
  9565. this.socialTasks.steam.curatorLinks.push(link);
  9566. }
  9567. if (action === 'do') {
  9568. this.undoneTasks.steam.curatorLinks.push(link);
  9569. }
  9570. }
  9571. } else if (socialIcon.hasClass('fa-bullhorn') && /Complete/gi.test(taskText)) {
  9572. if (action !== 'do') {
  9573. continue;
  9574. }
  9575. const gleamLink = await this.#getGleamLink(taskText);
  9576. if (!gleamLink) {
  9577. continue;
  9578. }
  9579. this.undoneTasks.extra.gleam.push(gleamLink);
  9580. } 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 {
  9581. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskText}`);
  9582. }
  9583. }
  9584. logStatus.success();
  9585. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9586. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9587. if (window.DEBUG) {
  9588. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9589. }
  9590. GM_setValue(`gleamTasks-${this.giveawayId}`, {
  9591. tasks: this.socialTasks,
  9592. time: new Date().getTime()
  9593. });
  9594. return true;
  9595. } catch (error) {
  9596. throwError(error, 'Gleam.classifyTask');
  9597. return false;
  9598. }
  9599. }
  9600. async extraDoTask({
  9601. gleam
  9602. }) {
  9603. try {
  9604. const pro = [];
  9605. for (const link of gleam) {
  9606. pro.push(this.#doGleamTask(link));
  9607. }
  9608. return Promise.all(pro).then(() => true);
  9609. } catch (error) {
  9610. throwError(error, 'Gleam.extraDoTask');
  9611. return false;
  9612. }
  9613. }
  9614. async verifyTask() {
  9615. try {
  9616. scripts_echoLog({
  9617. text: `${i18n('verifyingTask')}...`
  9618. });
  9619. const tasks = $('.entry-content .entry-method');
  9620. unsafeWindow._OxA = '_OxA';
  9621. for (const task of tasks) {
  9622. if ($('[campaign-key="campaign.key"]').length > 0) {
  9623. return scripts_echoLog({
  9624. text: i18n('campaign')
  9625. });
  9626. }
  9627. const $task = $(task);
  9628. if ($task.find('i.fa-question').length === 0) {
  9629. continue;
  9630. }
  9631. const taskInfo = $task.find('.user-links');
  9632. taskInfo[0].click();
  9633. const aElements = $task.find('.expandable').find('a.btn');
  9634. if (aElements.length > 0) {
  9635. for (const element of aElements) {
  9636. const $element = $(element);
  9637. const href = $element.attr('href');
  9638. $element.removeAttr('href')[0].click();
  9639. $element.attr('href', href);
  9640. }
  9641. }
  9642. unsafeWindow.$hookTimer?.setSpeed(1e3);
  9643. const visitBtn = $task.find('.expandable').find('span:contains(more seconds),button:contains(more seconds)').filter(':visible');
  9644. if (visitBtn.length > 0 && unsafeWindow.$hookTimer) {
  9645. const newTab = GM_openInTab('', {
  9646. active: true
  9647. });
  9648. await delay(1e3);
  9649. newTab?.close();
  9650. window.focus();
  9651. }
  9652. await delay(3e3);
  9653. unsafeWindow.$hookTimer?.setSpeed(1);
  9654. const expandInfo = $task.find('.expandable');
  9655. const [ input ] = expandInfo.find('input');
  9656. if (input) {
  9657. const evt = new Event('input', {
  9658. bubbles: true,
  9659. cancelable: true,
  9660. composed: true
  9661. });
  9662. const valuelimit = [ ...expandInfo.text().matchAll(/"(.+?)"/g) ].at(-1)?.[1];
  9663. input.value = valuelimit || 'vloot';
  9664. input.dispatchEvent(evt);
  9665. await delay(1e3);
  9666. }
  9667. await this.#checkSync();
  9668. const continueBtn = $task.find('.expandable').find('span:contains(Continue),button:contains(Continue)');
  9669. for (const button of continueBtn) {
  9670. button.click();
  9671. await delay(500);
  9672. await this.#checkSync();
  9673. }
  9674. }
  9675. scripts_echoLog({
  9676. text: i18n('verifiedGleamTasks')
  9677. });
  9678. } catch (error) {
  9679. throwError(error, 'Gleam.verifyTask');
  9680. return false;
  9681. }
  9682. }
  9683. async #checkSync() {
  9684. try {
  9685. return await new Promise(resolve => {
  9686. const checker = setInterval(() => {
  9687. if ($('.entry-content .entry-method i.fa-sync').length === 0) {
  9688. clearInterval(checker);
  9689. resolve(true);
  9690. }
  9691. }, 500);
  9692. });
  9693. } catch (error) {
  9694. throwError(error, 'Gleam.checkSync');
  9695. return false;
  9696. }
  9697. }
  9698. async #doGleamTask(link) {
  9699. try {
  9700. const logStatus = scripts_echoLog({
  9701. text: i18n('doingGleamTask')
  9702. });
  9703. return await new Promise(resolve => {
  9704. GM_openInTab(`${link}?8b07d23f4bfa65f9`, {
  9705. active: true,
  9706. insert: true,
  9707. setParent: true
  9708. }).onclose = () => {
  9709. logStatus.success();
  9710. resolve(true);
  9711. };
  9712. });
  9713. } catch (error) {
  9714. throwError(error, 'Gleam.doGleamTask');
  9715. return false;
  9716. }
  9717. }
  9718. #getGiveawayId() {
  9719. try {
  9720. const giveawayId = window.location.pathname;
  9721. if (giveawayId) {
  9722. this.giveawayId = giveawayId;
  9723. return true;
  9724. }
  9725. scripts_echoLog({
  9726. text: i18n('getFailed', 'GiveawayId')
  9727. });
  9728. return false;
  9729. } catch (error) {
  9730. throwError(error, 'Gleam.getGiveawayId');
  9731. return false;
  9732. }
  9733. }
  9734. async #getGleamLink(title) {
  9735. try {
  9736. const logStatus = scripts_echoLog({
  9737. text: i18n('gettingGleamLink')
  9738. });
  9739. const {
  9740. result,
  9741. statusText,
  9742. status,
  9743. data
  9744. } = await tools_httpRequest({
  9745. url: 'https://www.vloot.io/api/v1/giveaways',
  9746. method: 'GET',
  9747. responseType: 'json'
  9748. });
  9749. if (result === 'Success') {
  9750. if (data?.status === 200 && data?.response?.Success === true && data?.response?.Data) {
  9751. const {
  9752. link
  9753. } = data.response.Data.find(giveaway => title.replace(/[\s]/g, '').toLowerCase().includes(giveaway.title.replace(/[\s]/g, '').toLowerCase())) || {};
  9754. if (link) {
  9755. logStatus.success();
  9756. return link;
  9757. }
  9758. logStatus.error(`Error:${i18n('getLinkFailed')}`);
  9759. return false;
  9760. }
  9761. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9762. return false;
  9763. }
  9764. logStatus.error(`${result}:${statusText}(${status})`);
  9765. return false;
  9766. } catch (error) {
  9767. throwError(error, 'Gleam.getGleamLink');
  9768. return false;
  9769. }
  9770. }
  9771. async #checkLeftKey() {
  9772. try {
  9773. if (!globalOptions.other.checkLeftKey) {
  9774. return true;
  9775. }
  9776. const campaignString = $('div.popup-blocks-container').attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  9777. if (!campaignString) {
  9778. return false;
  9779. }
  9780. const {
  9781. campaign,
  9782. incentive
  9783. } = JSON.parse(campaignString);
  9784. const controllerString = $('div.campaign.reward').attr('ng-init')?.match(/initContestant\(([\w\W]+?)\);/)?.[1];
  9785. let ownedKey = false;
  9786. if (controllerString) {
  9787. if (JSON.parse(controllerString).contestant?.claims?.incentives?.[incentive.id]?.length) {
  9788. ownedKey = true;
  9789. }
  9790. }
  9791. if (campaign.banned || campaign.finished && !ownedKey || campaign.paused || new Date().getTime() < campaign.starts_at * 1e3) {
  9792. await external_Swal_default().fire({
  9793. icon: 'warning',
  9794. title: i18n('notice'),
  9795. text: i18n('giveawayNotWork'),
  9796. confirmButtonText: i18n('confirm'),
  9797. cancelButtonText: i18n('cancel'),
  9798. showCancelButton: true
  9799. }).then(({
  9800. value
  9801. }) => {
  9802. if (value) {
  9803. window.close();
  9804. }
  9805. });
  9806. }
  9807. return true;
  9808. } catch (error) {
  9809. throwError(error, 'Gleam.checkLeftKey');
  9810. return false;
  9811. }
  9812. }
  9813. }
  9814. const website_Gleam = Gleam;
  9815. const SweepWidget_defaultOptions = {
  9816. username: '',
  9817. email: ''
  9818. };
  9819. class SweepWidget extends website_Website {
  9820. name = 'SweepWidget';
  9821. options = {
  9822. ...SweepWidget_defaultOptions,
  9823. ...GM_getValue('SweepWidgetOptions')
  9824. };
  9825. buttons = [ 'doTask' ];
  9826. static test() {
  9827. return /^https?:\/\/sweepwidget\.com\/view\/[\d]+/.test(window.location.href);
  9828. }
  9829. async after() {
  9830. try {
  9831. if (!this.#checkLogin()) {
  9832. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9833. }
  9834. } catch (error) {
  9835. throwError(error, 'SweepWidget.after');
  9836. }
  9837. }
  9838. init() {
  9839. try {
  9840. const logStatus = scripts_echoLog({
  9841. text: i18n('initing')
  9842. });
  9843. if (!this.#checkLogin()) {
  9844. logStatus.warning(i18n('needLogin'));
  9845. return false;
  9846. }
  9847. if (!this.#getGiveawayId()) {
  9848. return false;
  9849. }
  9850. this.initialized = true;
  9851. logStatus.success();
  9852. return true;
  9853. } catch (error) {
  9854. throwError(error, 'SweepWidget.init');
  9855. return false;
  9856. }
  9857. }
  9858. classifyTask() {
  9859. return true;
  9860. }
  9861. async doTask() {
  9862. try {
  9863. if ($('#unlock_rewards_main_wrapper').length === 0) {
  9864. if ($('input[name="sw__login_name"]:visible').length > 0) {
  9865. $('input[name="sw__login_name"]').val(this.options.username);
  9866. }
  9867. if ($('input[name="sw__login_email"]:visible').length > 0) {
  9868. $('input[name="sw__login_email"]').val(this.options.email);
  9869. }
  9870. if ($('#sw_login_button:visible').length > 0) {
  9871. $('#sw_login_button')[0].click();
  9872. }
  9873. if (!await this.#checkEnter()) {
  9874. return false;
  9875. }
  9876. }
  9877. const logStatus = scripts_echoLog({
  9878. text: i18n('SweepWidgetNotice')
  9879. });
  9880. const tasks = $('#sw_inner_entry_methods_l2_wrapper>div.sw_entry');
  9881. for (const task of tasks) {
  9882. const $task = $(task);
  9883. if ($task.find('i.fa-check:visible').length > 0) {
  9884. continue;
  9885. }
  9886. const title = $task.find('.sw_text_inner');
  9887. title[0].click();
  9888. const aElement = $task.find('a.sw_link');
  9889. const link = aElement.attr('href');
  9890. aElement.attr('href', '#a').attr('target', '_self');
  9891. aElement[0]?.click();
  9892. await delay(300);
  9893. aElement.attr('href', link).attr('target', '_blank');
  9894. $task.find('input[type="text"]').val('test');
  9895. const verifyBtn = $task.find('input.sw_verify');
  9896. if (verifyBtn.prop('disabled') === true) {
  9897. title[0].click();
  9898. await delay(300);
  9899. title[0].click();
  9900. await delay(300);
  9901. }
  9902. $task.find('input.sw_verify').removeAttr('disabled')[0]?.click();
  9903. await this.#checkFinish($task);
  9904. await delay(parseInt(`${Math.random() * (3e3 - 1e3 + 1) + 1e3}`, 10));
  9905. }
  9906. logStatus.success();
  9907. return true;
  9908. } catch (error) {
  9909. throwError(error, 'SweepWidget.doTask');
  9910. return false;
  9911. }
  9912. }
  9913. #checkLogin() {
  9914. try {
  9915. if ($('#twitter_login_button').length > 0) {
  9916. $('#twitter_login_button')[0].click();
  9917. }
  9918. return true;
  9919. } catch (error) {
  9920. throwError(error, 'SweepWidget.checkLogin');
  9921. return false;
  9922. }
  9923. }
  9924. #getGiveawayId() {
  9925. try {
  9926. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  9927. if (giveawayId) {
  9928. this.giveawayId = giveawayId;
  9929. return true;
  9930. }
  9931. scripts_echoLog({
  9932. text: i18n('getFailed', 'GiveawayId')
  9933. });
  9934. return false;
  9935. } catch (error) {
  9936. throwError(error, 'SweepWidget.getGiveawayId');
  9937. return false;
  9938. }
  9939. }
  9940. async #checkEnter() {
  9941. try {
  9942. return new Promise(resolve => {
  9943. const checker = setInterval(() => {
  9944. if ($('#unlock_rewards_main_wrapper').length > 0) {
  9945. clearInterval(checker);
  9946. resolve(true);
  9947. }
  9948. }, 500);
  9949. });
  9950. } catch (error) {
  9951. throwError(error, 'SweepWidget.checkEnter');
  9952. return false;
  9953. }
  9954. }
  9955. async #checkFinish($task) {
  9956. try {
  9957. return new Promise(resolve => {
  9958. const checker = setInterval(() => {
  9959. if ($task.find('i.fa-check:visible').length > 0 || $task.find('.sw_entry_input:visible').length === 0) {
  9960. clearInterval(checker);
  9961. resolve(true);
  9962. }
  9963. }, 500);
  9964. });
  9965. } catch (error) {
  9966. throwError(error, 'SweepWidget.checkFinish');
  9967. return false;
  9968. }
  9969. }
  9970. }
  9971. const website_SweepWidget = SweepWidget;
  9972. const defaultWhiteList = {
  9973. discord: {
  9974. servers: []
  9975. },
  9976. instagram: {
  9977. users: []
  9978. },
  9979. twitch: {
  9980. channels: []
  9981. },
  9982. twitter: {
  9983. users: [],
  9984. retweets: [],
  9985. likes: []
  9986. },
  9987. vk: {
  9988. names: []
  9989. },
  9990. youtube: {
  9991. channels: [],
  9992. likes: []
  9993. },
  9994. reddit: {
  9995. reddits: []
  9996. },
  9997. steam: {
  9998. groups: [],
  9999. officialGroups: [],
  10000. wishlists: [],
  10001. follows: [],
  10002. forums: [],
  10003. workshops: [],
  10004. curators: [],
  10005. workshopVotes: [],
  10006. curatorLikes: [],
  10007. announcements: [],
  10008. licenses: [],
  10009. playtests: []
  10010. }
  10011. };
  10012. const link2id = async function(type) {
  10013. try {
  10014. const link = $('#socialLink').val();
  10015. let id = '';
  10016. switch (type) {
  10017. case 'discord.servers':
  10018. id = link.match(/invite\/(.+)/)?.[1] || '';
  10019. break;
  10020.  
  10021. case 'instagram.users':
  10022. id = link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1] || '';
  10023. break;
  10024.  
  10025. case 'twitch.channels':
  10026. id = link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2] || '';
  10027. break;
  10028.  
  10029. case 'twitter.users':
  10030. id = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || '';
  10031. break;
  10032.  
  10033. case 'twitter.retweets':
  10034. id = link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1] || '';
  10035. break;
  10036.  
  10037. case 'vk.names':
  10038. id = link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1] || '';
  10039. break;
  10040.  
  10041. case 'youtube.channels':
  10042. id = (await getInfo(link, 'channel'))?.params?.channelId || '';
  10043. break;
  10044.  
  10045. case 'youtube.likes':
  10046. id = (await getInfo(link, 'likeVideo'))?.params?.videoId || '';
  10047. break;
  10048.  
  10049. case 'reddit.reddits':
  10050. id = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1] || link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1] || '';
  10051. break;
  10052.  
  10053. case 'steam.groups':
  10054. id = link.match(/groups\/(.+)\/?/)?.[1] || '';
  10055. break;
  10056.  
  10057. case 'steam.wishlists':
  10058. case 'steam.follows':
  10059. case 'steam.forums':
  10060. id = link.match(/app\/([\d]+)/)?.[1] || '';
  10061. break;
  10062.  
  10063. case 'steam.workshops':
  10064. id = link.match(/\?id=([\d]+)/)?.[1] || '';
  10065. break;
  10066.  
  10067. case 'steam.curators':
  10068. {
  10069. if (link.includes('curator')) {
  10070. id = link.match(/curator\/([\d]+)/)?.[1] || '';
  10071. } else {
  10072. const param = link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3);
  10073. if (!param || param.length !== 2) {
  10074. break;
  10075. }
  10076. const steam = new social_Steam();
  10077. if (await steam.init()) {
  10078. id = await steam.getCuratorId(param[0], param[1]) || '';
  10079. }
  10080. }
  10081. }
  10082. break;
  10083. }
  10084. return id;
  10085. } catch (error) {
  10086. throwError(error, 'link2id');
  10087. return i18n('getFailed', 'id');
  10088. }
  10089. };
  10090. const disabledType = {
  10091. steam: [ 'workshopVotes', 'curatorLikes', 'announcements' ],
  10092. twitter: [ 'likes' ]
  10093. };
  10094. const assignWhiteList = whiteList => {
  10095. try {
  10096. const newWhiteList = {};
  10097. for (const [ key, value ] of Object.entries(defaultWhiteList)) {
  10098. newWhiteList[key] = {
  10099. ...value,
  10100. ...whiteList[key]
  10101. };
  10102. }
  10103. return newWhiteList;
  10104. } catch (error) {
  10105. throwError(error, 'assignWhiteList');
  10106. return defaultWhiteList;
  10107. }
  10108. };
  10109. const whiteListOptions = function(showType) {
  10110. try {
  10111. const whiteList = assignWhiteList(GM_getValue('whiteList') || {});
  10112. let whiteListOptionsForm = `<form id="whiteListForm" class="auto-task-form">
  10113. <table class="auto-task-table"><thead><tr><td>${i18n('website')}</td><td>${i18n('type')}</td><td>${i18n('edit')}</td></tr></thead><tbody>`;
  10114. for (const [ social, types ] of Object.entries(whiteList)) {
  10115. 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('');
  10116. }
  10117. whiteListOptionsForm += '</tbody></table></form>';
  10118. if (showType === 'swal') {
  10119. external_Swal_default().fire({
  10120. title: i18n('whiteListOptions'),
  10121. html: whiteListOptionsForm,
  10122. showConfirmButton: false,
  10123. showCloseButton: true
  10124. });
  10125. } else {
  10126. $('body').append(`<h2>${i18n('whiteList')}</h2>${whiteListOptionsForm}`);
  10127. }
  10128. $('.editWhiteList').on('click', function() {
  10129. const value = $(this).attr('data-value');
  10130. if (!value) {
  10131. return;
  10132. }
  10133. const [ social, type ] = value.split('.');
  10134. if (!whiteList?.[social]?.[type]) {
  10135. scripts_echoLog({}).warning(i18n('whiteListNotFound', value));
  10136. return;
  10137. }
  10138. external_Swal_default().fire({
  10139. title: i18n('changeWhiteListOption', value),
  10140. input: 'textarea',
  10141. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10142. <button id="link2id" data-type="${value}" class="swal2-confirm swal2-styled">获取id</button>
  10143. <p style="margin-bottom:0 !important;">在下方填写白名单,每行一个</p>`,
  10144. inputValue: whiteList[social][type].join('\n'),
  10145. showConfirmButton: true,
  10146. confirmButtonText: i18n('save'),
  10147. showCancelButton: true,
  10148. cancelButtonText: i18n('close'),
  10149. showDenyButton: true,
  10150. denyButtonText: i18n('return')
  10151. }).then(({
  10152. isDenied,
  10153. isConfirmed,
  10154. value
  10155. }) => {
  10156. if (isDenied) {
  10157. if (showType === 'swal') {
  10158. whiteListOptions(showType);
  10159. }
  10160. return;
  10161. } else if (isConfirmed) {
  10162. whiteList[social][type] = value.split('\n');
  10163. GM_setValue('whiteList', whiteList);
  10164. external_Swal_default().fire({
  10165. title: i18n('changeWhiteListSuccess'),
  10166. icon: 'success'
  10167. });
  10168. }
  10169. });
  10170. $('#link2id').on('click', async function() {
  10171. const type = $(this).attr('data-type');
  10172. $('#socialLink').val(await link2id(type));
  10173. });
  10174. });
  10175. } catch (error) {
  10176. throwError(error, 'whiteListOptions');
  10177. }
  10178. };
  10179. const whiteList = whiteListOptions;
  10180. const setGistData = async (token, gistId, fileName, content) => {
  10181. try {
  10182. const logStatus = scripts_echoLog({
  10183. text: i18n('settingData')
  10184. });
  10185. const contentData = JSON.stringify({
  10186. files: {
  10187. [fileName]: {
  10188. content: JSON.stringify(content)
  10189. }
  10190. }
  10191. });
  10192. const {
  10193. result,
  10194. statusText,
  10195. status,
  10196. data
  10197. } = await tools_httpRequest({
  10198. url: `https://api.github.com/gists/${gistId}`,
  10199. headers: {
  10200. Accept: 'application/vnd.github.v3+json',
  10201. Authorization: `token ${token}`
  10202. },
  10203. data: contentData,
  10204. responseType: 'json',
  10205. method: 'POST',
  10206. timeout: 3e4
  10207. });
  10208. if (result === 'Success') {
  10209. if (data?.status === 200 && data.response.files?.[fileName]?.content === JSON.stringify(content)) {
  10210. logStatus.success();
  10211. return true;
  10212. }
  10213. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10214. return false;
  10215. }
  10216. logStatus.error(`${result}:${statusText}(${status})`);
  10217. return false;
  10218. } catch (error) {
  10219. throwError(error, 'setGistData');
  10220. return false;
  10221. }
  10222. };
  10223. const getGistData = async (token, gistId, fileName, test = false) => {
  10224. try {
  10225. const logStatus = scripts_echoLog({
  10226. text: i18n('gettingData')
  10227. });
  10228. const {
  10229. result,
  10230. statusText,
  10231. status,
  10232. data
  10233. } = await tools_httpRequest({
  10234. url: `https://api.github.com/gists/${gistId}`,
  10235. headers: {
  10236. Accept: 'application/vnd.github.v3+json',
  10237. Authorization: `token ${token}`
  10238. },
  10239. responseType: 'json',
  10240. method: 'GET',
  10241. timeout: 3e4
  10242. });
  10243. if (result === 'Success') {
  10244. if (data?.status === 200) {
  10245. const content = data.response?.files?.[fileName]?.content;
  10246. let formatedContent;
  10247. if (!content) {
  10248. logStatus.error(`Error:${i18n('noRemoteData')}`);
  10249. return false;
  10250. }
  10251. if (test) {
  10252. logStatus.success();
  10253. return true;
  10254. }
  10255. try {
  10256. formatedContent = JSON.parse(content);
  10257. } catch (error) {
  10258. logStatus.error(`Error:${i18n('errorRemoteDataFormat')}`);
  10259. return false;
  10260. }
  10261. logStatus.success();
  10262. return formatedContent;
  10263. }
  10264. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10265. return false;
  10266. }
  10267. logStatus.error(`${result}:${statusText}(${status})`);
  10268. return false;
  10269. } catch (error) {
  10270. throwError(error, 'getGistData');
  10271. return false;
  10272. }
  10273. };
  10274. const syncOptions = () => {
  10275. try {
  10276. const {
  10277. TOKEN,
  10278. GIST_ID,
  10279. FILE_NAME,
  10280. SYNC_HISTORY
  10281. } = GM_getValue('gistOptions') || {
  10282. TOKEN: '',
  10283. GIST_ID: '',
  10284. FILE_NAME: '',
  10285. SYNC_HISTORY: true
  10286. };
  10287. external_Swal_default().fire({
  10288. title: i18n('gistOptions'),
  10289. 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;">
  10290. ${i18n('upload2gist')}</button>` + `<button id="download-data" type="button" class="swal2-confirm swal2-styled" style="display: inline-block;">
  10291. ${i18n('downloadFromGist')}</button></p>`,
  10292. focusConfirm: false,
  10293. showLoaderOnConfirm: true,
  10294. 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>`,
  10295. preConfirm: async () => {
  10296. const token = $('#github-token').val();
  10297. const gistId = $('#gist-id').val();
  10298. const fileName = $('#file-name').val();
  10299. const syncHistory = $('#sync-history').prop('checked');
  10300. GM_setValue('gistOptions', {
  10301. TOKEN: token,
  10302. GIST_ID: gistId,
  10303. FILE_NAME: fileName,
  10304. SYNC_HISTORY: syncHistory
  10305. });
  10306. return await getGistData(token, gistId, fileName, true);
  10307. },
  10308. allowOutsideClick: () => !external_Swal_default().isLoading(),
  10309. confirmButtonText: i18n('saveAndTest'),
  10310. showCancelButton: true,
  10311. cancelButtonText: i18n('close')
  10312. }).then(({
  10313. value
  10314. }) => {
  10315. if (value) {
  10316. external_Swal_default().fire({
  10317. icon: 'success',
  10318. title: i18n('testSuccess')
  10319. }).then(syncOptions);
  10320. } else if (value !== undefined) {
  10321. external_Swal_default().fire({
  10322. icon: 'error',
  10323. title: i18n('testFailed')
  10324. }).then(syncOptions);
  10325. }
  10326. });
  10327. $('#upload-data').on('click', async () => {
  10328. const {
  10329. TOKEN,
  10330. GIST_ID,
  10331. FILE_NAME
  10332. } = GM_getValue('gistOptions') || {};
  10333. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10334. return external_Swal_default().fire({
  10335. icon: 'error',
  10336. title: i18n('saveAndTestNotice')
  10337. }).then(syncOptions);
  10338. }
  10339. external_Swal_default().fire({
  10340. icon: 'info',
  10341. title: i18n('processingData')
  10342. });
  10343. const data = {};
  10344. const names = GM_listValues();
  10345. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10346. for (const name of names) {
  10347. if (name === 'gistOptions' || /^[\w]+?Auth$/.test(name)) {
  10348. continue;
  10349. }
  10350. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10351. continue;
  10352. }
  10353. data[name] = GM_getValue(name);
  10354. }
  10355. external_Swal_default().update({
  10356. icon: 'info',
  10357. title: i18n('updatingData')
  10358. });
  10359. if (await setGistData(TOKEN, GIST_ID, FILE_NAME, data)) {
  10360. external_Swal_default().fire({
  10361. icon: 'success',
  10362. title: i18n('syncDataSuccess')
  10363. });
  10364. } else {
  10365. external_Swal_default().fire({
  10366. icon: 'error',
  10367. title: i18n('syncDataFailed')
  10368. });
  10369. }
  10370. });
  10371. $('#download-data').on('click', async () => {
  10372. const {
  10373. TOKEN,
  10374. GIST_ID,
  10375. FILE_NAME
  10376. } = GM_getValue('gistOptions') || {};
  10377. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10378. return external_Swal_default().fire({
  10379. icon: 'error',
  10380. title: i18n('saveAndTestNotice')
  10381. }).then(syncOptions);
  10382. }
  10383. external_Swal_default().fire({
  10384. icon: 'info',
  10385. title: i18n('downloadingData')
  10386. });
  10387. const data = await getGistData(TOKEN, GIST_ID, FILE_NAME);
  10388. if (!data) {
  10389. return external_Swal_default().fire({
  10390. icon: 'error',
  10391. title: i18n('checkedNoData')
  10392. }).then(syncOptions);
  10393. }
  10394. external_Swal_default().update({
  10395. icon: 'info',
  10396. title: i18n('savingData')
  10397. });
  10398. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10399. for (const [ name, value ] of Object.entries(data)) {
  10400. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10401. continue;
  10402. }
  10403. GM_setValue(name, value);
  10404. }
  10405. external_Swal_default().fire({
  10406. icon: 'success',
  10407. title: i18n('syncDataSuccess')
  10408. });
  10409. });
  10410. } catch (error) {
  10411. throwError(error, 'syncOptions');
  10412. }
  10413. };
  10414. const dataSync = syncOptions;
  10415. class Setting {
  10416. name = 'Setting';
  10417. buttons = [ 'saveGlobalOptions', 'syncData', 'tasksHistory' ];
  10418. syncData = dataSync;
  10419. tasksHistory() {
  10420. GM_openInTab('https://auto-task-v4.hclonely.com/history.html', {
  10421. active: true
  10422. });
  10423. }
  10424. static test() {
  10425. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/setting.html';
  10426. }
  10427. before() {
  10428. try {
  10429. $('body').html('').addClass('auto-task-options');
  10430. } catch (error) {
  10431. throwError(error, 'Setting.before');
  10432. }
  10433. }
  10434. after() {
  10435. try {
  10436. this.#environment();
  10437. changeGlobalOptions('page');
  10438. whiteList('page');
  10439. $('input[name="other.twitterVerifyId"]').after(`<button id="getTwitterUserId" type="button">${i18n('getTwitterUserId')}</button>`);
  10440. $('#getTwitterUserId').on('click', () => {
  10441. this.#getId('twitterUser');
  10442. });
  10443. $('input[name="other.youtubeVerifyChannel"]').after(`<button id="getYoutubeChannelId" type="button">${i18n('getYoutubeChannelId')}</button>`);
  10444. $('#getYoutubeChannelId').on('click', () => {
  10445. this.#getId('youtubeChannel');
  10446. });
  10447. $('input[name^="position"]').on('input', function() {
  10448. const type = $(this).attr('name').replace('position.', '');
  10449. const xLabel = 'rightleft';
  10450. const yLabel = 'topbottpm';
  10451. switch (type) {
  10452. case 'buttonSideX':
  10453. case 'buttonSideY':
  10454. case 'buttonDistance':
  10455. {
  10456. const distance = $('input[name="position.buttonDistance"]').val();
  10457. const sideX = $('input[name="position.buttonSideX"]').val();
  10458. const sideY = $('input[name="position.buttonSideY"]').val();
  10459. if (![ 'right', 'left' ].includes(sideX)) {
  10460. break;
  10461. }
  10462. if (![ 'top', 'bottom' ].includes(sideY)) {
  10463. break;
  10464. }
  10465. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10466. break;
  10467. }
  10468. const distanceArr = distance.split(',');
  10469. $('#auto-task-buttons').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10470. break;
  10471. }
  10472.  
  10473. case 'showButtonSideX':
  10474. case 'showButtonSideY':
  10475. case 'showButtonDistance':
  10476. {
  10477. const distance = $('input[name="position.showButtonDistance"]').val();
  10478. const sideX = $('input[name="position.showButtonSideX"]').val();
  10479. const sideY = $('input[name="position.showButtonSideY"]').val();
  10480. if (![ 'right', 'left' ].includes(sideX)) {
  10481. break;
  10482. }
  10483. if (![ 'top', 'bottom' ].includes(sideY)) {
  10484. break;
  10485. }
  10486. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10487. break;
  10488. }
  10489. const distanceArr = distance.split(',');
  10490. $('div.show-button-div').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10491. break;
  10492. }
  10493.  
  10494. case 'logSideX':
  10495. case 'logSideY':
  10496. case 'logDistance':
  10497. {
  10498. const distance = $('input[name="position.logDistance"]').val();
  10499. const sideX = $('input[name="position.logSideX"]').val();
  10500. const sideY = $('input[name="position.logSideY"]').val();
  10501. if (![ 'right', 'left' ].includes(sideX)) {
  10502. break;
  10503. }
  10504. if (![ 'top', 'bottom' ].includes(sideY)) {
  10505. break;
  10506. }
  10507. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10508. break;
  10509. }
  10510. const distanceArr = distance.split(',');
  10511. $('#auto-task-info').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10512. break;
  10513. }
  10514.  
  10515. default:
  10516. break;
  10517. }
  10518. });
  10519. $('input[name^="hotKey"]').attr('readonly', 'readonly').off('keydown').on('keydown', function(event) {
  10520. let functionKey = '';
  10521. if (event.altKey) {
  10522. functionKey += 'alt + ';
  10523. } else if (event.ctrlKey) {
  10524. functionKey += 'ctrl + ';
  10525. } else if (event.shiftKey) {
  10526. functionKey += 'shift + ';
  10527. }
  10528. $(this).val(functionKey + (event.key.length === 1 ? event.key.toLowerCase() : ''));
  10529. });
  10530. } catch (error) {
  10531. throwError(error, 'Setting.after');
  10532. }
  10533. }
  10534. saveGlobalOptions() {
  10535. try {
  10536. saveData();
  10537. } catch (error) {
  10538. throwError(error, 'Setting.saveGlobalOptions');
  10539. }
  10540. }
  10541. #getId(social) {
  10542. try {
  10543. external_Swal_default().fire({
  10544. title: i18n('getId', i18n(social)),
  10545. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10546. <button id="link2id" data-type="${social}" class="swal2-confirm swal2-styled">获取id</button>`,
  10547. showCancelButton: true,
  10548. cancelButtonText: i18n('close'),
  10549. showConfirmButton: false
  10550. });
  10551. $('#link2id').on('click', async function() {
  10552. const link = $('#socialLink').val();
  10553. if (!link) {
  10554. return;
  10555. }
  10556. const type = $(this).attr('data-type');
  10557. if (type === 'twitterUser') {
  10558. const name = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || link;
  10559. $('#socialLink').val(await new social_Twitter().userName2id(name) || '');
  10560. } else if (type === 'youtubeChannel') {
  10561. const name = /^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www.youtube.com\/.*/.test(link) ? link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1] : link;
  10562. $('#socialLink').val((await getInfo(name, 'channel'))?.params?.channelId || '');
  10563. }
  10564. });
  10565. } catch (error) {
  10566. throwError(error, 'Setting.getId');
  10567. }
  10568. }
  10569. #environment() {
  10570. try {
  10571. const userAgent = (0, javascript_utils_umd_min.ua)();
  10572. const environmentForm = `<form id="environmentForm" class="auto-task-form">
  10573. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('name')}</td><td>${i18n('version')}</td></tr></thead><tbody>
  10574. <tr><td>${i18n('os')}</td><td>${userAgent.os}</td><td>${userAgent.osVersion}</td></tr>
  10575. <tr><td>${i18n('browser')}</td><td>${userAgent.browserZH}</td><td>${userAgent.browserVersion}</td></tr>
  10576. <tr><td>${i18n('scriptManager')}</td><td>${GM_info.scriptHandler}</td><td>${GM_info.version}</td></tr>
  10577. <tr><td>${i18n('script')}</td><td>${GM_info.script.name}</td><td>${GM_info.script.version}</td></tr>
  10578. </tbody></table></form>`;
  10579. $('body').append(`<h2>${i18n('environment')}</h2>${environmentForm}`);
  10580. } catch (error) {
  10581. throwError(error, 'Setting.environment');
  10582. }
  10583. }
  10584. }
  10585. const website_Setting = Setting;
  10586. class History extends website_Keylol {
  10587. name = 'History';
  10588. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect', 'clearHistory' ];
  10589. static test() {
  10590. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/history.html';
  10591. }
  10592. before() {
  10593. try {
  10594. $('body').html('<div class="container"></div>').addClass('auto-task-history');
  10595. const data = GM_listValues() || [];
  10596. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  10597. for (const item of tasksHistory) {
  10598. this.#addItem(item);
  10599. }
  10600. } catch (error) {
  10601. throwError(error, 'History.before');
  10602. }
  10603. }
  10604. clearHistory() {
  10605. try {
  10606. const data = GM_listValues() || [];
  10607. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  10608. for (const item of tasksHistory) {
  10609. GM_deleteValue(item);
  10610. }
  10611. external_Swal_default().fire({
  10612. title: i18n('clearHistoryFinished'),
  10613. icon: 'success'
  10614. });
  10615. } catch (error) {
  10616. throwError(error, 'History.clearHistory');
  10617. }
  10618. }
  10619. #addItem(item) {
  10620. try {
  10621. const tasksData = GM_getValue(item);
  10622. if (!tasksData?.tasks) {
  10623. return;
  10624. }
  10625. let html = '';
  10626. let title = '';
  10627. let link = '';
  10628. const [ website, id ] = item.split('-');
  10629. switch (website) {
  10630. case 'fawTasks':
  10631. title = `Freeanywhere[${id}]`;
  10632. link = `https://freeanywhere.net/#/giveaway/${id}`;
  10633. break;
  10634.  
  10635. case 'gasTasks':
  10636. title = `Giveawaysu[${id}]`;
  10637. link = `https://giveaway.su/giveaway/view/${id}`;
  10638. break;
  10639.  
  10640. case 'gcTasks':
  10641. title = `GiveeClub[${id}]`;
  10642. link = `https://givee.club/event/${id}`;
  10643. break;
  10644.  
  10645. case 'gkTasks':
  10646. title = `Givekey[${id}]`;
  10647. link = `https://givekey.ru/giveaway/${id}`;
  10648. break;
  10649.  
  10650. case 'gleamTasks':
  10651. title = `Gleam[${id}]`;
  10652. link = `https://gleam.io${id}`;
  10653. break;
  10654.  
  10655. case 'khTasks':
  10656. title = `keyhub[${id}]`;
  10657. link = `https://key-hub.eu/giveaway/${id}`;
  10658. break;
  10659.  
  10660. case 'prysTasks':
  10661. title = `Prys[${id}]`;
  10662. link = `https://prys.revadike.com/giveaway/?id=${id}`;
  10663. break;
  10664.  
  10665. default:
  10666. return;
  10667. }
  10668. for (const [ social, types ] of Object.entries(tasksData.tasks)) {
  10669. for (const [ type, tasks ] of Object.entries(types)) {
  10670. for (const task of tasks) {
  10671. 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>`;
  10672. }
  10673. }
  10674. }
  10675. $('.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>`);
  10676. $('span.delete-task').on('click', function() {
  10677. const itemName = $(this).attr('data-name');
  10678. if (itemName) {
  10679. GM_deleteValue(itemName);
  10680. $(`div.card[data-name="${itemName}"]`).remove();
  10681. external_Swal_default().fire({
  10682. title: i18n('clearTaskFinished'),
  10683. text: itemName,
  10684. icon: 'success'
  10685. });
  10686. } else {
  10687. external_Swal_default().fire({
  10688. title: i18n('clearTaskFailed'),
  10689. icon: 'error'
  10690. });
  10691. }
  10692. });
  10693. } catch (error) {
  10694. throwError(error, 'History.addItem');
  10695. }
  10696. }
  10697. }
  10698. const website_History = History;
  10699. const GiveawayHopper_defaultTasksTemplate = {
  10700. steam: {
  10701. groupLinks: [],
  10702. wishlistLinks: [],
  10703. followLinks: [],
  10704. curatorLinks: [],
  10705. curatorLikeLinks: []
  10706. },
  10707. twitter: {
  10708. userLinks: [],
  10709. retweetLinks: []
  10710. },
  10711. twitch: {
  10712. channelLinks: []
  10713. },
  10714. discord: {
  10715. serverLinks: []
  10716. },
  10717. youtube: {
  10718. channelLinks: []
  10719. },
  10720. extra: {
  10721. giveawayHopper: []
  10722. }
  10723. };
  10724. const GiveawayHopper_defaultTasks = JSON.stringify(GiveawayHopper_defaultTasksTemplate);
  10725. class GiveawayHopper extends website_Website {
  10726. name = 'GiveawayHopper';
  10727. undoneTasks = JSON.parse(GiveawayHopper_defaultTasks);
  10728. socialTasks = JSON.parse(GiveawayHopper_defaultTasks);
  10729. tasks = [];
  10730. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  10731. static test() {
  10732. return window.location.host === 'giveawayhopper.com';
  10733. }
  10734. async after() {
  10735. try {
  10736. if (!this.#checkLogin()) {
  10737. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  10738. }
  10739. this.#getGiveawayId();
  10740. } catch (error) {
  10741. throwError(error, 'GiveawayHopper.after');
  10742. }
  10743. }
  10744. async init() {
  10745. try {
  10746. const logStatus = scripts_echoLog({
  10747. text: i18n('initing')
  10748. });
  10749. if (!await this.#checkLeftKey()) {
  10750. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  10751. }
  10752. this.initialized = true;
  10753. logStatus.success();
  10754. return true;
  10755. } catch (error) {
  10756. throwError(error, 'GiveawayHopper.init');
  10757. return false;
  10758. }
  10759. }
  10760. async classifyTask(action) {
  10761. try {
  10762. if (!this.giveawayId) {
  10763. await this.#getGiveawayId();
  10764. }
  10765. const logStatus = scripts_echoLog({
  10766. text: i18n('getTasksInfo')
  10767. });
  10768. if (action === 'undo') {
  10769. this.socialTasks = GM_getValue(`giveawayHopperTasks-${this.giveawayId}`)?.tasks || JSON.parse(GiveawayHopper_defaultTasks);
  10770. }
  10771. const {
  10772. result,
  10773. statusText,
  10774. status,
  10775. data
  10776. } = await tools_httpRequest({
  10777. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/with-auth`,
  10778. method: 'GET',
  10779. responseType: 'json',
  10780. fetch: true,
  10781. headers: {
  10782. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10783. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10784. }
  10785. });
  10786. if (result === 'Success') {
  10787. if (data?.status === 200 && data?.response?.tasks) {
  10788. this.tasks = data.response.tasks;
  10789. for (const task of data.response.tasks) {
  10790. if (task.isDone) {
  10791. continue;
  10792. }
  10793. await tools_httpRequest({
  10794. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/visited`,
  10795. method: 'GET',
  10796. responseType: 'json',
  10797. fetch: true,
  10798. headers: {
  10799. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10800. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10801. }
  10802. });
  10803. if (task.category === 'Steam' && task.type === 'JoinGroup') {
  10804. const steamGroupLink = await getRedirectLink(`https://steamcommunity.com/gid/${task.group_id}`);
  10805. if (!steamGroupLink) {
  10806. continue;
  10807. }
  10808. if (action === 'undo') {
  10809. this.socialTasks.steam.groupLinks.push(steamGroupLink);
  10810. }
  10811. if (action === 'do') {
  10812. this.undoneTasks.steam.groupLinks.push(steamGroupLink);
  10813. }
  10814. continue;
  10815. }
  10816. if (task.category === 'Discord' && task.type === 'JoinServer') {
  10817. if (action === 'undo') {
  10818. this.socialTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  10819. }
  10820. if (action === 'do') {
  10821. this.undoneTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  10822. }
  10823. continue;
  10824. }
  10825. if ([ 'TikTok', 'YouTube', 'General' ].includes(task.category)) {
  10826. continue;
  10827. }
  10828. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${task.category}-${task.type}`);
  10829. }
  10830. logStatus.success();
  10831. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  10832. this.socialTasks = this.uniqueTasks(this.socialTasks);
  10833. if (window.DEBUG) {
  10834. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  10835. }
  10836. GM_setValue(`giveawayHopperTasks-${this.giveawayId}`, {
  10837. tasks: this.socialTasks,
  10838. time: new Date().getTime()
  10839. });
  10840. return true;
  10841. }
  10842. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10843. return false;
  10844. }
  10845. logStatus.error(`${result}:${statusText}(${status})`);
  10846. return false;
  10847. } catch (error) {
  10848. throwError(error, 'GiveawayHopper.classifyTask');
  10849. return false;
  10850. }
  10851. }
  10852. async verifyTask() {
  10853. try {
  10854. for (const task of this.tasks) {
  10855. if (task.isDone) {
  10856. continue;
  10857. }
  10858. const logStatus = scripts_echoLog({
  10859. text: `${i18n('verifyingTask')}[${task.displayName?.replace(':target', task.targetName) || task.name}]...`
  10860. });
  10861. if (!task.link) {
  10862. if (task.category === 'YouTube' && task.type === 'FollowAccount') {
  10863. task.link = `https://www.youtube.com/@${task.targetName}`;
  10864. } else if (task.category === 'TikTok' && task.type === 'FollowAccount') {
  10865. task.link = `https://www.tiktok.com/@${task.targetName}`;
  10866. } else if (task.category === 'Steam' && task.type === 'JoinGroup') {
  10867. task.link = '';
  10868. } else if (task.category === 'Discord' && task.type === 'JoinServer') {
  10869. task.link = '';
  10870. }
  10871. }
  10872. if (task.link) {
  10873. await tools_httpRequest({
  10874. 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}`,
  10875. method: 'GET',
  10876. fetch: true,
  10877. headers: {
  10878. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10879. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10880. }
  10881. });
  10882. }
  10883. await delay(1e3);
  10884. const postData = {
  10885. taskcategory: task.category,
  10886. taskname: task.type
  10887. };
  10888. if ([ 'YouTube', 'TikTok' ].includes(task.category)) {
  10889. postData.username = '1';
  10890. }
  10891. const {
  10892. result,
  10893. statusText,
  10894. status,
  10895. data
  10896. } = await tools_httpRequest({
  10897. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/complete`,
  10898. method: 'POST',
  10899. fetch: true,
  10900. headers: {
  10901. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10902. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1]),
  10903. 'content-type': 'application/json'
  10904. },
  10905. dataType: 'json',
  10906. data: JSON.stringify(postData)
  10907. });
  10908. if (result === 'Success') {
  10909. if (data?.status === 200 && data?.response?.completed) {
  10910. logStatus.success();
  10911. continue;
  10912. }
  10913. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10914. continue;
  10915. }
  10916. logStatus.error(`${result}:${statusText}(${status})`);
  10917. continue;
  10918. }
  10919. } catch (error) {
  10920. throwError(error, 'GiveawayHopper.verifyTask');
  10921. return false;
  10922. }
  10923. }
  10924. #getGiveawayId() {
  10925. try {
  10926. const giveawayId = window.location.pathname.split('/').at(-1);
  10927. if (giveawayId) {
  10928. this.giveawayId = giveawayId;
  10929. return true;
  10930. }
  10931. scripts_echoLog({
  10932. text: i18n('getFailed', 'GiveawayId')
  10933. });
  10934. return false;
  10935. } catch (error) {
  10936. throwError(error, 'GiveawayHopper.getGiveawayId');
  10937. return false;
  10938. }
  10939. }
  10940. #checkLogin() {
  10941. try {
  10942. if (!globalOptions.other.checkLogin) {
  10943. return true;
  10944. }
  10945. if ($('div.widget-connections-edit:contains("Log in")').length > 0) {
  10946. $('div.widget-connections-edit:contains("Log in") a')[0].click();
  10947. }
  10948. return true;
  10949. } catch (error) {
  10950. throwError(error, 'GiveawayHopper.checkLogin');
  10951. return false;
  10952. }
  10953. }
  10954. async #checkLeftKey() {
  10955. try {
  10956. if (!globalOptions.other.checkLeftKey) {
  10957. return true;
  10958. }
  10959. if ($('p.widget-single-prize span').length > 0 && parseInt($('p.widget-single-prize span').text()?.match(/\d+/)?.[0] || '0', 10) > 0) {
  10960. return true;
  10961. }
  10962. await external_Swal_default().fire({
  10963. icon: 'warning',
  10964. title: i18n('notice'),
  10965. text: i18n('noKeysLeft'),
  10966. confirmButtonText: i18n('confirm'),
  10967. cancelButtonText: i18n('cancel'),
  10968. showCancelButton: true
  10969. }).then(({
  10970. value
  10971. }) => {
  10972. if (value) {
  10973. window.close();
  10974. }
  10975. });
  10976. return true;
  10977. } catch (error) {
  10978. throwError(error, 'GiveawayHopper.checkLeftKey');
  10979. return false;
  10980. }
  10981. }
  10982. }
  10983. const website_GiveawayHopper = GiveawayHopper;
  10984. 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 ];
  10985. const websiteOptions = function(website, options) {
  10986. try {
  10987. let websiteOptionsForm = `<form id="websiteOptionsForm" class="auto-task-form">
  10988. <table class="auto-task-table"><thead><tr><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  10989. for (const [ option, value ] of Object.entries(options)) {
  10990. websiteOptionsForm += `<tr><td>${option}</td><td><input class="editOption" type="text" name="${option}" value="${value}"/></td></tr>`;
  10991. }
  10992. websiteOptionsForm += '</tbody></table></form>';
  10993. external_Swal_default().fire({
  10994. title: i18n('websiteOptions'),
  10995. html: websiteOptionsForm,
  10996. showConfirmButton: true,
  10997. confirmButtonText: i18n('save'),
  10998. showCancelButton: true,
  10999. cancelButtonText: i18n('close')
  11000. }).then(({
  11001. isConfirmed
  11002. }) => {
  11003. if (isConfirmed) {
  11004. $('#websiteOptionsForm').serializeArray().map(value => {
  11005. options[value.name] = value.value;
  11006. return value;
  11007. });
  11008. GM_setValue(`${website}Options`, options);
  11009. external_Swal_default().fire({
  11010. title: i18n('changeWebsiteOptionsSuccess'),
  11011. icon: 'success'
  11012. });
  11013. }
  11014. });
  11015. } catch (error) {
  11016. throwError(error, 'websiteOptions');
  11017. }
  11018. };
  11019. const options = websiteOptions;
  11020. const external_keyboardJS_namespaceObject = keyboardJS;
  11021. var external_keyboardJS_default = __webpack_require__.n(external_keyboardJS_namespaceObject);
  11022. const checkUpdate = async (updateLink, auto) => {
  11023. try {
  11024. const checkUrl = `${updateLink}package.json?time=${new Date().getTime()}`;
  11025. const {
  11026. result,
  11027. statusText,
  11028. status,
  11029. data
  11030. } = await tools_httpRequest({
  11031. url: checkUrl,
  11032. responseType: 'json',
  11033. method: 'GET',
  11034. timeout: 3e4
  11035. });
  11036. if (result === 'Success') {
  11037. if (data?.response?.version) {
  11038. return data.response;
  11039. }
  11040. if (!auto) {
  11041. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${data?.statusText}(${data?.status})]`);
  11042. }
  11043. return false;
  11044. }
  11045. if (!auto) {
  11046. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${result}:${statusText}(${status})]`);
  11047. }
  11048. return false;
  11049. } catch (error) {
  11050. throwError(error, 'checkUpdate');
  11051. return false;
  11052. }
  11053. };
  11054. const hasNewVersion = (currentVersion, remoteVersion) => {
  11055. try {
  11056. const [ currentRealVersion ] = currentVersion.split('-');
  11057. const [ remoteRealVersion, isPreview ] = remoteVersion.split('-');
  11058. if (isPreview && !globalOptions.other.receivePreview) {
  11059. return false;
  11060. }
  11061. const [ currentVersion1, currentVersion2, currentVersion3 ] = currentRealVersion.split('.').map(value => parseInt(value, 10));
  11062. const [ remoteVersion1, remoteVersion2, remoteVersion3 ] = remoteRealVersion.split('.').map(value => parseInt(value, 10));
  11063. if (remoteVersion1 > currentVersion1) {
  11064. return true;
  11065. }
  11066. if (remoteVersion1 < currentVersion1) {
  11067. return false;
  11068. }
  11069. if (remoteVersion2 > currentVersion2) {
  11070. return true;
  11071. }
  11072. if (remoteVersion2 < currentVersion2) {
  11073. return false;
  11074. }
  11075. if (remoteVersion3 > currentVersion3) {
  11076. return true;
  11077. }
  11078. return false;
  11079. } catch (error) {
  11080. throwError(error, 'compareVersion');
  11081. return false;
  11082. }
  11083. };
  11084. const updateChecker = async () => {
  11085. try {
  11086. const currentVersion = GM_info.script.version;
  11087. const updateSource = globalOptions.other.autoUpdateSource.toLowerCase();
  11088. const updateLinks = {
  11089. github: 'https://github.com/HCLonely/auto-task-new/raw/main/',
  11090. jsdelivr: 'https://cdn.jsdelivr.net/gh/HCLonely/auto-task-v4@main/',
  11091. standby: 'https://auto-task-v4.hclonely.com/'
  11092. };
  11093. let version;
  11094. let updateLink = '';
  11095. let packageData;
  11096. if ([ 'github', 'jsdelivr', 'standby' ].includes(updateSource)) {
  11097. updateLink = updateLinks[updateSource];
  11098. packageData = await checkUpdate(updateLink, false);
  11099. } else {
  11100. updateLink = updateLinks.github;
  11101. packageData = await checkUpdate(updateLink, true);
  11102. if (!packageData) {
  11103. updateLink = updateLinks.jsdelivr;
  11104. packageData = await checkUpdate(updateLink, true);
  11105. if (!packageData) {
  11106. updateLink = updateLinks.standby;
  11107. packageData = await checkUpdate(updateLink, true);
  11108. }
  11109. }
  11110. }
  11111. if (packageData) {
  11112. version = packageData.version || currentVersion;
  11113. } else {
  11114. version = currentVersion;
  11115. scripts_echoLog({}).error(i18n('checkUpdateFailed'));
  11116. }
  11117. if (packageData && hasNewVersion(currentVersion, version)) {
  11118. scripts_echoLog({
  11119. html: `<li><font>${i18n('newVersionNotice', version, `${updateLink}dist/${GM_info.script.name}.user.js`)}</font></li>`
  11120. });
  11121. scripts_echoLog({
  11122. html: `<li>${i18n('updateText', version)}</li><ol class="update-text">${packageData.change?.map(change => `<li>${change}</li>`).join('')}<li>${i18n('updateHistory')}</li></ol>`
  11123. });
  11124. }
  11125. } catch (error) {
  11126. throwError(error, 'updateChecker');
  11127. }
  11128. };
  11129. const scripts_updateChecker = updateChecker;
  11130. window.STYLE = GM_addStyle(auto_task.A + GM_getResourceText('style'));
  11131. window.DEBUG = !!globalOptions.other?.debug;
  11132. window.TRACE = !!globalOptions.other?.debug && typeof console.trace === 'function';
  11133. const loadScript = async () => {
  11134. if (window.name === 'ATv4_twitchAuth' && window.location.hostname === 'www.twitch.tv') {
  11135. const authToken = external_Cookies_default().get('auth-token');
  11136. const isLogin = !!external_Cookies_default().get('login');
  11137. if (isLogin) {
  11138. GM_setValue('twitchAuth', {
  11139. authToken: authToken,
  11140. clientVersion: __twilightBuildID,
  11141. clientId: commonOptions?.headers?.['Client-ID'],
  11142. deviceId: commonOptions?.headers?.['Device-ID'],
  11143. clientSessionId: window.localStorage.local_storage_app_session_id.replace(/"/g, '')
  11144. });
  11145. window.close();
  11146. external_Swal_default().fire('', i18n('closePageNotice'));
  11147. } else {
  11148. external_Swal_default().fire('', i18n('needLogin'));
  11149. }
  11150. return;
  11151. }
  11152. if (window.name === 'ATv4_redditAuth' && window.location.hostname === 'www.reddit.com') {
  11153. const betaButton = $('#redesign-beta-optin-btn');
  11154. if (betaButton.length > 0) {
  11155. return betaButton[0].click();
  11156. }
  11157. window.close();
  11158. external_Swal_default().fire('', i18n('closePageNotice'));
  11159. return;
  11160. }
  11161. let website;
  11162. for (const Website of Websites) {
  11163. if (Website.test()) {
  11164. website = new Website();
  11165. break;
  11166. }
  11167. }
  11168. if (!website) {
  11169. console.log('%c%s', 'color:#ff0000', 'Auto-Task[Warning]: 脚本停止加载,当前网站不支持!');
  11170. return;
  11171. }
  11172. if (website?.before) {
  11173. await website?.before();
  11174. }
  11175. $('body').append(`
  11176. <div id="auto-task-info"
  11177. style="display:${globalOptions.other.defaultShowLog ? 'block' : 'none'};
  11178. ${globalOptions.position.logSideX}:${globalOptions.position.logDistance.split(',')[0]}px;
  11179. ${globalOptions.position.logSideY}:${globalOptions.position.logDistance.split(',')[1]}px;">
  11180. </div>
  11181. <div id="auto-task-buttons"
  11182. style="display:${globalOptions.other.defaultShowButton ? 'block' : 'none'};
  11183. ${globalOptions.position.buttonSideX}:${globalOptions.position.buttonDistance.split(',')[0]}px;
  11184. ${globalOptions.position.buttonSideY}:${globalOptions.position.buttonDistance.split(',')[1]}px;">
  11185. </div>
  11186. <div class="show-button-div"
  11187. style="display:${globalOptions.other.defaultShowButton ? 'none' : 'block'};
  11188. ${globalOptions.position.showButtonSideX}:${globalOptions.position.showButtonDistance.split(',')[0]}px;
  11189. ${globalOptions.position.showButtonSideY}:${globalOptions.position.showButtonDistance.split(',')[1]}px;">
  11190. <a class="auto-task-website-btn"
  11191. href="javascript:void(0);"
  11192. target="_self"
  11193. title="${i18n('showButton')}"> </a>
  11194. </div>
  11195. `);
  11196. $('div.show-button-div').on('click', () => {
  11197. $('#auto-task-buttons').show();
  11198. $('div.show-button-div').hide();
  11199. });
  11200. const toggleLog = () => {
  11201. const $this = $('#toggle-log');
  11202. const status = $this.attr('data-status');
  11203. if (status === 'show') {
  11204. $('#auto-task-info').hide();
  11205. $this.attr('data-status', 'hide').text(i18n('showLog'));
  11206. } else {
  11207. $('#auto-task-info').show();
  11208. $this.attr('data-status', 'show').text(i18n('hideLog'));
  11209. }
  11210. };
  11211. external_keyboardJS_default().bind(globalOptions.hotKey.doTaskKey, () => {
  11212. if (website.doTask) {
  11213. website.doTask();
  11214. }
  11215. });
  11216. external_keyboardJS_default().bind(globalOptions.hotKey.undoTaskKey, () => {
  11217. if (website.undoTask) {
  11218. website.undoTask();
  11219. }
  11220. });
  11221. external_keyboardJS_default().bind(globalOptions.hotKey.toggleLogKey, toggleLog);
  11222. if (website?.after) {
  11223. await website?.after();
  11224. }
  11225. if (website?.buttons && $('#auto-task-buttons').children().length === 0) {
  11226. $('#auto-task-buttons').addClass(`${website.name}-buttons`);
  11227. for (const button of website.buttons) {
  11228. if (website[button]) {
  11229. const btnElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">${i18n(button)}</a></p>`);
  11230. btnElement.find('a.auto-task-website-btn').on('click', () => {
  11231. website[button]();
  11232. });
  11233. $('#auto-task-buttons').append(btnElement);
  11234. }
  11235. }
  11236. }
  11237. const hideButtonElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">
  11238. ${i18n('hideButton')}</a></p>`);
  11239. hideButtonElement.find('a.auto-task-website-btn').on('click', () => {
  11240. $('#auto-task-buttons').hide();
  11241. $('div.show-button-div').show();
  11242. });
  11243. 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'}">
  11244. ${globalOptions.other.defaultShowLog ? i18n('hideLog') : i18n('showLog')}</a></p>`);
  11245. toggleLogElement.find('a.auto-task-website-btn').on('click', toggleLog);
  11246. $('#auto-task-buttons').append(hideButtonElement).append(toggleLogElement);
  11247. if (website?.options) {
  11248. GM_registerMenuCommand(i18n('changeWebsiteOptions'), () => {
  11249. options(website.name, website.options);
  11250. });
  11251. }
  11252. if (website.name !== 'Setting') {
  11253. GM_registerMenuCommand(i18n('changeGlobalOptions'), () => {
  11254. changeGlobalOptions('swal');
  11255. });
  11256. GM_registerMenuCommand(i18n('settingPage'), () => {
  11257. GM_openInTab('https://auto-task-v4.hclonely.com/setting.html', {
  11258. active: true
  11259. });
  11260. });
  11261. }
  11262. console.log('%c%s', 'color:#1bbe1a', 'Auto-Task[Load]: 脚本加载完成');
  11263. const [ v1, v2 ] = GM_info.version.split('.');
  11264. if (!(parseInt(v1, 10) >= 5 && parseInt(v2, 10) >= 2)) {
  11265. scripts_echoLog({}).error(i18n('versionNotMatched'));
  11266. }
  11267. if (!GM_getValue('notice')) {
  11268. external_Swal_default().fire({
  11269. title: i18n('swalNotice'),
  11270. icon: 'warning'
  11271. }).then(() => {
  11272. GM_openInTab(i18n('noticeLink'), {
  11273. active: true
  11274. });
  11275. GM_setValue('notice', new Date().getTime());
  11276. });
  11277. scripts_echoLog({
  11278. html: `<li><font class="warning">${i18n('echoNotice', i18n('noticeLink'))}</font></li>`
  11279. }).font?.find('a').on('click', () => {
  11280. GM_setValue('notice', new Date().getTime());
  11281. });
  11282. }
  11283. scripts_updateChecker();
  11284. };
  11285. if (window.location.hostname === 'discord.com') {
  11286. const LocalStorage = window.localStorage;
  11287. if (window.name === 'ATv4_discordAuth') {
  11288. window.localStorage.removeItem = () => true;
  11289. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11290. if (discordAuth && discordAuth.length > 0) {
  11291. GM_setValue('discordAuth', {
  11292. auth: discordAuth
  11293. });
  11294. window.close();
  11295. external_Swal_default().fire('', i18n('closePageNotice'));
  11296. } else {
  11297. external_Swal_default().fire({
  11298. text: i18n('getDiscordAuthFailed'),
  11299. icon: 'error'
  11300. });
  11301. }
  11302. } else {
  11303. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11304. if (discordAuth && discordAuth.length > 0) {
  11305. GM_setValue('discordAuth', {
  11306. auth: discordAuth
  11307. });
  11308. }
  11309. }
  11310. } else if (window.location.hostname === 'opquests.com') {
  11311. loadScript();
  11312. } else if ((window.name === 'ATv4_updateStoreAuth' || GM_getValue('ATv4_updateStoreAuth')) && window.location.host === 'store.steampowered.com') {
  11313. $(() => {
  11314. if ($('[data-miniprofile]').length === 0) {
  11315. return;
  11316. }
  11317. const storeSessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11318. if (storeSessionID) {
  11319. GM_deleteValue('ATv4_updateStoreAuth');
  11320. GM_setValue('steamStoreAuth', {
  11321. storeSessionID: storeSessionID
  11322. });
  11323. window.close();
  11324. external_Swal_default().fire('', i18n('closePageNotice'));
  11325. } else {
  11326. external_Swal_default().fire({
  11327. title: 'Error: Get "sessionID" failed',
  11328. icon: 'error'
  11329. });
  11330. }
  11331. });
  11332. } else if ((window.name === 'ATv4_updateCommunityAuth' || GM_getValue('ATv4_updateCommunityAuth')) && window.location.host === 'steamcommunity.com') {
  11333. $(() => {
  11334. const steam64Id = document.body.innerHTML.match(/g_steamID = "(.+?)";/)?.[1];
  11335. const communitySessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11336. if (steam64Id && communitySessionID) {
  11337. GM_deleteValue('ATv4_updateCommunityAuth');
  11338. GM_setValue('steamCommunityAuth', {
  11339. steam64Id: steam64Id,
  11340. communitySessionID: communitySessionID
  11341. });
  11342. window.close();
  11343. external_Swal_default().fire('', i18n('closePageNotice'));
  11344. } else {
  11345. setTimeout(() => {
  11346. external_Swal_default().fire({
  11347. title: 'Error: Get "sessionID" failed',
  11348. icon: 'error'
  11349. });
  11350. }, 3e3);
  11351. }
  11352. });
  11353. } else {
  11354. if (window.location.hostname === 'key-hub.eu') {
  11355. unsafeWindow.keyhubtracker = 1;
  11356. unsafeWindow.gaData = {};
  11357. }
  11358. $(loadScript);
  11359. }
  11360. }();
  11361. })();