auto-task-v4

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

目前為 2025-02-01 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name auto-task-v4
  3. // @namespace auto-task-v4
  4. // @version 4.6.0
  5. // @description 自动完成 Freeanywhere,Giveawaysu,GiveeClub,Givekey,Gleam,Indiedb,keyhub,OpiumPulses,Opquests,SweepWidget 等网站的任务。
  6. // @description:en Automatically complete the tasks of FreeAnyWhere, GiveawaySu, GiveeClub, Givekey, Gleam, Indiedb, keyhub, OpiumPulses, Opquests, SweepWidget websites.
  7. // @author HCLonely
  8. // @license MIT
  9. // @run-at document-start
  10. // @homepage https://auto-task-doc.js.org/
  11. // @supportURL https://github.com/HCLonely/auto-task-v4/issues
  12. // @icon https://auto-task-v4.hclonely.com/favicon.ico
  13.  
  14. // @include *://freeanywhere.net/*
  15. // @include *://giveaway.su/giveaway/view/*
  16. // @include *://givee.club/*/event/*
  17. // @include *://givekey.ru/giveaway/*
  18. // @include *://www.indiedb.com/giveaways*
  19. // @include *://key-hub.eu/giveaway/*
  20. // @include *://keylol.com/*
  21. // @include *://www.opiumpulses.com/giveaways
  22. // @include *://prys.revadike.com/giveaway/?id=*
  23. // @include *://opquests.com/quests/*
  24. // @include *://gleam.io/*
  25. // @include *://sweepwidget.com/view/*
  26. // @include *://giveawayhopper.com/c/*
  27.  
  28. // @include *://discord.com/*
  29. // @include *://www.twitch.tv/*
  30. // @include *://www.youtube.com/*
  31. // @include *://*.reddit.com/*
  32. // @include *://twitter.com/settings/account?k*
  33. // @include *://x.com/settings/account*
  34. // @include *://steamcommunity.com/*
  35. // @include *://store.steampowered.com/*
  36. // @include https://auto-task-v4.hclonely.com/setting.html
  37. // @include https://auto-task-v4.hclonely.com/history.html
  38.  
  39. // @grant GM_setValue
  40. // @grant GM_getValue
  41. // @grant GM_listValues
  42. // @grant GM_deleteValue
  43. // @grant GM_addStyle
  44. // @grant GM_xmlhttpRequest
  45. // @grant GM_registerMenuCommand
  46. // @grant GM_info
  47. // @grant GM_openInTab
  48. // @grant GM_setClipboard
  49. // @grant GM_getResourceText
  50. // @grant GM_cookie
  51. // @grant GM_addValueChangeListener
  52. // @grant GM_removeValueChangeListener
  53. // @grant unsafeWindow
  54. // @grant window.close
  55. // @grant window.localStorage
  56. // @grant window.sessionStorage
  57. // @grant window.focus
  58.  
  59. // @connect cdn.jsdelivr.net
  60. // @connect store.steampowered.com
  61. // @connect steamcommunity.com
  62. // @connect login.steampowered.com
  63. // @connect twitter.com
  64. // @connect x.com
  65. // @connect api.twitter.com
  66. // @connect youtube.com
  67. // @connect www.youtube.com
  68. // @connect facebook.com
  69. // @connect instagram.com
  70. // @connect vk.com
  71. // @connect twitch.tv
  72. // @connect www.twitch.tv
  73. // @connect gql.twitch.tv
  74. // @connect github.com
  75. // @connect discordapp.com
  76. // @connect discord.gg
  77. // @connect discord.com
  78. // @connect www.reddit.com
  79. // @connect oauth.reddit.com
  80. // @connect raw.githubusercontent.com
  81. // @connect t.me
  82. // @connect bit.ly
  83. // @connect giveaway.su
  84. // @connect google.com
  85. // @connect www.vloot.io
  86. // @connect givee.club
  87. // @connect gleam.io
  88. // @connect www.indiedb.com
  89. // @connect key-hub.eu
  90. // @connect opquests.com
  91. // @connect itch.io
  92. // @connect auto-task-v4.hclonely.com
  93. // @connect giveawayhopper.com
  94. // @connect *
  95. // @require https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
  96. // @require https://cdn.jsdelivr.net/npm/js-cookie@3.0.1/dist/js.cookie.min.js
  97. // @require https://cdn.jsdelivr.net/npm/regenerator-runtime@0.13.5/runtime.min.js
  98. // @require https://cdn.jsdelivr.net/npm/js-sha1@0.6.0/src/sha1.min.js
  99. // @require https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js
  100. // @resource style https://cdn.jsdelivr.net/npm/sweetalert2@11.3.5/dist/sweetalert2.min.css
  101. // @require https://cdn.jsdelivr.net/npm/keyboardjs@2.6.4/dist/keyboard.min.js
  102. // @require https://cdn.jsdelivr.net/npm/dayjs@1.10.7/dayjs.min.js
  103.  
  104. // @noframes
  105. // ==/UserScript==
  106.  
  107. console.log('%c%s', 'color:blue', 'Auto-Task[Load]: 脚本开始加载');
  108. (function() {
  109. var __webpack_modules__ = {
  110. 991: function(__unused_webpack_module, exports) {
  111. !function(e, n) {
  112. true ? n(exports) : 0;
  113. }(this, function(e) {
  114. 'use strict';
  115. var t = function() {
  116. return (t = Object.assign || function(e) {
  117. for (var n, o = 1, t = arguments.length; o < t; o++) {
  118. for (var r in n = arguments[o]) {
  119. Object.prototype.hasOwnProperty.call(n, r) && (e[r] = n[r]);
  120. }
  121. }
  122. return e;
  123. }).apply(this, arguments);
  124. };
  125. function r(e, n, o) {
  126. if (o || 2 === arguments.length) {
  127. for (var t, r = 0, i = n.length; r < i; r++) {
  128. !t && r in n || ((t = t || Array.prototype.slice.call(n, 0, r))[r] = n[r]);
  129. }
  130. }
  131. return e.concat(t || Array.prototype.slice.call(n));
  132. }
  133. function d(e) {
  134. return '[object Object]' === n(e);
  135. }
  136. function l(e, n) {
  137. var o = r(r([], n || [], !0), [ '_' ], !1).join('|');
  138. return e.replace(new RegExp('(('.concat(o, ')[a-z])+'), 'g'), function(e, n) {
  139. return n.replace(new RegExp(o), '').toLocaleUpperCase();
  140. });
  141. }
  142. var n = function(e) {
  143. return Object.prototype.toString.call(e);
  144. };
  145. var o = (i.prototype.init = function() {
  146. try {
  147. this.getSystemName(), this.getBrowserName();
  148. } catch (e) {
  149. console.warn('[UA formatter error] '.concat(e));
  150. }
  151. }, i.prototype.getEngine = function() {
  152. var e = this.agent;
  153. return -1 !== e.indexOf('Trident') ? 'Trident' : -1 !== e.indexOf('Firefox') ? 'Gecko' : -1 !== e.indexOf('Presto') ? 'Presto' : 'WebKit';
  154. }, i.prototype.getSystemName = function() {
  155. var e, n = (this.agent.match(/^[a-z]+\/\d+\.\d+\s?\(([a-z\d\s:;./_-]+)\)/i) || [])[1];
  156. try {
  157. var o = '';
  158. if (/Windows/i.test(n)) {
  159. var t = (n.match(/NT\s(\d+\.\d+)/) || [])[1];
  160. switch (this.info.os = 'Windows', t) {
  161. case '6.3':
  162. o = '8.1';
  163. break;
  164.  
  165. case '6.2':
  166. o = '8';
  167. break;
  168.  
  169. case '6.1':
  170. o = '7';
  171. break;
  172.  
  173. case '5.2':
  174. case '5.1':
  175. o = 'XP';
  176. break;
  177.  
  178. default:
  179. o = t;
  180. }
  181. return this.info.device = 'PC', void (this.info.osVersion = o);
  182. }
  183. if (/^Macintosh/i.test(n)) {
  184. return o = (n.match(/X\s((\d+(_|\.))+\d+)/) || [])[1], this.info.os = 'Macintosh',
  185. this.info.device = 'PC', void (this.info.osVersion = null !== (e = null == o ? void 0 : o.replace(/_/g, '.')) && void 0 !== e ? e : 'Unknown');
  186. }
  187. if (/^iPad/i.test(n)) {
  188. return o = (n.match(/((\d+_)+\d+)/) || [])[1], this.info.os = 'iPad',
  189. this.info.device = 'Tablet', void (this.info.osVersion = o.replace(/_/g, '.'));
  190. }
  191. if (/^iPhone/i.test(n)) {
  192. return o = (n.match(/((\d+_)+\d+)/) || [])[1], this.info.os = 'iPhone',
  193. this.info.device = 'Mobile', void (this.info.osVersion = o.replace(/_/g, '.'));
  194. }
  195. if (-1 !== n.indexOf('Android')) {
  196. var r = (n.match(/Android\s((\d+\.?)+\d?)/) || [])[1];
  197. return this.info.device = 'Mobile', this.info.os = 'Android', void (this.info.osVersion = r);
  198. }
  199. if (/Linux\s[a-z\d_]+/.test(n)) {
  200. return this.info.os = 'Linux', void (this.info.osVersion = 'Unknown');
  201. }
  202. this.info.os = 'Unknown', this.info.osVersion = 'Unknown';
  203. } catch (e) {
  204. this.info.os = 'Unknown', this.info.osVersion = 'Unknown';
  205. }
  206. }, i.prototype.getBrowserName = function() {
  207. var e = Object.keys(this.browserNameMap).map(function(e) {
  208. return new RegExp(''.concat(e, '(\\/|\\s)(\\d+\\.)+\\d+'));
  209. }), n = 1 < (n = (this.agent.match(/[a-z\d]+(\/|\s)(\d+\.)+\d+/gi) || []).filter(function(n) {
  210. return -1 !== e.findIndex(function(e) {
  211. return e.test(n);
  212. });
  213. })).length && !/^Safari/.test(n[n.length - 1]) ? n.reverse() : n;
  214. this.info = t(t({}, this.info), this._formatBrowserVersion(n[0]));
  215. }, i.prototype._formatBrowserVersion = function(e) {
  216. var n, o, t, r;
  217. try {
  218. for (var i = null !== (o = null === (n = e.match(/(?<name>[a-z\d]+)(\/|\s)(?<version>(\d+\.)+\d+)/i)) || void 0 === n ? void 0 : n.groups) && void 0 !== o ? o : {}, s = i.name, a = i.version, c = {}, f = 0, u = Object.entries(this.browserNameMap); f < u.length; f++) {
  219. var d = u[f], l = d[0], h = d[1];
  220. if (new RegExp(l).test(s)) {
  221. c = h;
  222. break;
  223. }
  224. }
  225. var p = {
  226. browserVersion: null != a ? a : 'Unknown',
  227. browser: null !== (t = c.en) && void 0 !== t ? t : 'Unknown',
  228. browserZH: null !== (r = (null == c ? void 0 : c.zh) || c.en) && void 0 !== r ? r : 'Unknown'
  229. };
  230. return 'Trident' === s && (p.browserVersion = {
  231. '4.0': 8,
  232. '5.0': 9,
  233. '6.0': 10,
  234. '7.0': 11
  235. }[a]), p;
  236. } catch (e) {
  237. return console.warn('[UA formatter error] '.concat(e)), {
  238. browser: 'Unknown',
  239. browserVersion: 'Unknown'
  240. };
  241. }
  242. }, i);
  243. function i(e) {
  244. this.agent = '', this.info = {
  245. browser: '',
  246. browserZH: '',
  247. browserVersion: '',
  248. os: '',
  249. osVersion: '',
  250. device: 'Unknown',
  251. engine: 'WebKit'
  252. }, this.browserNameMap = {
  253. MicroMessenger: {
  254. en: 'MicroMessenger',
  255. zh: '微信'
  256. },
  257. MetaSr: {
  258. en: 'MetaSr',
  259. zh: '搜狗浏览器'
  260. },
  261. 'QQ(Browser)?': {
  262. en: 'QQBrowser',
  263. zh: 'QQ浏览器'
  264. },
  265. UCBrowser: {
  266. en: 'UCBrowser',
  267. zh: 'UC浏览器'
  268. },
  269. '2345Explorer': {
  270. en: '2345Explorer',
  271. zh: '2345极速浏览器'
  272. },
  273. Mb2345Browser: {
  274. en: 'Mb2345Browser',
  275. zh: '2345手机浏览器'
  276. },
  277. Trident: {
  278. en: 'Internet Explorer'
  279. },
  280. 'Edge?': {
  281. en: 'Edge'
  282. },
  283. OPR: {
  284. en: 'Opera'
  285. },
  286. Vivaldi: {
  287. en: 'Vivaldi'
  288. },
  289. Firefox: {
  290. en: 'Firefox'
  291. },
  292. Chrome: {
  293. en: 'Chrome'
  294. },
  295. Safari: {
  296. en: 'Safari'
  297. }
  298. }, this.agent = e, this.init();
  299. var n = this.info, o = n.browser, e = n.browserVersion, n = n.osVersion;
  300. this.info = t(t({}, this.info), {
  301. engine: this.getEngine(),
  302. browserVersion: 'Safari' === o ? n : e
  303. });
  304. }
  305. function s() {
  306. this.cookies = {}, this.init();
  307. }
  308. var a = new (s.prototype.init = function() {
  309. var o = {};
  310. document.cookie.split(/;\s/).forEach(function(e) {
  311. var n = e.split(/=/), e = n[0], n = n[1];
  312. o[e] = n;
  313. }), this.cookies = o;
  314. }, s.prototype.getItem = function(e) {
  315. return this.cookies[e];
  316. }, s.prototype.getAllItems = function() {
  317. return this.cookies;
  318. }, s.prototype.setItem = function(e, n, o, t, r, i) {
  319. document.cookie = ''.concat(e, '=').concat(n).concat(o ? '; expires='.concat(o) : '').concat(t ? '; path='.concat(t) : '').concat(r ? '; domain='.concat(r) : '').concat(i ? '; secure' : '');
  320. }, s)();
  321. e.countDown = function e(n, o, t, r) {
  322. if (!window) {
  323. throw new Error('window is not defind.');
  324. }
  325. if (0 < n) {
  326. return r && r(), n--, window[o] = window.setTimeout(function() {
  327. e(n, o, t, r);
  328. }, 1e3), function() {
  329. return clearTimeout(window[o]);
  330. };
  331. }
  332. clearTimeout(window[o]), t && t();
  333. }, e.createRandomID = function(e) {
  334. void 0 === e && (e = 12);
  335. for (var n = [], o = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''), t = o.length, r = 0; r < e; r++) {
  336. n.push(o[Math.round(Math.random() * t)]);
  337. }
  338. return n.join('');
  339. }, e.dCookie = a, e.debounce = function(o, t, r) {
  340. var i;
  341. void 0 === t && (t = 0);
  342. var s = r = void 0 === r ? !1 : r;
  343. return function() {
  344. var e = this, n = arguments;
  345. s && (o.apply(this, arguments), s = !1), clearTimeout(i), i = setTimeout(function() {
  346. r ? s = !0 : o.apply(e, n);
  347. }, t);
  348. };
  349. }, e.deepCopy = function e(n) {
  350. if (d(n) || Array.isArray(n)) {
  351. var o, t = Array.isArray(n) ? [] : {};
  352. for (o in n) {
  353. t[o] = e(n[o]);
  354. }
  355. return t;
  356. }
  357. return n;
  358. }, e.formatQueryParams = function(e) {
  359. e = null === (e = /\?(?<params>(.*)=.+)/.exec(decodeURIComponent(e))) || void 0 === e ? void 0 : e.groups;
  360. if (!e) {
  361. return {};
  362. }
  363. for (var n = e.params.split('&'), t = {}, o = 0; o < n.length; o++) {
  364. n[o].replace(/([^?&]*)=([^?&]*)/, function(e, n, o) {
  365. return t[n] = o, e;
  366. });
  367. }
  368. return t;
  369. }, e.formatThousandth = function(e) {
  370. var n = ''.concat(e).split('.'), e = n[0], n = n[1], n = void 0 === n ? '' : n, e = e.replace(/\d{1,3}(?=(\d{3})+$)/g, '$&,');
  371. return ''.concat(e).concat(n ? '.'.concat(n) : '');
  372. }, e.generateTree = function e(n, o, t, r) {
  373. for (var i = [], s = 0; s < n.length; s++) {
  374. var a = n[s];
  375. a[t] === o && (i.push(a), a.children = e(n, a[null != r ? r : 'id'], t, r));
  376. }
  377. return i;
  378. }, e.isEmpty = function(e) {
  379. return Array.isArray(e) ? 0 === e.length : d(e) ? 0 === Object.keys(e).length : [ '[object Set]', '[object Map]' ].includes(n(e)) ? 0 === e.size : [ null, void 0, '' ].includes(e);
  380. }, e.isFunction = function(e) {
  381. return '[object Function]' === n(e);
  382. }, e.isImageUrl = function(e) {
  383. return /\.((png)|(jpe?g)|(gif)|(svg)|(webp))$/gi.test(e);
  384. }, e.isObject = d, e.isRegexp = function(e) {
  385. return '[object RegExp]' === n(e);
  386. }, e.objectKeyToCamelCase = function e(n, o, t) {
  387. if (Array.isArray(n)) {
  388. for (var r = [], i = 0; i < n.length; i++) {
  389. r[i] = e(o && n[i][o] ? n[i][o] : n[i], o, t);
  390. }
  391. } else if (d(n)) {
  392. r = {};
  393. for (var s = o && n[o] ? n[o] : n, a = 0, c = Object.entries(s); a < c.length; a++) {
  394. var f = (u = c[a])[0], u = u[1];
  395. Array.isArray(u) || d(s) ? r[l(f, t)] = e(u, o, t) : r[l(f, t)] = u;
  396. }
  397. } else {
  398. r = n;
  399. }
  400. return r;
  401. }, e.realType = n, e.searchParams = function(e, n) {
  402. return void 0 === e && (e = null === location || void 0 === location ? void 0 : location.search),
  403. new URLSearchParams(e).get(n);
  404. }, e.toLowerCamelCase = l, e.toUnderline = function(e) {
  405. return e.replace(/([A-Z])/g, function(e) {
  406. return '_'.concat(e.toLocaleLowerCase());
  407. });
  408. }, e.ua = function(e) {
  409. return void 0 === e && (e = navigator.userAgent), new o(e).info;
  410. }, Object.defineProperty(e, '__esModule', {
  411. value: !0
  412. });
  413. });
  414. },
  415. 675: function(module, __webpack_exports__, __webpack_require__) {
  416. 'use strict';
  417. __webpack_require__.d(__webpack_exports__, {
  418. A: function() {
  419. return __WEBPACK_DEFAULT_EXPORT__;
  420. }
  421. });
  422. var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(601);
  423. var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = __webpack_require__.n(_node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
  424. var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(314);
  425. var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = __webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
  426. var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()(_node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default());
  427. ___CSS_LOADER_EXPORT___.push([ module.id, `.colorful-button,#auto-task-buttons a.auto-task-website-btn,.show-button-div a.auto-task-website-btn,body.auto-task-options .auto-task-form table button{position:relative;padding:5px 10px;text-align:center;color:#fff;text-decoration:none;background:linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);border-radius:30px;background-size:400%;text-transform:capitalize}.colorful-button:hover,#auto-task-buttons a.auto-task-website-btn:hover,.show-button-div a.auto-task-website-btn:hover,body.auto-task-options .auto-task-form table button:hover{transform:scale(1.05);box-shadow:0 6px 20px rgba(0,0,0,.3);cursor:pointer}.colorful-button:hover::before,#auto-task-buttons a.auto-task-website-btn:hover::before,.show-button-div a.auto-task-website-btn:hover::before,body.auto-task-options .auto-task-form table button:hover::before{filter:blur(10px);opacity:1}.colorful-button::before,#auto-task-buttons a.auto-task-website-btn::before,.show-button-div a.auto-task-website-btn::before,body.auto-task-options .auto-task-form table button::before{content:"";position:absolute;top:-5px;left:-5px;right:-5px;bottom:-5px;z-index:-1;background:linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);border-radius:40px;background-size:400%;opacity:-1}#auto-task-info{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 getFinalUrl = (responseHeaders, finalUrl) => {
  568. const realFinalUrl = responseHeaders?.split('\n')?.find(header => header.includes('location') ? header.replace('loctation:', '').trim() : null);
  569. return realFinalUrl || finalUrl;
  570. };
  571. const httpRequest = async (options, times = 0) => {
  572. if (window.TRACE) {
  573. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  574. }
  575. try {
  576. const result = await new Promise(resolve => {
  577. if (options.dataType) {
  578. options.responseType = options.dataType;
  579. }
  580. const requestObj = {
  581. ...{
  582. timeout: 3e4,
  583. ontimeout(data) {
  584. resolve({
  585. result: 'Error',
  586. statusText: 'Timeout',
  587. status: 601,
  588. data: data,
  589. options: options
  590. });
  591. },
  592. onabort(data) {
  593. resolve({
  594. result: 'Error',
  595. statusText: 'Aborted',
  596. status: 602,
  597. data: data,
  598. options: options
  599. });
  600. },
  601. onerror(data) {
  602. resolve({
  603. result: 'Error',
  604. statusText: 'Error',
  605. status: 603,
  606. data: data,
  607. options: options
  608. });
  609. },
  610. onload(data) {
  611. data.finalUrl = getFinalUrl(data.responseHeaders, data.finalUrl);
  612. if (options.responseType === 'json' && data?.response && typeof data.response !== 'object') {
  613. try {
  614. data.response = JSON.parse(data.responseText);
  615. } catch (error) {}
  616. }
  617. resolve({
  618. result: 'Success',
  619. statusText: 'Load',
  620. status: 600,
  621. data: data,
  622. options: options
  623. });
  624. }
  625. },
  626. ...options
  627. };
  628. GM_xmlhttpRequest(requestObj);
  629. });
  630. if (window.DEBUG) {
  631. console.log('%cAuto-Task[httpRequest]:', 'color:blue', JSON.stringify(result));
  632. }
  633. if (result.status !== 600 && times < 2) {
  634. return await httpRequest(options, times + 1);
  635. }
  636. return result;
  637. } catch (error) {
  638. console.log('%cAuto-Task[httpRequest]:', 'color:red', JSON.stringify({
  639. errorMsg: error,
  640. options: options
  641. }));
  642. throwError(error, 'httpRequest');
  643. return {
  644. result: 'JsError',
  645. statusText: 'Error',
  646. status: 604,
  647. error: error,
  648. options: options
  649. };
  650. }
  651. };
  652. const tools_httpRequest = httpRequest;
  653. const echoLog = ({
  654. type,
  655. text,
  656. html,
  657. id
  658. }) => {
  659. const emptyStatus = {
  660. success: () => emptyStatus,
  661. error: () => emptyStatus,
  662. warning: () => emptyStatus,
  663. info: () => emptyStatus,
  664. view: () => emptyStatus
  665. };
  666. try {
  667. let ele;
  668. if (type) {
  669. switch (type) {
  670. case 'joiningSteamGroup':
  671. case 'leavingSteamGroup':
  672. case 'gettingSteamGroupId':
  673. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/groups/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  674. break;
  675.  
  676. case 'joiningSteamOfficialGroup':
  677. case 'leavingSteamOfficialGroup':
  678. case 'gettingSteamOfficialGroupId':
  679. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/games/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  680. break;
  681.  
  682. case 'subscribingForum':
  683. case 'unsubscribingForum':
  684. case 'gettingForumId':
  685. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/app/${text}/discussions/" target="_blank">${text}</a>]...<font></font></li>`);
  686. break;
  687.  
  688. case 'followingCurator':
  689. case 'unfollowingCurator':
  690. case 'gettingCuratorId':
  691. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/${text?.includes('/') ? text : `curator/${text}`}" target="_blank">${text}</a>]...<font></font></li>`);
  692. break;
  693.  
  694. case 'addingToWishlist':
  695. case 'removingFromWishlist':
  696. case 'followingGame':
  697. case 'unfollowingGame':
  698. case 'gettingSubid':
  699. case 'addingFreeLicense':
  700. case 'requestingPlayTestAccess':
  701. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/app/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  702. break;
  703.  
  704. case 'addingFreeLicenseSubid':
  705. ele = $(`<li>${i18n('addingFreeLicense')}[<a href="https://steamdb.info/sub/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  706. break;
  707.  
  708. case 'favoritingWorkshop':
  709. case 'unfavoritingWorkshop':
  710. case 'gettingWorkshopAppId':
  711. case 'votingUpWorkshop':
  712. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/sharedfiles/filedetails/?id=${text}" target="_blank">
  713. ${text}</a>]...<font></font></li>`);
  714. break;
  715.  
  716. case 'gettingAnnouncementParams':
  717. case 'likingAnnouncement':
  718. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/news/app/${text}/view/${id}" target="_blank">
  719. ${id}</a>]...<font></font></li>`);
  720. break;
  721.  
  722. case 'joiningDiscordServer':
  723. case 'gettingDiscordGuild':
  724. ele = $(`<li>${i18n(type)}[<a href="https://discord.com/invite/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  725. break;
  726.  
  727. case 'leavingDiscordServer':
  728. ele = $(`<li>${i18n(type)}[<a href="https://discord.com/channels/@me/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  729. break;
  730.  
  731. case 'updateDiscordAuth':
  732. ele = $(`<li style="color:red;">${i18n('updateDiscordAuth')}</li>`);
  733. break;
  734.  
  735. case 'followingTwitchChannel':
  736. case 'unfollowingTwitchChannel':
  737. case 'gettingTwitchChannelId':
  738. ele = $(`<li>${i18n(type)}[<a href="https://www.twitch.tv/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  739. break;
  740.  
  741. case 'gettingInsUserId':
  742. case 'followingIns':
  743. case 'unfollowingIns':
  744. ele = $(`<li>${i18n(type)}[<a href="https://www.instagram.com/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  745. break;
  746.  
  747. case 'gettingTwitterUserId':
  748. case 'followingTwitterUser':
  749. case 'unfollowingTwitterUser':
  750. ele = $(`<li>${i18n(type)}[<a href="https://x.com/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  751. break;
  752.  
  753. case 'retweetting':
  754. case 'unretweetting':
  755. ele = $(`<li>${i18n(type)}${text}...<font></font></li>`);
  756. break;
  757.  
  758. case 'joiningReddit':
  759. case 'leavingReddit':
  760. ele = $(`<li>${i18n(type)}[<a href="https://www.reddit.com/r/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  761. break;
  762.  
  763. case 'followingRedditUser':
  764. case 'unfollowingRedditUser':
  765. ele = $(`<li>${i18n(type)}[<a href="https://www.reddit.com/user/${text?.replace('u_', '')}" target="_blank">
  766. ${text?.replace('u_', '')}</a>]...<font></font></li>`);
  767. break;
  768.  
  769. case 'followingYtbChannel':
  770. case 'unfollowingYtbChannel':
  771. ele = $(`<li>${i18n(type)}[<a href="https://www.youtube.com/channel/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  772. break;
  773.  
  774. case 'likingYtbVideo':
  775. case 'unlikingYtbVideo':
  776. ele = $(`<li>${i18n(type)}[<a href="https://www.youtube.com/watch?v=${text}" target="_blank">${text}</a>]...<font></font></li>`);
  777. break;
  778.  
  779. case 'gettingVkId':
  780. case 'joiningVkGroup':
  781. case 'leavingVkGroup':
  782. case 'joiningVkPublic':
  783. case 'leavingVkPublic':
  784. case 'sendingVkWall':
  785. case 'deletingVkWall':
  786. ele = $(`<li>${i18n(type)}[<a href="https://vk.com/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  787. break;
  788.  
  789. case 'visitingLink':
  790. ele = $(`<li>${i18n('visitingLink')}[<a href="${text}" target="_blank">${text}</a>]...<font></font></li>`);
  791. break;
  792.  
  793. case 'verifyingInsAuth':
  794. case 'text':
  795. ele = $(`<li>${i18n(text)}<font></font></li>`);
  796. break;
  797.  
  798. case 'html':
  799. ele = $(text || html);
  800. break;
  801.  
  802. case 'whiteList':
  803. ele = $(`<li><font class="warning">${i18n('skipTask')}[${text}(${id})](${i18n('whiteList')})</font></li>`);
  804. break;
  805.  
  806. case 'globalOptionsSkip':
  807. ele = $(`<li>${i18n('skipTaskOption')}<font class="warning">${text}</font></li>`);
  808. break;
  809.  
  810. default:
  811. ele = $(`<li>${i18n('unKnown')}:${type}(${text})...<font></font></li>`);
  812. break;
  813. }
  814. } else if (text) {
  815. ele = $(`<li>${i18n(text)}<font></font></li>`);
  816. } else if (html) {
  817. ele = $(html);
  818. } else {
  819. ele = $('<li><font></font></li>');
  820. }
  821. ele.addClass('card-text');
  822. $('#auto-task-info').append(ele);
  823. ele[0]?.scrollIntoView();
  824. const font = ele.find('font');
  825. const status = {
  826. font: font,
  827. success(text = 'Success', html = false) {
  828. this.font?.attr('class', '').addClass('success');
  829. html ? this.font?.html(text) : this.font?.text(text);
  830. return this;
  831. },
  832. error(text = 'Error', html = false) {
  833. this.font?.attr('class', '').addClass('error');
  834. html ? this.font?.html(text) : this.font?.text(text);
  835. return this;
  836. },
  837. warning(text = 'Warning', html = false) {
  838. this.font?.attr('class', '').addClass('warning');
  839. html ? this.font?.html(text) : this.font?.text(text);
  840. return this;
  841. },
  842. info(text = 'Info', html = false) {
  843. this.font?.attr('class', '').addClass('info');
  844. html ? this.font?.html(text) : this.font?.text(text);
  845. return this;
  846. },
  847. view() {
  848. this.font?.[0].scrollIntoView();
  849. return this;
  850. }
  851. };
  852. return status;
  853. } catch (error) {
  854. throwError(error, 'echoLog');
  855. return emptyStatus;
  856. }
  857. };
  858. const scripts_echoLog = echoLog;
  859. const unique = array => {
  860. try {
  861. return [ ...new Set(array) ];
  862. } catch (error) {
  863. throwError(error, 'unique');
  864. return [];
  865. }
  866. };
  867. const delay = (time = 1e3) => new Promise(resolve => {
  868. setTimeout(() => {
  869. resolve(true);
  870. }, time);
  871. });
  872. const getRedirectLink = async link => {
  873. try {
  874. if (!link) {
  875. return null;
  876. }
  877. const redirectLinksCache = GM_getValue('redirectLinks') || {};
  878. if (redirectLinksCache[link]) {
  879. redirectLinksCache[link];
  880. }
  881. return await tools_httpRequest({
  882. url: link,
  883. method: 'GET'
  884. }).then(({
  885. data
  886. }) => {
  887. if (data?.finalUrl) {
  888. redirectLinksCache[link] = data.finalUrl;
  889. GM_setValue('redirectLinks', redirectLinksCache);
  890. return data.finalUrl;
  891. }
  892. return null;
  893. });
  894. } catch (error) {
  895. throwError(error, 'getRedirectLink');
  896. return null;
  897. }
  898. };
  899. const visitLink = async (link, options) => {
  900. try {
  901. const logStatus = scripts_echoLog({
  902. type: 'visitLink',
  903. text: link
  904. });
  905. return await tools_httpRequest({
  906. url: link,
  907. method: 'GET',
  908. ...options
  909. }).then(({
  910. result,
  911. statusText,
  912. status
  913. }) => {
  914. if (result === 'Success') {
  915. logStatus.success();
  916. return true;
  917. }
  918. logStatus.error(`${result}:${statusText}(${status})`);
  919. return false;
  920. });
  921. } catch (error) {
  922. throwError(error, 'visitLink');
  923. return false;
  924. }
  925. };
  926. const getUrlQuery = url => {
  927. try {
  928. const query = {};
  929. if (url) {
  930. if (url.includes('?')) {
  931. url.split('?')[1].replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  932. query[key] = value;
  933. return str;
  934. });
  935. }
  936. } else {
  937. window.location.search.replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  938. query[key] = value;
  939. return str;
  940. });
  941. }
  942. return query;
  943. } catch (error) {
  944. throwError(error, 'getUrlQuery');
  945. return {};
  946. }
  947. };
  948. const getUuid = () => {
  949. const uuidUrl = URL.createObjectURL(new Blob()).toString();
  950. return uuidUrl.slice(uuidUrl.lastIndexOf('/') + 1);
  951. };
  952. const stringToColour = str => {
  953. try {
  954. let hash = 0;
  955. for (let i = 0; i < str.length; i++) {
  956. hash = str.charCodeAt(i) + ((hash << 5) - hash);
  957. }
  958. let colour = '#';
  959. for (let i = 0; i < 3; i++) {
  960. const value = hash >> i * 8 & 255;
  961. colour += `00${value.toString(16)}`.slice(-2);
  962. }
  963. return colour;
  964. } catch (error) {
  965. throwError(error, 'stringToColour');
  966. return '#fff';
  967. }
  968. };
  969. const defaultGlobalOptions = {
  970. doTask: {
  971. discord: {
  972. servers: true
  973. },
  974. instagram: {
  975. users: true
  976. },
  977. twitch: {
  978. channels: true
  979. },
  980. twitter: {
  981. users: true,
  982. retweets: true
  983. },
  984. vk: {
  985. names: true
  986. },
  987. youtube: {
  988. channels: true,
  989. likes: true
  990. },
  991. reddit: {
  992. reddits: true
  993. },
  994. steam: {
  995. groups: true,
  996. officialGroups: true,
  997. wishlists: true,
  998. follows: true,
  999. forums: true,
  1000. workshops: true,
  1001. curators: true,
  1002. workshopVotes: true,
  1003. announcements: true,
  1004. licenses: true,
  1005. playtests: true
  1006. }
  1007. },
  1008. undoTask: {
  1009. discord: {
  1010. servers: true
  1011. },
  1012. instagram: {
  1013. users: true
  1014. },
  1015. twitch: {
  1016. channels: true
  1017. },
  1018. twitter: {
  1019. users: true,
  1020. retweets: true
  1021. },
  1022. vk: {
  1023. names: true
  1024. },
  1025. youtube: {
  1026. channels: true,
  1027. likes: true
  1028. },
  1029. reddit: {
  1030. reddits: true
  1031. },
  1032. steam: {
  1033. groups: true,
  1034. officialGroups: true,
  1035. wishlists: true,
  1036. follows: true,
  1037. forums: true,
  1038. workshops: true,
  1039. curators: true
  1040. }
  1041. },
  1042. ASF: {
  1043. AsfEnabled: false,
  1044. AsfIpcUrl: '',
  1045. AsfIpcPassword: '',
  1046. AsfBotname: 'asf'
  1047. },
  1048. position: {
  1049. buttonSideX: 'right',
  1050. buttonSideY: 'top',
  1051. buttonDistance: '15,30',
  1052. showButtonSideX: 'right',
  1053. showButtonSideY: 'top',
  1054. showButtonDistance: '15,30',
  1055. logSideX: 'right',
  1056. logSideY: 'bottom',
  1057. logDistance: '10,10'
  1058. },
  1059. hotKey: {
  1060. doTaskKey: 'alt + d',
  1061. undoTaskKey: 'alt + u',
  1062. toggleLogKey: 'alt + l'
  1063. },
  1064. other: {
  1065. twitterVerifyId: '783214',
  1066. youtubeVerifyChannel: 'UCrXUsMBcfTVqwAS7DKg9C0Q',
  1067. autoUpdateSource: 'jsdelivr',
  1068. language: 'zh',
  1069. checkLogin: true,
  1070. checkLeftKey: true,
  1071. defaultShowButton: true,
  1072. defaultShowLog: true,
  1073. debug: false,
  1074. receivePreview: true
  1075. }
  1076. };
  1077. const userDefinedGlobalOptions = GM_getValue('globalOptions') || {};
  1078. const assignObject = (obj1, obj2) => {
  1079. try {
  1080. const newObj = {};
  1081. for (const [ key, value ] of Object.entries(obj1)) {
  1082. if (Object.prototype.toString.call(value) === '[object Object]' && Object.prototype.toString.call(obj2[key]) === '[object Object]') {
  1083. newObj[key] = assignObject(value, obj2[key]);
  1084. } else {
  1085. newObj[key] = obj2[key] ?? value;
  1086. }
  1087. }
  1088. return newObj;
  1089. } catch (error) {
  1090. throwError(error, 'assignObject');
  1091. return defaultGlobalOptions;
  1092. }
  1093. };
  1094. const globalOptions = assignObject(defaultGlobalOptions, userDefinedGlobalOptions);
  1095. const saveData = () => {
  1096. try {
  1097. const data = {};
  1098. $('#globalOptionsForm').serializeArray().map(value => {
  1099. data[value.name] = value.value;
  1100. return value;
  1101. });
  1102. $.makeArray($('#globalOptionsForm input')).map(element => {
  1103. const name = $(element).attr('name');
  1104. const keys = name.split('.');
  1105. if (keys.length === 3) {
  1106. globalOptions[keys[0]][keys[1]][keys[2]] = data[name] ? data[name] === 'on' ? true : data[name] : false;
  1107. } else if (keys.length === 2) {
  1108. globalOptions[keys[0]][keys[1]] = data[name] ? data[name] === 'on' ? true : data[name] : false;
  1109. }
  1110. return element;
  1111. });
  1112. GM_setValue('globalOptions', globalOptions);
  1113. external_Swal_default().fire({
  1114. title: i18n('changeGlobalOptionsSuccess'),
  1115. icon: 'success'
  1116. });
  1117. } catch (error) {
  1118. throwError(error, 'saveData');
  1119. }
  1120. };
  1121. const changeGlobalOptions = showType => {
  1122. try {
  1123. let globalOptionsForm = `<form id="globalOptionsForm" class="auto-task-form">
  1124. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  1125. for (const [ type, data1 ] of Object.entries(globalOptions)) {
  1126. for (const [ option, data2 ] of Object.entries(data1)) {
  1127. if ([ 'other', 'position', 'hotKey', 'ASF' ].includes(type)) {
  1128. if (typeof data2 === 'boolean') {
  1129. 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>`;
  1130. } else {
  1131. 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>`;
  1132. }
  1133. } else {
  1134. for (const [ socialType, data3 ] of Object.entries(data2)) {
  1135. 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>`;
  1136. }
  1137. }
  1138. }
  1139. }
  1140. globalOptionsForm += '</tbody></table></form>';
  1141. if (showType === 'swal') {
  1142. external_Swal_default().fire({
  1143. title: i18n('globalOptions'),
  1144. html: globalOptionsForm,
  1145. showConfirmButton: true,
  1146. confirmButtonText: i18n('save'),
  1147. showCancelButton: true,
  1148. cancelButtonText: i18n('close')
  1149. }).then(({
  1150. isConfirmed
  1151. }) => {
  1152. if (isConfirmed) {
  1153. saveData();
  1154. }
  1155. });
  1156. } else {
  1157. $('body').append(`<h2>${i18n('globalOptions')}</h2>${globalOptionsForm}`);
  1158. }
  1159. } catch (error) {
  1160. throwError(error, 'changeGlobalOptions');
  1161. }
  1162. };
  1163. const data = {
  1164. website: '网站',
  1165. type: '类型',
  1166. edit: '编辑',
  1167. whiteList: '白名单',
  1168. skipTask: '跳过撤销任务',
  1169. whiteListOptions: '白名单设置',
  1170. changeWhiteListOption: '设置白名单(%0)',
  1171. whiteListNotFound: '找不到此项白名单: %0',
  1172. changeWhiteListSuccess: '白名单修改成功,刷新生效!',
  1173. changeWebsiteOptions: '网站设置',
  1174. changeGlobalOptions: '全局设置',
  1175. ok: '是',
  1176. save: '保存',
  1177. close: '关闭',
  1178. return: '返回',
  1179. option: '选项',
  1180. value: '值',
  1181. websiteOptions: '当前网站设置',
  1182. changeWebsiteOptionsSuccess: '更改当前网站设置成功,刷新生效!',
  1183. changeGlobalOptionsSuccess: '更改全局设置成功,刷新生效!',
  1184. needLogin: '请先登录!',
  1185. getTasksInfo: '正在获取并处理任务信息...',
  1186. gettingKey: '正在获取Key...',
  1187. verifyingTask: '正在验证任务',
  1188. notice: '自动任务脚本提醒',
  1189. noKeysLeft: '此页面已经没有剩余key了,是否关闭?',
  1190. giveawayEnded: '此活动已结束,是否关闭?',
  1191. giveawayNotWork: '此活动因某些原因(已结束/暂停/未开始...)不可用(如果是脚本误判请及时反馈),是否关闭?',
  1192. confirm: '确定',
  1193. cancel: '取消',
  1194. unKnown: '未知',
  1195. unKnownTaskType: '未识别的任务',
  1196. doing: '正在做任务',
  1197. allTasksComplete: '所有任务已完成!',
  1198. getTaskIdFailed: '获取任务Id失败!',
  1199. initSuccess: '%0 初始化成功!',
  1200. initFailed: '%0 初始化失败!',
  1201. errorLink: '链接错误: %0',
  1202. needInit: '请先初始化',
  1203. verifyingAuth: '正在验证%0凭证...',
  1204. updatingAuth: '正在更新%0凭证...',
  1205. refreshingToken: '正在刷新%0凭证...',
  1206. settingToken: '正在设置%0凭证...',
  1207. steamStoreTab: 'Steam商店(弹窗)',
  1208. steamCommunityTab: 'Steam社区(弹窗)',
  1209. initing: '正在初始化...',
  1210. getFailed: '获取%0失败!',
  1211. checkLoginFailed: '检测登录状态失败!',
  1212. checkLeftKeyFailed: '检测剩余Key失败!',
  1213. userId: '用户Id',
  1214. joiningGiveaway: '正在加入赠Key',
  1215. needJoinGiveaway: '需要先加入赠Key',
  1216. cannotUndo: '此网站不支持取消任务',
  1217. verifyAuth: '正在验证 %0 凭证...',
  1218. closePageNotice: '如果此页面没有自动关闭,请自行关闭本页面。',
  1219. errorReport: '检测到脚本报错,是否前往反馈BUG?',
  1220. visitingLink: '正在访问链接: ',
  1221. doTask: '做任务',
  1222. undoTask: '撤销任务',
  1223. verifyTask: '验证任务',
  1224. getKey: '获取Key',
  1225. selectAll: '全选',
  1226. selectNone: '全不选',
  1227. invertSelect: '反选',
  1228. doFreeTask: '加入免费赠品',
  1229. doPointTask: '加入点数赠品',
  1230. skipTaskOption: '设置中已配置跳过任务',
  1231. other: '其他',
  1232. globalOptions: '全局设置',
  1233. checkLogin: '登录检测</br>需要登录的网站自动登录,部分网站支持',
  1234. checkLeftKey: '剩余Key检测</br>赠Key活动结束提示是否关闭,部分网站支持',
  1235. twitterVerifyId: '通过尝试关注该账号验证Twitter凭证</br>默认为Twitter官方帐号 783214</br>不想关注官方账号可以改为自己的帐号',
  1236. youtubeVerifyChannel: '通过尝试订阅该频道验证YouTube凭证</br>默认为YouTube官方频道 UCrXUsMBcfTVqwAS7DKg9C0Q</br>不想关注官方频道可以改为自己的频道',
  1237. autoUpdateSource: '更新源</br>github: 需代理,实时更新</br>jsdelivr: 可不用代理,更新有延迟</br>standby: 备用</br>auto: 依次使用github, jsdelivr, standby源进行尝试更新',
  1238. saveGlobalOptions: '保存设置',
  1239. settingPage: '设置页面',
  1240. name: '名称',
  1241. version: '版本',
  1242. scriptManager: '脚本管理器',
  1243. script: '脚本',
  1244. environment: '环境',
  1245. os: '系统',
  1246. browser: '浏览器',
  1247. getId: '获取 %0 id',
  1248. getTwitterUserId: '获取Twitter用户id(获取id功能仅在设置页面可用)',
  1249. getYoutubeChannelId: '获取Youtube频道id(获取id功能仅在设置页面可用)',
  1250. showButton: '显示按钮',
  1251. hideButton: '隐藏按钮',
  1252. showLog: '显示日志',
  1253. hideLog: '隐藏日志',
  1254. defaultShowButton: '默认显示按钮',
  1255. defaultShowLog: '默认显示日志',
  1256. debug: '输出调试日志,不要开启此选项!',
  1257. receivePreview: '接收预览版更新',
  1258. position: '组件位置',
  1259. buttonSideX: '按钮区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1260. buttonSideY: '按钮区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1261. buttonDistance: '按钮区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1262. showButtonSideX: '显示按钮水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1263. showButtonSideY: '显示按钮垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1264. showButtonDistance: '显示按钮距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1265. logSideX: '日志区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1266. logSideY: '日志区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1267. logDistance: '日志区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1268. hotKey: '快捷键',
  1269. doTaskKey: '做任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1270. undoTaskKey: '撤销任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1271. toggleLogKey: '显示/隐藏日志快捷键</br>(实时预览功能仅在设置页面可用)',
  1272. tasksHistory: '任务历史',
  1273. clearHistory: '清空历史',
  1274. clearHistoryFinished: '已清空任务历史!',
  1275. deleteTask: '删除任务',
  1276. lastChangeTime: '最后一次修改时间',
  1277. clearTaskFinished: '删除以下任务完成!',
  1278. clearTaskFailed: '删除任务失败,没有找到任务名!',
  1279. syncData: '数据同步',
  1280. settingData: '正在上传数据...',
  1281. gettingData: '正在获取数据...',
  1282. help: '帮助',
  1283. fileName: '文件名',
  1284. upload2gist: '同步到Gist',
  1285. downloadFromGist: '从Gist同步',
  1286. saveAndTest: '保存配置并测试',
  1287. testSuccess: '测试成功!',
  1288. testFailed: '测试失败!',
  1289. saveAndTestNotice: '请先保存配置并测试!',
  1290. processingData: '正在处理数据...',
  1291. updatingData: '正在上传数据...',
  1292. syncDataSuccess: '同步数据成功!',
  1293. syncDataFailed: '同步数据失败,请在控制台查看错误信息!',
  1294. downloadingData: '正在下载数据...',
  1295. checkedNoData: '没有检测到远程数据,请确认配置是否正确!',
  1296. savingData: '正在保存数据...',
  1297. syncHistory: '同步任务历史',
  1298. checkUpdateFailed: '检测更新失败',
  1299. newVersionNotice: '检测到新版本V%0, <a class="high-light" href="%1" target="_blank">点此更新</a>',
  1300. language: '语言</br>目前仅支持zh: 中文, en: 英文',
  1301. gistOptions: 'Gist 设置',
  1302. swalNotice: '检测到您第一次安装V4版本脚本,请前往阅读用前必读内容!',
  1303. echoNotice: '检测到您第一次安装V4版本脚本,请<a class="high-light" href="%0" target="_blank">点此前往</a>阅读用前必读内容!',
  1304. noticeLink: 'https://auto-task-doc.js.org/guide/#用前必读',
  1305. toGithub: '前往Github反馈',
  1306. toKeylol: '前往其乐论坛反馈',
  1307. copySuccess: '错误信息已复制到剪切板,是否前往其乐论坛反馈?',
  1308. copyFailed: '请复制下方错误信息后前往Keylol论坛反馈!',
  1309. updateText: '%0 版本更新内容:',
  1310. Active: '进行中',
  1311. Ended: '已结束',
  1312. Banned: '已封禁',
  1313. Paused: '已暂停',
  1314. notStart: '未开始',
  1315. noRemoteData: '检测到远程无数据',
  1316. errorRemoteDataFormat: '远程数据格式错误',
  1317. updateHistory: '历史更新记录<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">点此查看</a>',
  1318. AsfEnabled: '使用ASF做Steam相关任务(需<a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a>插件)',
  1319. AsfIpcUrl: 'ASF IPC 地址',
  1320. AsfIpcPassword: 'ASF IPC 密码',
  1321. versionNotMatched: '脚本管理器版本过低,需TamperMonkey >= 5.2.0或TamperMonkey Beta >= 5.2.6196',
  1322. groups: '组',
  1323. officialGroups: '官方组',
  1324. wishlists: '愿望单',
  1325. follows: '游戏关注',
  1326. forums: '论坛',
  1327. workshops: '创意工坊收藏',
  1328. curators: '鉴赏家',
  1329. workshopVotes: '创意工坊点赞',
  1330. announcements: '社区通知',
  1331. steamCommunity: 'Steam社区',
  1332. steamStore: 'Steam商店',
  1333. licenses: '入库免费游戏',
  1334. playtests: '请求访问权限',
  1335. needLoginSteamStore: '请先<a href="https://store.steampowered.com/login/" target="_blank">登录Steam商店</a>',
  1336. needLoginSteamCommunity: '请先<a href="https://steamcommunity.com/login/home/" target="_blank">登录Steam社区</a>',
  1337. joiningSteamGroup: '正在加入Steam组',
  1338. leavingSteamGroup: '正在退出Steam组',
  1339. gettingSteamGroupId: '正在获取Steam组Id',
  1340. joiningSteamOfficialGroup: '正在加入Steam官方组',
  1341. leavingSteamOfficialGroup: '正在退出Steam官方组',
  1342. gettingSteamOfficialGroupId: '正在获取Steam官方组Id',
  1343. subscribingForum: '正在订阅Steam论坛',
  1344. unsubscribingForum: '正在取消订阅Steam论坛',
  1345. gettingForumId: '正在获取Steam论坛Id',
  1346. followingCurator: '正在关注Steam鉴赏家',
  1347. unfollowingCurator: '正在取关Steam鉴赏家',
  1348. gettingCuratorId: '正在获取Steam鉴赏家Id',
  1349. addingToWishlist: '正在添加游戏到Steam愿望单',
  1350. removingFromWishlist: '正在从Steam愿望单移除游戏',
  1351. followingGame: '正在关注Steam游戏',
  1352. unfollowingGame: '正在取关Steam游戏',
  1353. favoritingWorkshop: '正在收藏Steam创意工坊物品',
  1354. unfavoritingWorkshop: '正在取消收藏Steam创意工坊物品',
  1355. gettingWorkshopAppId: '正在获取Steam创意工坊物品Id',
  1356. votingUpWorkshop: '正在点赞Steam创意工坊物品',
  1357. gettingAnnouncementParams: '正在获取Steam通知信息',
  1358. likingAnnouncement: '正在点赞Steam通知',
  1359. changingArea: '正在更换Steam地区: %0...',
  1360. notNeededChangeArea: '当前地区不需要更换',
  1361. noAnotherArea: '请检测是否开启正确开启代理',
  1362. gettingAreaInfo: '正在获取Steam地区信息...',
  1363. changeAreaNotice: '疑似锁区游戏,尝试换区执行',
  1364. steamFinishNotice: 'Steam任务完成,尝试将购物车地区换回',
  1365. gettingSubid: '正在获取游戏subid',
  1366. addingFreeLicense: '正在入库',
  1367. missParams: '缺少参数',
  1368. gettingLicenses: '正在获取Licenses...',
  1369. requestingPlayTestAccess: '正在请求访问权限',
  1370. tryChangeAreaNotice: '此功能无法检测游戏是否限区,因此会尝试换区后再入库,换区失败也不影响后续入库',
  1371. gettingUserLink: '正在获取Steam用户社区链接...',
  1372. retry: '重试',
  1373. owned: '已拥有',
  1374. redirect: '重定向',
  1375. noSubid: '无法获取,跳过',
  1376. initingASF: '正在初始化ASF...',
  1377. servers: '服务器',
  1378. joiningDiscordServer: '正在加入Discord服务器',
  1379. leavingDiscordServer: '正在退出Discord服务器',
  1380. gettingDiscordGuild: '正在获取Discord服务器Id',
  1381. getDiscordAuthFailed: '获取Discord凭证失败,请检测Discord帐号是否已登录',
  1382. discordImportantNotice: '重要提醒!!!',
  1383. discordImportantNoticeText: '由于Discord网站后台更新,目前使用此脚本加组后可能会导致Discord帐号被强制退出,且需要两步验证才能正常登录,请谨慎使用!!!',
  1384. continue: '继续',
  1385. skipDiscordTask: '跳过Discord任务',
  1386. continueAndDontRemindAgain: '继续且不再提醒',
  1387. users: '用户',
  1388. loginIns: '请先<a href="https://www.instagram.com/accounts/login/" target="_blank">登录Instagram</a>',
  1389. insBanned: '您的Instagram账户已被封禁',
  1390. verifyingInsAuth: '正在验证Instagram凭证...',
  1391. gettingInsUserId: '正在获取Instagram用户Id',
  1392. followingIns: '正在关注Instagram用户',
  1393. unfollowingIns: '正在取关Instagram用户',
  1394. reddits: '社区/用户',
  1395. loginReddit: '请先<a href="https://www.reddit.com/login/" target="_blank">登录Reddit</a>',
  1396. changingRedditVersion: '正在切换Reddit为新版页面...',
  1397. joiningReddit: '正在加入Reddit社区',
  1398. leavingReddit: '正在退出Reddit社区',
  1399. followingRedditUser: '正在关注Reddit用户',
  1400. unfollowingRedditUser: '正在取关Reddit用户',
  1401. channels: '频道',
  1402. followingTwitchChannel: '正在关注Twitch频道',
  1403. unfollowingTwitchChannel: '正在取关Twitch频道',
  1404. gettingTwitchChannelId: '正在获取Twitch频道Id',
  1405. checkingTwitchIntegrity: '正在检查Twitch完整性...',
  1406. twitterUser: '推特用户',
  1407. retweets: '转推',
  1408. gettingTwitterUserId: '正在获取推特用户Id',
  1409. followingTwitterUser: '正在关注推特用户',
  1410. unfollowingTwitterUser: '正在取关推特用户',
  1411. retweetting: '正在转推',
  1412. unretweetting: '正在撤销转推',
  1413. names: '组/社区/动态',
  1414. loginVk: '请先<a href="https://vk.com/login/" target="_blank">登录Vk</a>',
  1415. gettingVkId: '正在获取Vk任务Id',
  1416. joiningVkGroup: '正在加入Vk组',
  1417. leavingVkGroup: '正在退出Vk组',
  1418. joiningVkPublic: '正在加入Vk社区',
  1419. leavingVkPublic: '正在退出Vk社区',
  1420. sendingVkWall: '正在转发Vk动态',
  1421. deletingVkWall: '正在撤销转发Vk动态',
  1422. youtubeChannel: 'YouTube频道',
  1423. likes: '点赞',
  1424. loginYtb: '请先<a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">登录YouTube</a>',
  1425. tryUpdateYtbAuth: '请尝试<a href="https://www.youtube.com/#auth" target="_blank">更新YouTube凭证</a>',
  1426. gettingYtbToken: '正在获取YouTube Token...',
  1427. followingYtbChannel: '正在订阅YouTube频道',
  1428. unfollowingYtbChannel: '正在退订YouTube频道',
  1429. likingYtbVideo: '正在点赞YouTube视频',
  1430. unlikingYtbVideo: '正在取消点赞YouTube视频',
  1431. giveKeyNoticeBefore: '每次验证间隔15s',
  1432. giveKeyNoticeAfter: '如果没有key, 请在<a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>查看',
  1433. noPoints: '点数不够,跳过抽奖',
  1434. getNeedPointsFailed: '获取所需点数失败,跳过抽奖',
  1435. joiningLottery: '正在加入抽奖',
  1436. doingGleamTask: '正在做Gleam任务...',
  1437. gettingGleamLink: '正在获取Gleam任务链接...',
  1438. gleamTaskNotice: '如果此页面长时间未关闭,请完成任一任务后自行关闭!',
  1439. verifiedGleamTasks: '已尝试验证所有任务,验证失败的任务请尝试手动验证或完成!',
  1440. campaign: '检测到人机验证,请完成验证后重新验证任务!',
  1441. gsNotice: '为避免得到"0000-0000-0000"key, 已自动屏蔽"Grab Key"按钮,获取key时请关闭脚本!',
  1442. giveeClubVerifyNotice: '正在验证任务...',
  1443. giveeClubVerifyFinished: '请等待验证完成后自行加入赠Key',
  1444. doingKeyhubTask: '正在做Keyhub任务...',
  1445. SweepWidgetNotice: '正在处理并验证任务,每次验证任务有1~3s间隔防止触发验证过快警告...',
  1446. tasksNotCompleted: '任务未完成',
  1447. confirmingTask: '正在跳过警告页面...'
  1448. };
  1449. const zh_CN = data;
  1450. const en_US_data = {
  1451. website: 'Website',
  1452. type: 'Type',
  1453. edit: 'Edit',
  1454. whiteList: 'Whitelist',
  1455. skipTask: 'Skip undo task',
  1456. whiteListOptions: 'Whitelist options',
  1457. changeWhiteListOption: 'Whitelist option(%0)',
  1458. whiteListNotFound: 'Cannot find this whitelist: %0',
  1459. changeWhiteListSuccess: 'The whitelist is successfully modified, and the page refresh will take effect!',
  1460. changeWebsiteOptions: 'Website options',
  1461. changeGlobalOptions: 'Global options',
  1462. ok: 'OK',
  1463. save: 'Save',
  1464. close: 'Close',
  1465. return: 'Return',
  1466. option: 'Option',
  1467. value: 'Value',
  1468. websiteOptions: 'Current website settings',
  1469. changeWebsiteOptionsSuccess: 'The current website setting is changed successfully, and the page refresh will take effect!',
  1470. changeGlobalOptionsSuccess: 'The global setting is changed successfully, and the refresh will take effect!',
  1471. needLogin: 'Please log in first!',
  1472. getTasksInfo: 'Obtaining and processing task information...',
  1473. gettingKey: 'Getting Key...',
  1474. verifyingTask: 'Verifying task',
  1475. notice: 'Automatic task script notice',
  1476. noKeysLeft: 'There are no more keys left on this page. Do you want to close it?',
  1477. giveawayEnded: 'This event has ended, do you want to close it?',
  1478. 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?',
  1479. confirm: 'Confirm',
  1480. cancel: 'Cancel',
  1481. unKnown: 'Unknown',
  1482. unKnownTaskType: 'Unrecognized task',
  1483. doing: 'Doing a task',
  1484. allTasksComplete: 'All tasks have been completed!',
  1485. getTaskIdFailed: 'Failed to obtain task Id!',
  1486. initSuccess: '%0 was initialized successfully!',
  1487. initFailed: '%0 initialization failed!',
  1488. errorLink: 'Link error: %0',
  1489. needInit: 'Please initialize first',
  1490. verifyingAuth: 'Verifying %0 token...',
  1491. updatingAuth: 'Update %0 token...',
  1492. refreshingToken: 'Refreshing %0 token...',
  1493. settingToken: 'Setting %0 token...',
  1494. steamStoreTab: 'Steam store (new tab)',
  1495. steamCommunityTab: 'Steam community(new tab)',
  1496. initing: 'Initializing...',
  1497. getFailed: 'Failed to get %0!',
  1498. checkLoginFailed: 'Failed to detect login status!',
  1499. checkLeftKeyFailed: 'Failed to detect the remaining keys!',
  1500. userId: 'User Id',
  1501. joiningGiveaway: 'Joining giveaway',
  1502. needJoinGiveaway: 'Need to join the giveaway first',
  1503. cannotUndo: 'This website does not support canceling tasks',
  1504. verifyAuth: 'Verifying %0 token...',
  1505. closePageNotice: 'f this page does not close automatically, please close this page yourself.',
  1506. errorReport: 'A script error is detected, do you want to report the BUG?',
  1507. visitingLink: 'Visiting link: ',
  1508. doTask: 'DoTask',
  1509. undoTask: 'UndoTask',
  1510. verifyTask: 'Verify',
  1511. getKey: 'GetKey',
  1512. selectAll: 'SelectAll',
  1513. selectNone: 'SelectNone',
  1514. invertSelect: 'InvertSelect',
  1515. doFreeTask: 'FreeTask',
  1516. doPointTask: 'PointTask',
  1517. skipTaskOption: 'Skip task has been configured in the settings',
  1518. other: 'Other',
  1519. globalOptions: 'Global Options',
  1520. checkLogin: 'Login detection</br>Need to log in to the website automatically log in, part of this website supports.',
  1521. checkLeftKey: 'Key remaining detection</br>The end of the giveaway event prompts whether to close or not, part of this website supports.',
  1522. 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.',
  1523. 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.',
  1524. 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.',
  1525. saveGlobalOptions: 'SaveSettings',
  1526. settingPage: 'Setting Page',
  1527. name: 'Name',
  1528. version: 'Version',
  1529. scriptManager: 'Script Manager',
  1530. script: 'Script',
  1531. environment: 'Environment',
  1532. os: 'OS',
  1533. browser: 'Browser',
  1534. getId: 'Get %0 id',
  1535. getTwitterUserId: 'Get Twitter user id (Get id function is only available on the settings page).',
  1536. getYoutubeChannelId: 'Get Youtube channel id (Get id function is only available on the settings page).',
  1537. showButton: 'ShowButton',
  1538. hideButton: 'HideButton',
  1539. showLog: 'ShowLog',
  1540. hideLog: 'HideLog',
  1541. defaultShowButton: 'Default display button',
  1542. defaultShowLog: 'Display log by default',
  1543. debug: 'Output debug log, do not enable this option!',
  1544. receivePreview: 'Receive preview updates',
  1545. position: 'Component position',
  1546. buttonSideX: 'Horizontal positioning of the button area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1547. 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',
  1548. 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',
  1549. showButtonSideX: 'ShowButton horizontal positioning (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1550. showButtonSideY: 'ShowButton vertical positioning (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  1551. 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',
  1552. logSideX: 'Horizontal positioning of the log area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1553. logSideY: 'Vertical positioning of the log area (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  1554. 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',
  1555. hotKey: 'Shortcut key',
  1556. doTaskKey: 'DoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  1557. undoTaskKey: 'UndoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  1558. toggleLogKey: 'ShowLog/HideLog shortcut keys</br> (real-time preview function is only available on the settings page).',
  1559. tasksHistory: 'TasksHistory',
  1560. clearHistory: 'Clear history',
  1561. clearHistoryFinished: 'The mission history has been cleared!',
  1562. deleteTask: 'Delete task',
  1563. lastChangeTime: 'Last Change Time',
  1564. clearTaskFinished: 'Delete the following tasks completed!',
  1565. clearTaskFailed: 'Failed to delete the task, the task name was not found!',
  1566. syncData: 'DataSync',
  1567. settingData: 'Uploading data...',
  1568. gettingData: 'Getting data...',
  1569. help: 'Help',
  1570. fileName: 'Filename',
  1571. upload2gist: 'Sync to Gist',
  1572. downloadFromGist: 'Sync from Gist',
  1573. saveAndTest: 'Save configuration and test',
  1574. testSuccess: 'Test success!',
  1575. testFailed: 'Test failed!',
  1576. saveAndTestNotice: 'Please save the configuration and test first!',
  1577. processingData: 'Processing data...',
  1578. updatingData: 'Uploading data...',
  1579. syncDataSuccess: 'Synchronized data successfully!',
  1580. syncDataFailed: 'Failed to synchronize data, please check the error message on the console!',
  1581. downloadingData: 'Downloading data...',
  1582. checkedNoData: 'No remote data is detected, please confirm whether the configuration is correct!',
  1583. savingData: 'Saving data...',
  1584. syncHistory: 'Synchronize tasks history',
  1585. checkUpdateFailed: 'Check update failed',
  1586. newVersionNotice: 'Checked a new version V%0, <a class="high-light" href="%1" target="_blank">click to update</a>',
  1587. language: 'Language</br> Currently only supports zh: Chinese, en: English',
  1588. gistOptions: 'Gist Settings',
  1589. 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!',
  1590. 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!',
  1591. noticeLink: 'https://auto-task-doc.js.org/en/guide/#read-me-first',
  1592. toGithub: 'Feedback(Github)',
  1593. toKeylol: 'Feedback(Keylol)',
  1594. copySuccess: 'The error message has been copied to the clipboard. Do you want to go to the Keylol forum to give feedback?',
  1595. copyFailed: 'Please copy the error information below and report back to the Keylol forum!',
  1596. updateText: 'Updates in version %0:',
  1597. Active: 'Active',
  1598. Ended: 'Ended',
  1599. Banned: 'Banned',
  1600. Paused: 'Paused',
  1601. notStart: 'notStart',
  1602. noRemoteData: 'No data remotely',
  1603. errorRemoteDataFormat: 'Remote data has wrong format',
  1604. updateHistory: '<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">Click here</a>' + ' to view the historical update record.',
  1605. AsfEnabled: 'Use ASF to do Steam related tasks (requires <a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a> plugin)',
  1606. AsfIpcUrl: 'ASF IPC URL',
  1607. AsfIpcPassword: 'ASF IPC Password',
  1608. groups: 'Group',
  1609. officialGroups: 'Official Group',
  1610. wishlists: 'Wishlist',
  1611. follows: 'Follow Game',
  1612. forums: 'Forum',
  1613. workshops: 'Favorite Workshop',
  1614. curators: 'Curator',
  1615. workshopVotes: 'Voteup Workshop',
  1616. announcements: 'Announcement',
  1617. steamCommunity: 'Steam Community',
  1618. steamStore: 'Steam Store',
  1619. licenses: 'Add License',
  1620. playtests: 'Playtest Access',
  1621. needLoginSteamStore: 'Please <a href="https://store.steampowered.com/login/" target="_blank">log in to the Steam Store</a>',
  1622. needLoginSteamCommunity: 'Please <a href="https://steamcommunity.com/login/home/" target="_blank">log in to the Steam Community</a>',
  1623. joiningSteamGroup: 'Joining Steam Group',
  1624. leavingSteamGroup: 'Leaving Steam Group',
  1625. gettingSteamGroupId: 'Getting Steam Group Id',
  1626. joiningSteamOfficialGroup: 'Joining Steam Official Group',
  1627. leavingSteamOfficialGroup: 'Leaving Steam Official Group',
  1628. gettingSteamOfficialGroupId: 'Getting Steam Official Group Id',
  1629. subscribingForum: 'Subscribing the Steam Forum',
  1630. unsubscribingForum: 'Unsubscribing the Steam Forum',
  1631. gettingForumId: 'Getting Steam Forum Id',
  1632. followingCurator: 'Following Steam Curator',
  1633. unfollowingCurator: 'Unfollowing Steam Curator',
  1634. gettingCuratorId: 'Getting Steam Curator Id',
  1635. addingToWishlist: 'Adding the game to the Steam wishlist',
  1636. removingFromWishlist: 'Removing the game from the Steam wishlist',
  1637. followingGame: 'Following Steam games',
  1638. unfollowingGame: 'Unfollowing Steam games',
  1639. favoritingWorkshop: 'Favouring Steam Workshop Items',
  1640. unfavoritingWorkshop: 'Unfavoriting Steam Workshop Items',
  1641. gettingWorkshopAppId: 'Getting Steam Workshop Item Id',
  1642. votingUpWorkshop: 'Liking Steam workshop items',
  1643. gettingAnnouncementParams: 'Getting Steam announcement information',
  1644. likingAnnouncement: 'Liking Steam announcement',
  1645. changingArea: 'Changing Steam area: %0...',
  1646. notNeededChangeArea: 'The current area does not need to be changed',
  1647. noAnotherArea: 'Please check whether the proxy is turned on correctly',
  1648. gettingAreaInfo: 'Getting Steam area information...',
  1649. changeAreaNotice: 'Suspected of a locked zone game, try to change the zone to execute',
  1650. steamFinishNotice: 'Steam task completed, try to change the shopping cart area back to ',
  1651. gettingSubid: 'Getting subid',
  1652. addingFreeLicense: 'Adding free license',
  1653. missParams: 'Missing parameters',
  1654. gettingLicenses: 'Getting licenses...',
  1655. requestingPlayTestAccess: 'Requesting play test access',
  1656. 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.',
  1657. versionNotMatched: 'The script manager version is too low, requiring TamperMonkey >= 5.2.0 or TamperMonkey Beta >= 5.2.6196',
  1658. gettingUserLink: 'Getting steam user community link...',
  1659. retry: 'Retry',
  1660. owned: 'Owned',
  1661. redirect: 'Redirect',
  1662. noSubid: 'skip due to unrecognized',
  1663. initingASF: 'Initing ASF...',
  1664. servers: 'Server',
  1665. joiningDiscordServer: 'Joining Discord Server',
  1666. leavingDiscordServer: 'Leaving Discord Server',
  1667. gettingDiscordGuild: 'Getting Discord server Id',
  1668. getDiscordAuthFailed: 'Failed to get Discord token, please check whether the Discord account is logged in',
  1669. discordImportantNotice: 'Important Reminder! ! !',
  1670. 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! ! !',
  1671. continue: 'Continue',
  1672. skipDiscordTask: 'Skip',
  1673. continueAndDontRemindAgain: 'Continue without Reminders',
  1674. users: 'User',
  1675. loginIns: 'Please <a href="https://www.instagram.com/accounts/login/" target="_blank">log in to Instagram</a>',
  1676. insBanned: 'Your Instagram account has been banned',
  1677. verifyingInsAuth: 'Verifying Instagram token...',
  1678. gettingInsUserId: 'Getting Instagram user Id',
  1679. followingIns: 'Following Instagram user',
  1680. unfollowingIns: 'Unfollowing Instagram user',
  1681. reddits: 'Reddit/User',
  1682. loginReddit: 'Please <a href="https://www.reddit.com/login/" target="_blank">log in to Reddit</a>',
  1683. changingRedditVersion: 'Switching Reddit to a new version page...',
  1684. joiningReddit: 'Joining the Reddit',
  1685. leavingReddit: 'Leaving the Reddit',
  1686. followingRedditUser: 'Following Reddit User',
  1687. unfollowingRedditUser: 'Unfollowing Reddit User',
  1688. channels: 'Channel',
  1689. followingTwitchChannel: 'Following Twitch Channel',
  1690. unfollowingTwitchChannel: 'Unfollowing Twitch Channel',
  1691. gettingTwitchChannelId: 'Getting Twitch Channel Id',
  1692. checkingTwitchIntegrity: 'Checking Twitch integrity...',
  1693. twitterUser: 'Twitter User',
  1694. retweets: 'Retweet',
  1695. gettingTwitterUserId: 'Getting Twitter User Id',
  1696. followingTwitterUser: 'Following Twitter User',
  1697. unfollowingTwitterUser: 'Unfollowing Twitter User',
  1698. retweetting: 'Retweetting',
  1699. unretweetting: 'Unretweetting',
  1700. names: 'Group/Public/Wall',
  1701. loginVk: 'Please <a href="https://vk.com/login/" target="_blank">log in to Vk</a>',
  1702. gettingVkId: 'Getting Vk task Id',
  1703. joiningVkGroup: 'Joining Vk Group',
  1704. leavingVkGroup: 'Leaving Vk Group',
  1705. joiningVkPublic: 'Joining Vk Public',
  1706. leavingVkPublic: 'Leaving Vk Public',
  1707. sendingVkWall: 'Sending Vk Wall',
  1708. deletingVkWall: 'Deleting Vk Wall',
  1709. youtubeChannel: 'YouTube Channel',
  1710. likes: 'Like',
  1711. loginYtb: 'Please <a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">log in to YouTube</a>',
  1712. tryUpdateYtbAuth: 'Please try to <a href="https://www.youtube.com/#auth" target="_blank">update YouTube token</a>',
  1713. gettingYtbToken: 'Getting YouTube Token...',
  1714. followingYtbChannel: 'Subscribing to YouTube channel',
  1715. unfollowingYtbChannel: 'Unsubscribing to YouTube channel',
  1716. likingYtbVideo: 'Liking YouTube video',
  1717. unlikingYtbVideo: 'Unliking YouTube video',
  1718. giveKeyNoticeBefore: 'Each verification interval is 15s',
  1719. giveKeyNoticeAfter: 'If there is no key, please check at <a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>',
  1720. noPoints: 'Not enough points, skip the lottery',
  1721. getNeedPointsFailed: 'ailed to obtain the required points, skip the lottery',
  1722. joiningLottery: 'Joining the lottery',
  1723. doingGleamTask: 'Doing Gleam Task...',
  1724. gettingGleamLink: 'Getting Gleam task link...',
  1725. gleamTaskNotice: 'If this page has not been closed for a long time, please close it yourself after completing any task!',
  1726. verifiedGleamTasks: 'Attempted to verify all tasks. If the verification fails, please try to verify manually or complete it!',
  1727. campaign: 'ReCAPTCHA detected, please complete it and re-verify the tasks!',
  1728. 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!',
  1729. giveeClubVerifyNotice: 'Verifying task...',
  1730. giveeClubVerifyFinished: 'Wait for the verification to complete and join it by yourself',
  1731. doingKeyhubTask: 'Doing Keyhub Task...',
  1732. 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...',
  1733. tasksNotCompleted: 'Tasks Not Completed',
  1734. confirmingTask: 'Confirming task...'
  1735. };
  1736. const en_US = en_US_data;
  1737. const languages = {
  1738. zh: zh_CN,
  1739. en: en_US
  1740. };
  1741. const language = [ 'zh', 'en' ].includes(globalOptions.other.language) ? globalOptions.other.language : 'en';
  1742. const I18n = (key, ...argvs) => {
  1743. if (!languages[language]?.[key]) {
  1744. return key;
  1745. }
  1746. return languages[language][key].replace(/%([\d]+)/g, (match, index) => argvs[parseInt(index, 10)]);
  1747. };
  1748. const i18n = I18n;
  1749. function throwError(error, name) {
  1750. if (window.TRACE) {
  1751. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  1752. }
  1753. external_Swal_default().fire({
  1754. title: i18n('errorReport'),
  1755. icon: 'error',
  1756. showCancelButton: true,
  1757. confirmButtonText: i18n('toGithub'),
  1758. showDenyButton: true,
  1759. denyButtonText: i18n('toKeylol'),
  1760. cancelButtonText: i18n('close')
  1761. }).then(({
  1762. isDenied,
  1763. isConfirmed
  1764. }) => {
  1765. if (isConfirmed) {
  1766. 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,
  1767. 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'))}`, {
  1768. active: true
  1769. });
  1770. } else if (isDenied) {
  1771. const text = `错误链接: [url=${window.location.href}]${window.location.href}[/url]
  1772.  
  1773. 环境:
  1774.  
  1775. [code]${JSON.stringify((0, javascript_utils_umd_min.ua)(), null, 4)}[/code]
  1776.  
  1777. 脚本管理器: ${GM_info.scriptHandler} ${GM_info.version}
  1778. 脚本版本: ${GM_info.script.version}
  1779.  
  1780. 报错信息:
  1781. [code]${error.stack}[/code]
  1782.  
  1783. 执行日志:
  1784. [code]${$.makeArray($('#auto-task-info>li')).map(element => element.innerText).join('\n')}[/code]`;
  1785. GM_setClipboard(text);
  1786. external_Swal_default().fire({
  1787. title: i18n('copySuccess'),
  1788. icon: 'success',
  1789. confirmButtonText: i18n('ok')
  1790. }).then(() => {
  1791. GM_openInTab('https://keylol.com/forum.php?mod=post&action=reply&fid=319&tid=777450', {
  1792. active: true
  1793. });
  1794. });
  1795. }
  1796. });
  1797. console.log('%c%s', 'color:white;background:red', `Auto-Task[Error]: ${name}\n${error.stack}`);
  1798. }
  1799. class Social {
  1800. tasks;
  1801. getRealParams(name, links, doTask, link2param) {
  1802. try {
  1803. let realParams = [];
  1804. if (links.length > 0) {
  1805. realParams = [ ...realParams, ...links.map(link => link2param(link)).filter(link => link) ];
  1806. }
  1807. if (!doTask && this.tasks[name].length > 0) {
  1808. realParams = [ ...realParams, ...this.tasks[name] ];
  1809. }
  1810. return unique(realParams);
  1811. } catch (error) {
  1812. throwError(error, 'Social.getRealParams');
  1813. return [];
  1814. }
  1815. }
  1816. }
  1817. const social_Social = Social;
  1818. class Discord extends social_Social {
  1819. tasks;
  1820. whiteList;
  1821. #auth = GM_getValue('discordAuth') || {};
  1822. #cache = GM_getValue('discordCache') || {};
  1823. #initialized = false;
  1824. constructor() {
  1825. super();
  1826. const defaultTasksTemplate = {
  1827. servers: []
  1828. };
  1829. this.tasks = defaultTasksTemplate;
  1830. this.whiteList = {
  1831. ...defaultTasksTemplate,
  1832. ...GM_getValue('whiteList')?.discord || {}
  1833. };
  1834. }
  1835. async init(action) {
  1836. try {
  1837. if (!GM_getValue('dontRemindDiscordAgain')) {
  1838. const result = await external_Swal_default().fire({
  1839. title: i18n('discordImportantNotice'),
  1840. text: i18n('discordImportantNoticeText'),
  1841. showCancelButton: true,
  1842. showDenyButton: true,
  1843. confirmButtonText: i18n('continue'),
  1844. cancelButtonText: i18n('skipDiscordTask'),
  1845. denyButtonText: i18n('continueAndDontRemindAgain')
  1846. }).then(({
  1847. isConfirmed,
  1848. isDenied
  1849. }) => {
  1850. if (isConfirmed) {
  1851. return true;
  1852. }
  1853. if (isDenied) {
  1854. GM_setValue('dontRemindDiscordAgain', true);
  1855. return true;
  1856. }
  1857. return false;
  1858. });
  1859. if (!result) {
  1860. this.#initialized = false;
  1861. return 'skip';
  1862. }
  1863. }
  1864. if (GM_getValue('dontRemindDiscordAgain') || action === 'do' && !globalOptions.doTask.discord.servers || action === 'undo' && !globalOptions.undoTask.discord.servers) {
  1865. this.#initialized = false;
  1866. return 'skip';
  1867. }
  1868. if (this.#initialized) {
  1869. return true;
  1870. }
  1871. if (!this.#auth.auth) {
  1872. if (await this.#updateAuth()) {
  1873. this.#initialized = true;
  1874. return true;
  1875. }
  1876. return false;
  1877. }
  1878. const isVerified = await this.#verifyAuth();
  1879. if (isVerified) {
  1880. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  1881. this.#initialized = true;
  1882. return true;
  1883. }
  1884. GM_setValue('discordAuth', {
  1885. auth: null
  1886. });
  1887. if (await this.#updateAuth()) {
  1888. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  1889. this.#initialized = true;
  1890. return true;
  1891. }
  1892. scripts_echoLog({}).error(i18n('initFailed', 'Discord'));
  1893. return false;
  1894. } catch (error) {
  1895. throwError(error, 'Discord.init');
  1896. return false;
  1897. }
  1898. }
  1899. async #verifyAuth() {
  1900. try {
  1901. const logStatus = scripts_echoLog({
  1902. text: i18n('verifyingAuth', 'Discord')
  1903. });
  1904. const {
  1905. result,
  1906. statusText,
  1907. status,
  1908. data
  1909. } = await tools_httpRequest({
  1910. url: 'https://discord.com/api/v6/users/@me',
  1911. method: 'HEAD',
  1912. headers: {
  1913. authorization: this.#auth.auth
  1914. }
  1915. });
  1916. if (result === 'Success') {
  1917. if (data?.status === 200) {
  1918. logStatus.success();
  1919. return true;
  1920. }
  1921. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  1922. return false;
  1923. }
  1924. logStatus.error(`${result}:${statusText}(${status})`);
  1925. return false;
  1926. } catch (error) {
  1927. throwError(error, 'Discord.verifyAuth');
  1928. return false;
  1929. }
  1930. }
  1931. async #updateAuth() {
  1932. try {
  1933. const logStatus = scripts_echoLog({
  1934. text: i18n('updatingAuth', 'Discord')
  1935. });
  1936. return await new Promise(resolve => {
  1937. const newTab = GM_openInTab('https://discord.com/channels/@me', {
  1938. active: true,
  1939. insert: true,
  1940. setParent: true
  1941. });
  1942. newTab.name = 'ATv4_discordAuth';
  1943. newTab.onclose = async () => {
  1944. const auth = GM_getValue('discordAuth')?.auth;
  1945. if (auth) {
  1946. this.#auth = {
  1947. auth: auth
  1948. };
  1949. logStatus.success();
  1950. resolve(await this.#verifyAuth());
  1951. } else {
  1952. logStatus.error('Error: Update discord auth failed!');
  1953. resolve(false);
  1954. }
  1955. };
  1956. });
  1957. } catch (error) {
  1958. throwError(error, 'Discord.updateAuth');
  1959. return false;
  1960. }
  1961. }
  1962. async #joinServer(inviteId) {
  1963. try {
  1964. const logStatus = scripts_echoLog({
  1965. type: 'joiningDiscordServer',
  1966. text: inviteId
  1967. });
  1968. const {
  1969. result,
  1970. statusText,
  1971. status,
  1972. data
  1973. } = await tools_httpRequest({
  1974. url: `https://discord.com/api/v9/invites/${inviteId}`,
  1975. method: 'POST',
  1976. dataType: 'json',
  1977. headers: {
  1978. authorization: this.#auth.auth,
  1979. origin: 'https://discord.com',
  1980. referer: `https://discord.com/invite/${inviteId}`
  1981. }
  1982. });
  1983. if (result === 'Success' && data?.status === 200) {
  1984. logStatus.success();
  1985. const guild = String(data.response?.guild?.id);
  1986. if (guild) {
  1987. this.#setCache(inviteId, guild);
  1988. this.tasks.servers = unique([ ...this.tasks.servers, inviteId ]);
  1989. }
  1990. return true;
  1991. }
  1992. logStatus.error(`${result}:${statusText}(${status})`);
  1993. return false;
  1994. } catch (error) {
  1995. throwError(error, 'Discord.joinServer');
  1996. return false;
  1997. }
  1998. }
  1999. async #leaveServer(inviteId) {
  2000. try {
  2001. if (this.whiteList.servers.includes(inviteId)) {
  2002. scripts_echoLog({
  2003. type: 'whiteList',
  2004. text: 'Discord.leaveServer',
  2005. id: inviteId
  2006. });
  2007. return true;
  2008. }
  2009. const guild = await this.#getGuild(inviteId);
  2010. if (!guild) {
  2011. return false;
  2012. }
  2013. const logStatus = scripts_echoLog({
  2014. type: 'leavingDiscordServer',
  2015. text: guild
  2016. });
  2017. const {
  2018. result,
  2019. statusText,
  2020. status,
  2021. data
  2022. } = await tools_httpRequest({
  2023. url: `https://discord.com/api/v9/users/@me/guilds/${guild}`,
  2024. method: 'DELETE',
  2025. headers: {
  2026. authorization: this.#auth.auth
  2027. }
  2028. });
  2029. if (result === 'Success' && data?.status === 204) {
  2030. logStatus.success();
  2031. return true;
  2032. }
  2033. logStatus.error(`${result}:${statusText}(${status})`);
  2034. return false;
  2035. } catch (error) {
  2036. throwError(error, 'Discord.leaveServer');
  2037. return false;
  2038. }
  2039. }
  2040. async #getGuild(inviteId) {
  2041. try {
  2042. const logStatus = scripts_echoLog({
  2043. type: 'gettingDiscordGuild',
  2044. text: inviteId
  2045. });
  2046. const guild = this.#cache[inviteId];
  2047. if (guild) {
  2048. logStatus.success();
  2049. return guild;
  2050. }
  2051. const {
  2052. result,
  2053. statusText,
  2054. status,
  2055. data
  2056. } = await tools_httpRequest({
  2057. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2058. responseType: 'json',
  2059. method: 'GET'
  2060. });
  2061. if (result === 'Success' && data?.status === 200) {
  2062. const guild = data.response?.guild?.id;
  2063. if (guild) {
  2064. logStatus.success();
  2065. this.#setCache(inviteId, guild);
  2066. return guild;
  2067. }
  2068. logStatus.error(`${result}:${statusText}(${status})`);
  2069. return false;
  2070. }
  2071. logStatus.error(`${result}:${statusText}(${status})`);
  2072. return false;
  2073. } catch (error) {
  2074. throwError(error, 'Discord.getGuild');
  2075. return false;
  2076. }
  2077. }
  2078. async toggle({
  2079. doTask = true,
  2080. serverLinks = []
  2081. }) {
  2082. try {
  2083. if (!this.#initialized) {
  2084. scripts_echoLog({
  2085. text: i18n('needInit')
  2086. });
  2087. return false;
  2088. }
  2089. const prom = [];
  2090. if (doTask && !globalOptions.doTask.discord.servers || !doTask && !globalOptions.undoTask.discord.servers) {
  2091. scripts_echoLog({
  2092. type: 'globalOptionsSkip',
  2093. text: 'discord.servers'
  2094. });
  2095. } else {
  2096. const realServers = this.getRealParams('servers', serverLinks, doTask, link => link.match(/invite\/(.+)/)?.[1]);
  2097. if (realServers.length > 0) {
  2098. for (const server of realServers) {
  2099. if (doTask) {
  2100. prom.push(this.#joinServer(server));
  2101. } else {
  2102. prom.push(this.#leaveServer(server));
  2103. }
  2104. await delay(1e3);
  2105. }
  2106. }
  2107. }
  2108. return await Promise.all(prom).then(() => true);
  2109. } catch (error) {
  2110. throwError(error, 'Discord.toggleServers');
  2111. return false;
  2112. }
  2113. }
  2114. #setCache(inviteId, guild) {
  2115. try {
  2116. this.#cache[inviteId] = guild;
  2117. GM_setValue('discordCache', this.#cache);
  2118. } catch (error) {
  2119. throwError(error, 'Discord.setCache');
  2120. }
  2121. }
  2122. }
  2123. const social_Discord = Discord;
  2124. class Instagram extends social_Social {
  2125. tasks;
  2126. whiteList;
  2127. #cache = GM_getValue('instagramCache') || {};
  2128. #auth = {};
  2129. #initialized = false;
  2130. constructor() {
  2131. super();
  2132. const defaultTasksTemplate = {
  2133. users: []
  2134. };
  2135. this.tasks = defaultTasksTemplate;
  2136. this.whiteList = {
  2137. ...defaultTasksTemplate,
  2138. ...GM_getValue('whiteList')?.instagram || {}
  2139. };
  2140. }
  2141. async init() {
  2142. try {
  2143. if (this.#initialized) {
  2144. return true;
  2145. }
  2146. const isVerified = await this.#getUserInfo();
  2147. if (isVerified) {
  2148. scripts_echoLog({}).success(i18n('initSuccess', 'Instagram'));
  2149. this.#initialized = true;
  2150. return true;
  2151. }
  2152. scripts_echoLog({}).error(i18n('initFailed', 'Instagram'));
  2153. return false;
  2154. } catch (error) {
  2155. throwError(error, 'Instagram.init');
  2156. return false;
  2157. }
  2158. }
  2159. async #getUserInfo(name = 'instagram') {
  2160. try {
  2161. const logStatus = scripts_echoLog({
  2162. type: name === 'instagram' ? 'verifyingInsAuth' : 'gettingInsUserId',
  2163. text: name
  2164. });
  2165. const userId = this.#cache[name];
  2166. if (userId && name !== 'instagram') {
  2167. logStatus.success();
  2168. return userId;
  2169. }
  2170. const {
  2171. result,
  2172. statusText,
  2173. status,
  2174. data
  2175. } = await tools_httpRequest({
  2176. url: `https://www.instagram.com/${name}/`,
  2177. method: 'GET'
  2178. });
  2179. if (result === 'Success') {
  2180. if (data?.finalUrl.includes('accounts/login')) {
  2181. logStatus.error(`Error:${i18n('loginIns')}`, true);
  2182. return false;
  2183. } else if (data?.finalUrl.includes('www.instagram.com/challenge')) {
  2184. logStatus.error(`Error:${i18n('insBanned')}`);
  2185. return false;
  2186. }
  2187. if (data?.status === 200) {
  2188. const csrftoken = data.responseText.match(/"csrf_token":"(.+?)"/)?.[1];
  2189. const hash = data.responseText.match(/"rollout_hash":"(.+?)"/)?.[1];
  2190. if (name === 'instagram') {
  2191. if (csrftoken && hash) {
  2192. this.#auth = {
  2193. csrftoken: csrftoken,
  2194. hash: hash
  2195. };
  2196. return true;
  2197. }
  2198. return false;
  2199. }
  2200. const id = data.responseText.match(/"profilePage_([\d]+?)"/)?.[1];
  2201. if (id) {
  2202. this.#setCache(name, id);
  2203. logStatus.success();
  2204. return id;
  2205. }
  2206. logStatus.error('Error: Get ins data error!');
  2207. return false;
  2208. }
  2209. logStatus.error(`${result}:${statusText}(${status})`);
  2210. return false;
  2211. }
  2212. return false;
  2213. } catch (error) {
  2214. throwError(error, 'Instagram.getUserInfo');
  2215. return false;
  2216. }
  2217. }
  2218. async #followUser(name) {
  2219. try {
  2220. const id = await this.#getUserInfo(name);
  2221. if (!id) {
  2222. return false;
  2223. }
  2224. const logStatus = scripts_echoLog({
  2225. type: 'followingIns',
  2226. text: name
  2227. });
  2228. const {
  2229. result,
  2230. statusText,
  2231. status,
  2232. data
  2233. } = await tools_httpRequest({
  2234. url: `https://www.instagram.com/web/friendships/${id}/follow/`,
  2235. method: 'POST',
  2236. dataType: 'json',
  2237. headers: {
  2238. 'x-csrftoken': this.#auth.csrftoken,
  2239. origin: 'https://www.instagram.com',
  2240. referer: `https://www.instagram.com/${name}/`,
  2241. 'content-type': 'application/x-www-form-urlencoded',
  2242. 'sec-fetch-site': 'same-origin',
  2243. 'x-instagram-ajax': this.#auth.hash
  2244. }
  2245. });
  2246. if (result === 'Success') {
  2247. if (data?.status === 200 && data.response?.result === 'following') {
  2248. logStatus.success();
  2249. this.tasks.users = unique([ ...this.tasks.users, name ]);
  2250. return true;
  2251. }
  2252. logStatus.error(`Error:${data?.response?.feedback_message || `${data?.statusText}(${data?.status})`}`);
  2253. return false;
  2254. }
  2255. logStatus.error(`${result}:${statusText}(${status})`);
  2256. return false;
  2257. } catch (error) {
  2258. throwError(error, 'Instagram.followUser');
  2259. return false;
  2260. }
  2261. }
  2262. async #unfollowUser(name) {
  2263. try {
  2264. if (this.whiteList.users.includes(name)) {
  2265. scripts_echoLog({
  2266. type: 'whiteList',
  2267. text: 'Instagram.unfollowUser',
  2268. id: name
  2269. });
  2270. return true;
  2271. }
  2272. const id = await this.#getUserInfo(name);
  2273. if (!id) {
  2274. return false;
  2275. }
  2276. const logStatus = scripts_echoLog({
  2277. type: 'unfollowingIns',
  2278. text: name
  2279. });
  2280. const {
  2281. result,
  2282. statusText,
  2283. status,
  2284. data
  2285. } = await tools_httpRequest({
  2286. url: `https://www.instagram.com/web/friendships/${id}/unfollow/`,
  2287. method: 'POST',
  2288. dataType: 'json',
  2289. headers: {
  2290. 'x-csrftoken': this.#auth.csrftoken,
  2291. origin: 'https://www.instagram.com',
  2292. referer: `https://www.instagram.com/${name}/`,
  2293. 'content-type': 'application/x-www-form-urlencoded',
  2294. 'sec-fetch-site': 'same-origin',
  2295. 'x-instagram-ajax': this.#auth.hash
  2296. }
  2297. });
  2298. if (result === 'Success') {
  2299. if (data?.status === 200 && data.response?.status === 'ok') {
  2300. logStatus.success();
  2301. return true;
  2302. }
  2303. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2304. return false;
  2305. }
  2306. logStatus.error(`${result}:${statusText}(${status})`);
  2307. return false;
  2308. } catch (error) {
  2309. throwError(error, 'Instagram.unfollowUser');
  2310. return false;
  2311. }
  2312. }
  2313. async toggle({
  2314. doTask = true,
  2315. userLinks = []
  2316. }) {
  2317. try {
  2318. if (!this.#initialized) {
  2319. scripts_echoLog({
  2320. text: i18n('needInit')
  2321. });
  2322. return false;
  2323. }
  2324. const prom = [];
  2325. if (doTask && !globalOptions.doTask.instagram.users || !doTask && !globalOptions.undoTask.instagram.users) {
  2326. scripts_echoLog({
  2327. type: 'globalOptionsSkip',
  2328. text: 'instagram.users'
  2329. });
  2330. } else {
  2331. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1]);
  2332. if (realUsers.length > 0) {
  2333. for (const username of realUsers) {
  2334. if (doTask) {
  2335. prom.push(this.#followUser(username));
  2336. } else {
  2337. prom.push(this.#unfollowUser(username));
  2338. }
  2339. await delay(1e3);
  2340. }
  2341. }
  2342. }
  2343. return await Promise.all(prom).then(() => true);
  2344. } catch (error) {
  2345. throwError(error, 'Instagram.toggleUsers');
  2346. return false;
  2347. }
  2348. }
  2349. #setCache(name, id) {
  2350. try {
  2351. this.#cache[name] = id;
  2352. GM_setValue('instagramCache', this.#cache);
  2353. } catch (error) {
  2354. throwError(error, 'Instagram.setCache');
  2355. }
  2356. }
  2357. }
  2358. const social_Instagram = Instagram;
  2359. class Reddit extends social_Social {
  2360. tasks;
  2361. whiteList;
  2362. #auth;
  2363. #initialized = false;
  2364. constructor() {
  2365. super();
  2366. const defaultTasksTemplate = {
  2367. reddits: []
  2368. };
  2369. this.tasks = defaultTasksTemplate;
  2370. this.whiteList = {
  2371. ...defaultTasksTemplate,
  2372. ...GM_getValue('whiteList')?.reddit || {}
  2373. };
  2374. }
  2375. async init() {
  2376. try {
  2377. if (this.#initialized) {
  2378. return true;
  2379. }
  2380. const isVerified = await this.#updateAuth();
  2381. if (isVerified) {
  2382. scripts_echoLog({}).success(i18n('initSuccess', 'Reddit'));
  2383. this.#initialized = true;
  2384. return true;
  2385. }
  2386. scripts_echoLog({}).error(i18n('initFailed', 'Reddit'));
  2387. return false;
  2388. } catch (error) {
  2389. throwError(error, 'Reddit.init');
  2390. return false;
  2391. }
  2392. }
  2393. async #useBeta() {
  2394. try {
  2395. const logStatus = scripts_echoLog({
  2396. text: i18n('changingRedditVersion')
  2397. });
  2398. return await new Promise(resolve => {
  2399. const newTab = GM_openInTab('https://www.reddit.com/', {
  2400. active: true,
  2401. insert: true,
  2402. setParent: true
  2403. });
  2404. newTab.name = 'ATv4_redditAuth';
  2405. newTab.onclose = async () => {
  2406. logStatus.success();
  2407. resolve(await this.#updateAuth(true));
  2408. };
  2409. });
  2410. } catch (error) {
  2411. throwError(error, 'Reddit.useBeta');
  2412. return false;
  2413. }
  2414. }
  2415. async #updateAuth(beta = false) {
  2416. try {
  2417. const logStatus = scripts_echoLog({
  2418. text: i18n('updatingAuth', 'Reddit')
  2419. });
  2420. const {
  2421. result,
  2422. statusText,
  2423. status,
  2424. data
  2425. } = await tools_httpRequest({
  2426. url: 'https://www.reddit.com/',
  2427. method: 'GET',
  2428. nochche: true,
  2429. headers: {
  2430. 'Cache-Control': 'no-cache'
  2431. }
  2432. });
  2433. if (result === 'Success') {
  2434. if (data?.responseText.includes('www.reddit.com/login/')) {
  2435. logStatus.error(`Error:${i18n('loginReddit')}`, true);
  2436. return false;
  2437. }
  2438. if (data?.status === 200) {
  2439. if (data.responseText.includes('redesign-beta-optin-btn') && !beta) {
  2440. return await this.#useBeta();
  2441. }
  2442. const accessToken = data.responseText.match(/"accessToken":"(.*?)","expires":"(.*?)"/)?.[1];
  2443. if (accessToken) {
  2444. this.#auth = {
  2445. token: accessToken
  2446. };
  2447. logStatus.success();
  2448. return true;
  2449. }
  2450. logStatus.error('Error: Parameter "accessToken" not found!');
  2451. return false;
  2452. }
  2453. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2454. return false;
  2455. }
  2456. logStatus.error(`${result}:${statusText}(${status})`);
  2457. return false;
  2458. } catch (error) {
  2459. throwError(error, 'Reddit.updateAuth');
  2460. return false;
  2461. }
  2462. }
  2463. async #toggleTask({
  2464. name,
  2465. doTask = true
  2466. }) {
  2467. try {
  2468. if (!doTask && this.whiteList.reddits.includes(name)) {
  2469. scripts_echoLog({
  2470. type: 'whiteList',
  2471. text: 'Reddit.undoTask',
  2472. id: name
  2473. });
  2474. return true;
  2475. }
  2476. let type = doTask ? 'joiningReddit' : 'leavingReddit';
  2477. if (/^u_/.test(name)) {
  2478. type = doTask ? 'followingRedditUser' : 'unfollowingRedditUser';
  2479. }
  2480. const logStatus = scripts_echoLog({
  2481. type: type,
  2482. text: name
  2483. });
  2484. const {
  2485. result,
  2486. statusText,
  2487. status,
  2488. data
  2489. } = await tools_httpRequest({
  2490. url: 'https://oauth.reddit.com/api/subscribe?redditWebClient=desktop2x&app=desktop2x-client-production&raw_json=1&gilding_detail=1',
  2491. method: 'POST',
  2492. headers: {
  2493. authorization: `Bearer ${this.#auth.token}`,
  2494. 'content-type': 'application/x-www-form-urlencoded'
  2495. },
  2496. data: $.param({
  2497. action: doTask ? 'sub' : 'unsub',
  2498. sr_name: name,
  2499. api_type: 'json'
  2500. })
  2501. });
  2502. if (result === 'Success') {
  2503. if (data?.status === 200) {
  2504. logStatus.success();
  2505. if (doTask) {
  2506. this.tasks.reddits = unique([ ...this.tasks.reddits, name ]);
  2507. }
  2508. return true;
  2509. }
  2510. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2511. return false;
  2512. }
  2513. logStatus.error(`${result}:${statusText}(${status})`);
  2514. return false;
  2515. } catch (error) {
  2516. throwError(error, 'Reddit.toggleTask');
  2517. return false;
  2518. }
  2519. }
  2520. async toggle({
  2521. doTask = true,
  2522. redditLinks = []
  2523. }) {
  2524. try {
  2525. if (!this.#initialized) {
  2526. scripts_echoLog({
  2527. text: i18n('needInit')
  2528. });
  2529. return false;
  2530. }
  2531. const prom = [];
  2532. if (doTask && !globalOptions.doTask.reddit.reddits || !doTask && !globalOptions.undoTask.reddit.reddits) {
  2533. scripts_echoLog({
  2534. type: 'globalOptionsSkip',
  2535. text: 'reddit.reddits'
  2536. });
  2537. } else {
  2538. const realReddits = this.getRealParams('reddits', redditLinks, doTask, link => {
  2539. const name = link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1];
  2540. const userName = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1];
  2541. if (userName) {
  2542. return name || userName;
  2543. }
  2544. return name;
  2545. });
  2546. if (realReddits.length > 0) {
  2547. for (const name of realReddits) {
  2548. prom.push(this.#toggleTask({
  2549. name: name,
  2550. doTask: doTask
  2551. }));
  2552. await delay(1e3);
  2553. }
  2554. }
  2555. }
  2556. return await Promise.all(prom).then(() => true);
  2557. } catch (error) {
  2558. throwError(error, 'Reddit.toggle');
  2559. return false;
  2560. }
  2561. }
  2562. }
  2563. const social_Reddit = Reddit;
  2564. class Twitch extends social_Social {
  2565. tasks;
  2566. whiteList;
  2567. #auth = GM_getValue('twitchAuth') || {};
  2568. #cache = GM_getValue('twitchCache') || {};
  2569. #initialized = false;
  2570. #integrityToken;
  2571. constructor() {
  2572. super();
  2573. const defaultTasksTemplate = {
  2574. channels: []
  2575. };
  2576. this.tasks = defaultTasksTemplate;
  2577. this.whiteList = {
  2578. ...defaultTasksTemplate,
  2579. ...GM_getValue('whiteList')?.twitch || {}
  2580. };
  2581. }
  2582. async init() {
  2583. try {
  2584. if (this.#initialized) {
  2585. return true;
  2586. }
  2587. if (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId) {
  2588. if (await this.#updateAuth()) {
  2589. this.#initialized = true;
  2590. return true;
  2591. }
  2592. return false;
  2593. }
  2594. const isVerified = await this.#verifyAuth(true);
  2595. if (isVerified) {
  2596. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  2597. this.#initialized = true;
  2598. return true;
  2599. }
  2600. GM_setValue('twitchAuth', null);
  2601. if (await this.#updateAuth()) {
  2602. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  2603. this.#initialized = true;
  2604. return true;
  2605. }
  2606. scripts_echoLog({}).error(i18n('initFailed', 'Twitch'));
  2607. return false;
  2608. } catch (error) {
  2609. throwError(error, 'Twitch.init');
  2610. return false;
  2611. }
  2612. }
  2613. async #verifyAuth(isFirst) {
  2614. try {
  2615. const logStatus = scripts_echoLog({
  2616. text: i18n('verifyingAuth', 'Twitch')
  2617. });
  2618. const {
  2619. result,
  2620. statusText,
  2621. status,
  2622. data
  2623. } = await tools_httpRequest({
  2624. url: 'https://gql.twitch.tv/gql',
  2625. method: 'POST',
  2626. dataType: 'json',
  2627. headers: {
  2628. Authorization: `OAuth ${this.#auth.authToken}`,
  2629. 'Client-Id': this.#auth.clientId
  2630. },
  2631. data: '[{"operationName":"FrontPageNew_User","variables":{"limit":1},"extensions":{"persistedQuery":{"version":1,' + '"sha256Hash":"64bd07a2cbaca80699d62636d966cf6395a5d14a1f0a14282067dcb28b13eb11"}}}]'
  2632. });
  2633. if (result === 'Success') {
  2634. if (data?.status === 200 && data.response?.[0]?.data?.currentUser) {
  2635. await this.#integrity(isFirst);
  2636. logStatus.success();
  2637. return true;
  2638. }
  2639. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2640. return false;
  2641. }
  2642. logStatus.error(`${result}:${statusText}(${status})`);
  2643. return false;
  2644. } catch (error) {
  2645. throwError(error, 'Twitch.verifyAuth');
  2646. return false;
  2647. }
  2648. }
  2649. async #integrity(isFirst = true, ct = '') {
  2650. try {
  2651. const logStatus = scripts_echoLog({
  2652. text: i18n('checkingTwitchIntegrity')
  2653. });
  2654. if (isFirst && (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId)) {
  2655. return await this.#updateAuth(false);
  2656. }
  2657. const {
  2658. result,
  2659. statusText,
  2660. status,
  2661. data
  2662. } = await tools_httpRequest({
  2663. url: 'https://gql.twitch.tv/integrity',
  2664. method: 'POST',
  2665. dataType: 'json',
  2666. anonymous: true,
  2667. headers: {
  2668. Origin: 'https://www.twitch.tv',
  2669. Referer: 'https://www.twitch.tv/',
  2670. Authorization: `OAuth ${this.#auth.authToken}`,
  2671. 'Client-Id': this.#auth.clientId,
  2672. 'Client-Version': this.#auth.clientVersion,
  2673. 'X-Device-Id': this.#auth.deviceId,
  2674. 'Client-Session-Id': this.#auth.clientSessionId,
  2675. 'x-kpsdk-ct': ct
  2676. }
  2677. });
  2678. if (result === 'Success') {
  2679. if (!ct && data?.responseHeaders?.['x-kpsdk-ct']) {
  2680. return await this.#integrity(isFirst, data.responseHeaders['x-kpsdk-ct']);
  2681. }
  2682. if (data?.status === 200 && data.response?.token) {
  2683. this.#integrityToken = data.response.token;
  2684. logStatus.success();
  2685. return true;
  2686. }
  2687. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2688. return false;
  2689. }
  2690. logStatus.error(`${result}:${statusText}(${status})`);
  2691. return false;
  2692. } catch (error) {
  2693. throwError(error, 'Twitch.integrity');
  2694. return false;
  2695. }
  2696. }
  2697. async #updateAuth(isFirst = true) {
  2698. try {
  2699. const logStatus = scripts_echoLog({
  2700. text: i18n('updatingAuth', 'Twitch')
  2701. });
  2702. return await new Promise(resolve => {
  2703. const newTab = GM_openInTab('https://www.twitch.tv/', {
  2704. active: true,
  2705. insert: true,
  2706. setParent: true
  2707. });
  2708. newTab.name = 'ATv4_twitchAuth';
  2709. newTab.onclose = async () => {
  2710. const auth = GM_getValue('twitchAuth');
  2711. if (auth) {
  2712. this.#auth = auth;
  2713. logStatus.success();
  2714. resolve(await this.#verifyAuth(isFirst));
  2715. } else {
  2716. logStatus.error('Error: Update twitch auth failed!');
  2717. resolve(false);
  2718. }
  2719. };
  2720. });
  2721. } catch (error) {
  2722. throwError(error, 'Twitch.updateAuth');
  2723. return false;
  2724. }
  2725. }
  2726. async #toggleChannel({
  2727. name,
  2728. doTask = true
  2729. }) {
  2730. try {
  2731. if (!doTask && this.whiteList.channels.includes(name)) {
  2732. scripts_echoLog({
  2733. type: 'whiteList',
  2734. text: 'Twitch.unfollowChannel',
  2735. id: name
  2736. });
  2737. return true;
  2738. }
  2739. const channelId = await this.#getChannelId(name);
  2740. if (!channelId) {
  2741. return false;
  2742. }
  2743. const logStatus = scripts_echoLog({
  2744. type: `${doTask ? '' : 'un'}followingTwitchChannel`,
  2745. text: name
  2746. });
  2747. const followData = `[{"operationName":"FollowButton_FollowUser","variables":{"input":{"disableNotifications":false,"targetID":"${channelId}` + '"}},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"800e7346bdf7e5278a3c1d3f21b2b56e2639928f86815677a7126b093b2fdd08"}}}]';
  2748. const unfollowData = `[{"operationName":"FollowButton_UnfollowUser","variables":{"input":{"targetID":"${channelId}"}},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"f7dae976ebf41c755ae2d758546bfd176b4eeb856656098bb40e0a672ca0d880"}}}]';
  2749. const {
  2750. result,
  2751. statusText,
  2752. status,
  2753. data
  2754. } = await tools_httpRequest({
  2755. url: 'https://gql.twitch.tv/gql',
  2756. method: 'POST',
  2757. dataType: 'json',
  2758. anonymous: true,
  2759. headers: {
  2760. Origin: 'https://www.twitch.tv',
  2761. Referer: 'https://www.twitch.tv/',
  2762. Authorization: `OAuth ${this.#auth.authToken}`,
  2763. 'Client-Id': this.#auth.clientId,
  2764. 'Client-Version': this.#auth.clientVersion,
  2765. 'X-Device-Id': this.#auth.deviceId,
  2766. 'Client-Session-Id': this.#auth.clientSessionId,
  2767. 'Client-Integrity': this.#integrityToken
  2768. },
  2769. data: doTask ? followData : unfollowData
  2770. });
  2771. if (result === 'Success') {
  2772. if (data?.status === 200 && data.response?.[0] && !data.response[0].errors) {
  2773. logStatus.success();
  2774. if (doTask) {
  2775. this.tasks.channels = unique([ ...this.tasks.channels, name ]);
  2776. }
  2777. return true;
  2778. }
  2779. logStatus.error(`Error:${data?.response?.[0].errors?.[0]?.message || `${data?.statusText}(${data?.status})`}`);
  2780. return false;
  2781. }
  2782. logStatus.error(`${result}:${statusText}(${status})`);
  2783. return false;
  2784. } catch (error) {
  2785. throwError(error, 'Twitch.toggleChannel');
  2786. return false;
  2787. }
  2788. }
  2789. async #getChannelId(name) {
  2790. try {
  2791. const logStatus = scripts_echoLog({
  2792. type: 'gettingTwitchChannelId',
  2793. text: name
  2794. });
  2795. const channelId = this.#cache[name];
  2796. if (channelId) {
  2797. logStatus.success();
  2798. return channelId;
  2799. }
  2800. const {
  2801. result,
  2802. statusText,
  2803. status,
  2804. data
  2805. } = await tools_httpRequest({
  2806. url: 'https://gql.twitch.tv/gql',
  2807. method: 'POST',
  2808. headers: {
  2809. Authorization: `OAuth ${this.#auth.authToken}`,
  2810. 'Client-Id': this.#auth.clientId
  2811. },
  2812. responseType: 'json',
  2813. data: `[{"operationName":"ActiveWatchParty","variables":{"channelLogin":"${name}"},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"4a8156c97b19e3a36e081cf6d6ddb5dbf9f9b02ae60e4d2ff26ed70aebc80a30"}}}]'
  2814. });
  2815. if (result === 'Success') {
  2816. if (data?.status === 200) {
  2817. const channelId = data.response?.[0]?.data?.user?.id;
  2818. if (channelId) {
  2819. this.#setCache(name, String(channelId));
  2820. logStatus.success();
  2821. return channelId;
  2822. }
  2823. logStatus.error(`Error:${data.statusText}(${data.status})`);
  2824. return false;
  2825. }
  2826. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2827. return false;
  2828. }
  2829. logStatus.error(`${result}:${statusText}(${status})`);
  2830. return false;
  2831. } catch (error) {
  2832. throwError(error, 'Twitch.getChannelId');
  2833. return false;
  2834. }
  2835. }
  2836. async toggle({
  2837. doTask = true,
  2838. channelLinks = []
  2839. }) {
  2840. try {
  2841. if (!this.#initialized) {
  2842. scripts_echoLog({
  2843. text: i18n('needInit')
  2844. });
  2845. return false;
  2846. }
  2847. const prom = [];
  2848. if (doTask && !globalOptions.doTask.twitch.channels || !doTask && !globalOptions.undoTask.twitch.channels) {
  2849. scripts_echoLog({
  2850. type: 'globalOptionsSkip',
  2851. text: 'twitch.channels'
  2852. });
  2853. } else {
  2854. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2]);
  2855. if (realChannels.length > 0) {
  2856. for (const channel of realChannels) {
  2857. prom.push(this.#toggleChannel({
  2858. name: channel,
  2859. doTask: doTask
  2860. }));
  2861. await delay(1e3);
  2862. }
  2863. }
  2864. }
  2865. return Promise.all(prom).then(() => true);
  2866. } catch (error) {
  2867. throwError(error, 'Twitch.toggle');
  2868. return false;
  2869. }
  2870. }
  2871. #setCache(name, id) {
  2872. try {
  2873. this.#cache[name] = id;
  2874. GM_setValue('twitchCache', this.#cache);
  2875. } catch (error) {
  2876. throwError(error, 'Twitch.setCache');
  2877. }
  2878. }
  2879. }
  2880. const social_Twitch = Twitch;
  2881. class Twitter extends social_Social {
  2882. tasks;
  2883. whiteList;
  2884. #verifyId = globalOptions.other.twitterVerifyId;
  2885. #auth = GM_getValue('twitterAuth') || {};
  2886. #cache = GM_getValue('twitterCache') || {};
  2887. #initialized = false;
  2888. constructor() {
  2889. super();
  2890. const defaultTasksTemplate = {
  2891. users: [],
  2892. retweets: [],
  2893. likes: []
  2894. };
  2895. this.tasks = defaultTasksTemplate;
  2896. this.whiteList = {
  2897. ...defaultTasksTemplate,
  2898. ...GM_getValue('whiteList')?.twitter || {}
  2899. };
  2900. }
  2901. async init() {
  2902. try {
  2903. if (this.#initialized) {
  2904. return true;
  2905. }
  2906. if (!this.#auth.ct0) {
  2907. if (await this.#updateAuth()) {
  2908. this.#initialized = true;
  2909. return true;
  2910. }
  2911. return false;
  2912. }
  2913. const isVerified = await this.#verifyAuth();
  2914. if (isVerified) {
  2915. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  2916. this.#initialized = true;
  2917. return true;
  2918. }
  2919. GM_setValue('twitterAuth', null);
  2920. if (await this.#updateAuth()) {
  2921. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  2922. this.#initialized = true;
  2923. return true;
  2924. }
  2925. scripts_echoLog({}).error(i18n('initFailed', 'Twitter'));
  2926. return false;
  2927. } catch (error) {
  2928. throwError(error, 'Twitter.init');
  2929. return false;
  2930. }
  2931. }
  2932. async #verifyAuth() {
  2933. try {
  2934. return await this.#toggleUser({
  2935. name: 'verify',
  2936. doTask: true,
  2937. verify: true
  2938. });
  2939. } catch (error) {
  2940. throwError(error, 'Twitter.verifyAuth');
  2941. return false;
  2942. }
  2943. }
  2944. async #updateAuth() {
  2945. try {
  2946. const logStatus = scripts_echoLog({
  2947. text: i18n('updatingAuth', 'Twitter')
  2948. });
  2949. return await new Promise(resolve => {
  2950. GM_cookie.list({
  2951. url: 'https://x.com/settings/account'
  2952. }, async (cookies, error) => {
  2953. if (!error) {
  2954. const [ ct0, isLogin ] = cookies.map(cookie => [ 'ct0', 'twid' ].includes(cookie.name) ? cookie.value : null).filter(cookie => cookie);
  2955. if (isLogin && ct0) {
  2956. GM_setValue('twitterAuth', {
  2957. ct0: ct0
  2958. });
  2959. this.#auth = {
  2960. ct0: ct0
  2961. };
  2962. logStatus.success();
  2963. resolve(await this.#verifyAuth());
  2964. } else {
  2965. logStatus.error(i18n('needLogin'));
  2966. resolve(false);
  2967. }
  2968. } else {
  2969. logStatus.error('Error: Update twitter auth failed!');
  2970. resolve(false);
  2971. }
  2972. });
  2973. });
  2974. } catch (error) {
  2975. throwError(error, 'Twitter.updateToken');
  2976. return false;
  2977. }
  2978. }
  2979. async #toggleUser({
  2980. name,
  2981. doTask = true,
  2982. verify = false
  2983. }) {
  2984. try {
  2985. if (!doTask && !verify && this.whiteList.users.includes(name)) {
  2986. scripts_echoLog({
  2987. type: 'whiteList',
  2988. text: 'Twitter.unfollowUser',
  2989. id: name
  2990. });
  2991. return true;
  2992. }
  2993. const userId = verify ? this.#verifyId : await this.userName2id(name);
  2994. if (!userId) {
  2995. return false;
  2996. }
  2997. const logStatus = verify ? scripts_echoLog({
  2998. text: i18n('verifyingAuth', 'Twitter')
  2999. }) : scripts_echoLog({
  3000. type: `${doTask ? '' : 'un'}followingTwitterUser`,
  3001. text: name
  3002. });
  3003. const {
  3004. result,
  3005. statusText,
  3006. status,
  3007. data
  3008. } = await tools_httpRequest({
  3009. url: `https://x.com/i/api/1.1/friendships/${doTask ? 'create' : 'destroy'}.json`,
  3010. method: 'POST',
  3011. headers: {
  3012. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3013. 'Content-Type': 'application/x-www-form-urlencoded',
  3014. 'x-csrf-token': this.#auth.ct0
  3015. },
  3016. responseType: 'json',
  3017. data: $.param({
  3018. include_profile_interstitial_type: 1,
  3019. include_blocking: 1,
  3020. include_blocked_by: 1,
  3021. include_followed_by: 1,
  3022. include_want_retweets: 1,
  3023. include_mute_edge: 1,
  3024. include_can_dm: 1,
  3025. include_can_media_tag: 1,
  3026. skip_status: 1,
  3027. id: userId
  3028. })
  3029. });
  3030. if (result === 'Success') {
  3031. if (data?.status === 200) {
  3032. logStatus.success();
  3033. if (doTask && !verify) {
  3034. this.tasks.users = unique([ ...this.tasks.users, name ]);
  3035. }
  3036. return true;
  3037. }
  3038. if (verify && data?.status === 403 && data.response?.errors?.[0]?.code === 158) {
  3039. logStatus.success();
  3040. return true;
  3041. }
  3042. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3043. return false;
  3044. }
  3045. logStatus.error(`${result}:${statusText}(${status})`);
  3046. return false;
  3047. } catch (error) {
  3048. throwError(error, 'Twitter.toggleUser');
  3049. return false;
  3050. }
  3051. }
  3052. async userName2id(name) {
  3053. try {
  3054. const logStatus = scripts_echoLog({
  3055. type: 'gettingTwitterUserId',
  3056. text: name
  3057. });
  3058. const userId = this.#cache[name];
  3059. if (userId) {
  3060. logStatus.success();
  3061. return userId;
  3062. }
  3063. const {
  3064. result,
  3065. statusText,
  3066. status,
  3067. data
  3068. } = await tools_httpRequest({
  3069. 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`,
  3070. method: 'GET',
  3071. headers: {
  3072. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3073. 'content-type': 'application/json',
  3074. referer: `https://x.com/${name}`,
  3075. 'x-csrf-token': this.#auth.ct0
  3076. },
  3077. responseType: 'json'
  3078. });
  3079. if (result === 'Success') {
  3080. if (data?.status === 200) {
  3081. let response = data.response || (typeof data.responseText === 'object' ? data.responseText : null);
  3082. if (!response) {
  3083. try {
  3084. response = JSON.parse(data.responseText);
  3085. } catch (error) {
  3086. response = null;
  3087. }
  3088. }
  3089. const userId = String(response?.data?.user?.result?.rest_id);
  3090. if (userId) {
  3091. this.#setCache(name, userId);
  3092. logStatus.success();
  3093. return userId;
  3094. }
  3095. logStatus.error(`Error:${data.statusText}(${data.status})`);
  3096. return false;
  3097. }
  3098. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3099. return false;
  3100. }
  3101. logStatus.error(`${result}:${statusText}(${status})`);
  3102. return false;
  3103. } catch (error) {
  3104. throwError(error, 'Twitter.getUserId');
  3105. return false;
  3106. }
  3107. }
  3108. async #toggleRetweet({
  3109. retweetId,
  3110. doTask = true
  3111. }) {
  3112. try {
  3113. if (!doTask && this.whiteList.retweets.includes(retweetId)) {
  3114. scripts_echoLog({
  3115. type: 'whiteList',
  3116. text: 'Twitter.unretweet',
  3117. id: retweetId
  3118. });
  3119. return true;
  3120. }
  3121. const logStatus = scripts_echoLog({
  3122. type: `${doTask ? '' : 'un'}retweetting`,
  3123. text: retweetId
  3124. });
  3125. const {
  3126. result,
  3127. statusText,
  3128. status,
  3129. data
  3130. } = await tools_httpRequest({
  3131. url: `https://x.com/i/api/graphql/${doTask ? 'ojPdsZsimiJrUGLR1sjUtA/CreateRetweet' : 'iQtK4dl5hBmXewYZuEOKVw/DeleteRetweet'}`,
  3132. method: 'POST',
  3133. headers: {
  3134. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3135. 'Content-Type': 'application/json',
  3136. 'x-csrf-token': this.#auth.ct0
  3137. },
  3138. data: `{"variables":{"tweet_id":"${retweetId}","dark_request":false},"queryId":"${doTask ? 'ojPdsZsimiJrUGLR1sjUtA' : 'iQtK4dl5hBmXewYZuEOKVw'}"}`,
  3139. responseType: 'json'
  3140. });
  3141. if (result === 'Success') {
  3142. if (data?.status === 200 || data?.status === 403 && data.response?.errors?.[0]?.code === 327) {
  3143. logStatus.success();
  3144. if (doTask) {
  3145. this.tasks.retweets = unique([ ...this.tasks.retweets, retweetId ]);
  3146. }
  3147. return true;
  3148. }
  3149. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3150. return false;
  3151. }
  3152. logStatus.error(`${result}:${statusText}(${status})`);
  3153. return false;
  3154. } catch (error) {
  3155. throwError(error, 'Twitter.toggleRetweet');
  3156. return false;
  3157. }
  3158. }
  3159. async toggle({
  3160. doTask = true,
  3161. userLinks = [],
  3162. retweetLinks = []
  3163. }) {
  3164. try {
  3165. if (!this.#initialized) {
  3166. scripts_echoLog({
  3167. text: i18n('needInit')
  3168. });
  3169. return false;
  3170. }
  3171. const prom = [];
  3172. if (doTask && !globalOptions.doTask.twitter.users || !doTask && !globalOptions.undoTask.twitter.users) {
  3173. scripts_echoLog({
  3174. type: 'globalOptionsSkip',
  3175. text: 'twitter.users'
  3176. });
  3177. } else {
  3178. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/x\.com\/(.+)/)?.[1] || link.match(/https:\/\/twitter\.com\/(.+)/)?.[1]);
  3179. if (realUsers.length > 0) {
  3180. for (const user of realUsers) {
  3181. prom.push(this.#toggleUser({
  3182. name: user,
  3183. doTask: doTask
  3184. }));
  3185. await delay(1e3);
  3186. }
  3187. }
  3188. }
  3189. if (doTask && !globalOptions.doTask.twitter.retweets || !doTask && !globalOptions.undoTask.twitter.retweets) {
  3190. scripts_echoLog({
  3191. type: 'globalOptionsSkip',
  3192. text: 'twitter.retweets'
  3193. });
  3194. } else {
  3195. const realRetweets = this.getRealParams('retweets', retweetLinks, doTask, link => link.match(/https:\/\/x\.com\/.*?\/status\/([\d]+)/)?.[1] || link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1]);
  3196. if (realRetweets.length > 0) {
  3197. for (const retweet of realRetweets) {
  3198. prom.push(this.#toggleRetweet({
  3199. retweetId: retweet,
  3200. doTask: doTask
  3201. }));
  3202. await delay(1e3);
  3203. }
  3204. }
  3205. }
  3206. return Promise.all(prom).then(() => true);
  3207. } catch (error) {
  3208. throwError(error, 'Twitter.toggle');
  3209. return false;
  3210. }
  3211. }
  3212. #setCache(name, id) {
  3213. try {
  3214. this.#cache[name] = id;
  3215. GM_setValue('twitterCache', this.#cache);
  3216. } catch (error) {
  3217. throwError(error, 'Twitter.setCache');
  3218. }
  3219. }
  3220. }
  3221. const social_Twitter = Twitter;
  3222. class Vk extends social_Social {
  3223. tasks;
  3224. whiteList;
  3225. #username = '';
  3226. #cache = GM_getValue('vkCache') || {};
  3227. #initialized = false;
  3228. constructor() {
  3229. super();
  3230. const defaultTasksTemplate = {
  3231. names: []
  3232. };
  3233. this.tasks = defaultTasksTemplate;
  3234. this.whiteList = {
  3235. ...defaultTasksTemplate,
  3236. ...GM_getValue('whiteList')?.vk || {}
  3237. };
  3238. }
  3239. async init() {
  3240. try {
  3241. if (this.#initialized) {
  3242. return true;
  3243. }
  3244. const isVerified = await this.#verifyAuth();
  3245. if (isVerified) {
  3246. scripts_echoLog({}).success(i18n('initSuccess', 'Vk'));
  3247. this.#initialized = true;
  3248. return true;
  3249. }
  3250. scripts_echoLog({}).error(i18n('initFailed', 'Vk'));
  3251. return false;
  3252. } catch (error) {
  3253. throwError(error, 'Vk.init');
  3254. return false;
  3255. }
  3256. }
  3257. async #verifyAuth() {
  3258. try {
  3259. const logStatus = scripts_echoLog({
  3260. text: i18n('verifyAuth', 'Vk')
  3261. });
  3262. const {
  3263. result,
  3264. statusText,
  3265. status,
  3266. data
  3267. } = await tools_httpRequest({
  3268. url: 'https://vk.com/im',
  3269. method: 'GET'
  3270. });
  3271. if (result === 'Success') {
  3272. if (data?.finalUrl.includes('vk.com/login')) {
  3273. logStatus.error(`Error:${i18n('loginVk')}`, true);
  3274. return false;
  3275. }
  3276. if (data?.status === 200) {
  3277. this.#username = data.responseText.match(/TopNavBtn__profileLink" href="\/(.*?)"/)?.[1] || '';
  3278. logStatus.success();
  3279. return true;
  3280. }
  3281. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3282. return false;
  3283. }
  3284. logStatus.error(`${result}:${statusText}(${status})`);
  3285. return false;
  3286. } catch (error) {
  3287. throwError(error, 'Vk.verifyAuth');
  3288. return false;
  3289. }
  3290. }
  3291. async #toggleGroup(name, dataParam, doTask = true) {
  3292. try {
  3293. const logStatus = scripts_echoLog({
  3294. type: doTask ? 'joiningVkGroup' : 'leavingVkGroup',
  3295. text: name
  3296. });
  3297. if (dataParam.groupAct === 'enter' && !doTask || dataParam.groupAct === 'leave' && doTask) {
  3298. logStatus.success();
  3299. return true;
  3300. }
  3301. const reqData = {
  3302. act: doTask ? 'enter' : 'leave',
  3303. al: 1,
  3304. gid: dataParam.groupId,
  3305. hash: dataParam.groupHash
  3306. };
  3307. if (doTask) {
  3308. reqData.context = '_';
  3309. }
  3310. const {
  3311. result,
  3312. statusText,
  3313. status,
  3314. data
  3315. } = await tools_httpRequest({
  3316. url: 'https://vk.com/al_groups.php',
  3317. method: 'POST',
  3318. headers: {
  3319. origin: 'https://vk.com',
  3320. referer: `https://vk.com/${name}`,
  3321. 'content-type': 'application/x-www-form-urlencoded'
  3322. },
  3323. data: $.param(reqData)
  3324. });
  3325. if (result === 'Success') {
  3326. if (data?.status === 200) {
  3327. logStatus.success();
  3328. if (doTask) {
  3329. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3330. }
  3331. return true;
  3332. }
  3333. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3334. return false;
  3335. }
  3336. logStatus.error(`${result}:${statusText}(${status})`);
  3337. return false;
  3338. } catch (error) {
  3339. throwError(error, 'Vk.toggleGroup');
  3340. return false;
  3341. }
  3342. }
  3343. async #togglePublic(name, dataParam, doTask = true) {
  3344. try {
  3345. const logStatus = scripts_echoLog({
  3346. type: doTask ? 'joiningVkPublic' : 'leavingVkPublic',
  3347. text: name
  3348. });
  3349. if (dataParam.publicJoined && doTask || !dataParam.publicJoined && !doTask) {
  3350. logStatus.success();
  3351. return true;
  3352. }
  3353. const {
  3354. result,
  3355. statusText,
  3356. status,
  3357. data
  3358. } = await tools_httpRequest({
  3359. url: 'https://vk.com/al_public.php',
  3360. method: 'POST',
  3361. headers: {
  3362. origin: 'https://vk.com',
  3363. referer: `https://vk.com/${name}`,
  3364. 'content-type': 'application/x-www-form-urlencoded'
  3365. },
  3366. data: $.param({
  3367. act: doTask ? 'a_enter' : 'a_leave',
  3368. al: 1,
  3369. pid: dataParam.publicPid,
  3370. hash: dataParam.publicHash
  3371. })
  3372. });
  3373. if (result === 'Success') {
  3374. if (data?.status === 200) {
  3375. logStatus.success();
  3376. if (doTask) {
  3377. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3378. }
  3379. return true;
  3380. }
  3381. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3382. return false;
  3383. }
  3384. logStatus.error(`${result}:${statusText}(${status})`);
  3385. return false;
  3386. } catch (error) {
  3387. throwError(error, 'Vk.togglePublic');
  3388. return false;
  3389. }
  3390. }
  3391. async #sendWall(name) {
  3392. try {
  3393. const logStatus = scripts_echoLog({
  3394. type: 'sendingVkWall',
  3395. text: name
  3396. });
  3397. const {
  3398. result,
  3399. statusText,
  3400. status,
  3401. data
  3402. } = await tools_httpRequest({
  3403. url: 'https://vk.com/like.php',
  3404. method: 'POST',
  3405. headers: {
  3406. origin: 'https://vk.com',
  3407. referer: `https://vk.com/${name}`,
  3408. 'content-type': 'application/x-www-form-urlencoded'
  3409. },
  3410. data: $.param({
  3411. act: 'publish_box',
  3412. al: 1,
  3413. object: name
  3414. })
  3415. });
  3416. if (result === 'Success') {
  3417. if (data?.status === 200) {
  3418. const hash = data.responseText.match(/shHash:[\s]*'(.*?)'/)?.[1];
  3419. if (hash) {
  3420. const {
  3421. result: resultR,
  3422. statusText: statusTextR,
  3423. status: statusR,
  3424. data: dataR
  3425. } = await tools_httpRequest({
  3426. url: 'https://vk.com/like.php',
  3427. method: 'POST',
  3428. headers: {
  3429. origin: 'https://vk.com',
  3430. referer: `https://vk.com/${name}`,
  3431. 'content-type': 'application/x-www-form-urlencoded'
  3432. },
  3433. data: $.param({
  3434. Message: '',
  3435. act: 'a_do_publish',
  3436. al: 1,
  3437. close_comments: 0,
  3438. friends_only: 0,
  3439. from: 'box',
  3440. hash: hash,
  3441. list: '',
  3442. mark_as_ads: 0,
  3443. mute_notifications: 0,
  3444. object: name,
  3445. ret_data: 1,
  3446. to: 0
  3447. })
  3448. });
  3449. if (resultR === 'Success') {
  3450. if (dataR?.status === 200) {
  3451. const jsonData = JSON.parse(dataR.responseText?.replace('\x3c!--', '') || '{}');
  3452. if (jsonData?.payload?.[1]?.[1]?.share_my === true) {
  3453. logStatus.success();
  3454. const postId = String(jsonData?.payload?.[1]?.[1]?.post_id);
  3455. const ownerId = String(jsonData?.payload?.[1]?.[1]?.owner_id);
  3456. if (postId && ownerId) {
  3457. this.#setCache(name, `${ownerId}_${postId}`);
  3458. }
  3459. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3460. return true;
  3461. }
  3462. }
  3463. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  3464. return false;
  3465. }
  3466. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  3467. return false;
  3468. }
  3469. logStatus.error('Error: Get "hash" failed');
  3470. return false;
  3471. }
  3472. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3473. return false;
  3474. }
  3475. logStatus.error(`${result}:${statusText}(${status})`);
  3476. return false;
  3477. } catch (error) {
  3478. throwError(error, 'Vk.sendWall');
  3479. return false;
  3480. }
  3481. }
  3482. async #deleteWall(name, dataParams) {
  3483. try {
  3484. const logStatus = scripts_echoLog({
  3485. type: 'deletingVkWall',
  3486. text: name
  3487. });
  3488. const {
  3489. result,
  3490. statusText,
  3491. status,
  3492. data
  3493. } = await tools_httpRequest({
  3494. url: 'https://vk.com/al_wall.php?act=delete',
  3495. method: 'POST',
  3496. headers: {
  3497. origin: 'https://vk.com',
  3498. referer: `https://vk.com/${this.#username}?w=wall${this.#cache[name]}%2Fall`,
  3499. 'content-type': 'application/x-www-form-urlencoded'
  3500. },
  3501. data: $.param({
  3502. act: 'delete',
  3503. al: 1,
  3504. confirm: 0,
  3505. from: 'wkview',
  3506. hash: dataParams.wallHash,
  3507. post: this.#cache[name]
  3508. })
  3509. });
  3510. if (result === 'Success') {
  3511. if (data?.status === 200) {
  3512. const jsonData = JSON.parse(data.responseText?.replace('\x3c!--', '') || '{}');
  3513. if (jsonData?.payload?.[1]?.[1]) {
  3514. logStatus.success();
  3515. return true;
  3516. }
  3517. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3518. return false;
  3519. }
  3520. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3521. return false;
  3522. }
  3523. logStatus.error(`${result}:${statusText}(${status})`);
  3524. return false;
  3525. } catch (error) {
  3526. throwError(error, 'Vk.deleteWall');
  3527. return false;
  3528. }
  3529. }
  3530. async #getId(name, doTask) {
  3531. try {
  3532. let url = `https://vk.com/${name}`;
  3533. if (/^wall-/.test(name)) {
  3534. if (doTask) {
  3535. return {
  3536. type: 'sendWall'
  3537. };
  3538. }
  3539. if (!this.#cache[name]) {
  3540. return {
  3541. type: 'unSupport'
  3542. };
  3543. }
  3544. url = `https://vk.com/${this.#username}?w=wall${this.#cache[name]}`;
  3545. }
  3546. const logStatus = scripts_echoLog({
  3547. type: 'gettingVkId',
  3548. text: name
  3549. });
  3550. const {
  3551. result,
  3552. statusText,
  3553. status,
  3554. data
  3555. } = await tools_httpRequest({
  3556. url: url,
  3557. method: 'GET'
  3558. });
  3559. if (result === 'Success') {
  3560. if (data?.status === 200) {
  3561. const [ , groupAct, groupId, , groupHash ] = data.responseText.match(/Groups.(enter|leave)\(.*?,.*?([\d]+?), (&#39;|')(.*?)(&#39;|')/) || [];
  3562. const publicHash = data.responseText.match(/"enterHash":"(.*?)"/)?.[1];
  3563. const publicPid = data.responseText.match(/"public_id":([\d]+?),/)?.[1];
  3564. const publicJoined = !data.responseText.includes('Public.subscribe');
  3565. if (groupAct && groupId && groupHash) {
  3566. logStatus.success();
  3567. return {
  3568. groupAct: groupAct,
  3569. groupId: groupId,
  3570. groupHash: groupHash,
  3571. type: 'group'
  3572. };
  3573. } else if (publicHash && publicPid) {
  3574. logStatus.success();
  3575. return {
  3576. publicHash: publicHash,
  3577. publicPid: publicPid,
  3578. publicJoined: publicJoined,
  3579. type: 'public'
  3580. };
  3581. } else if (data.responseText.includes('wall.deletePost') && !doTask) {
  3582. const wallHash = data.responseText.match(/wall\.deletePost\(this, '.*?', '(.*?)'\)/)?.[1];
  3583. if (wallHash) {
  3584. logStatus.success();
  3585. return {
  3586. type: 'deleteWall',
  3587. wallHash: wallHash
  3588. };
  3589. }
  3590. } else if (name.includes('wall') && doTask) {
  3591. logStatus.success();
  3592. return {
  3593. type: 'sendWall'
  3594. };
  3595. }
  3596. logStatus.error('Error: Parameters not found!');
  3597. return false;
  3598. }
  3599. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3600. return false;
  3601. }
  3602. logStatus.error(`${result}:${statusText}(${status})`);
  3603. return false;
  3604. } catch (error) {
  3605. throwError(error, 'Vk.getId');
  3606. return false;
  3607. }
  3608. }
  3609. async #toggleVk({
  3610. name,
  3611. doTask = true
  3612. }) {
  3613. try {
  3614. if (!doTask && this.whiteList.names.includes(name)) {
  3615. scripts_echoLog({
  3616. type: 'whiteList',
  3617. text: 'Vk.undoTask',
  3618. id: name
  3619. });
  3620. return true;
  3621. }
  3622. const formatName = name.replace(/\/$/, '');
  3623. const data = await this.#getId(formatName, doTask);
  3624. if (!data) {
  3625. return false;
  3626. }
  3627. switch (data.type) {
  3628. case 'group':
  3629. return await this.#toggleGroup(formatName, data, doTask);
  3630.  
  3631. case 'public':
  3632. return await this.#togglePublic(formatName, data, doTask);
  3633.  
  3634. case 'sendWall':
  3635. return doTask ? await this.#sendWall(formatName) : true;
  3636.  
  3637. case 'deleteWall':
  3638. return doTask ? true : await this.#deleteWall(formatName, data);
  3639.  
  3640. default:
  3641. return false;
  3642. }
  3643. } catch (error) {
  3644. throwError(error, 'Vk.toggleVk');
  3645. return false;
  3646. }
  3647. }
  3648. async toggle({
  3649. doTask = true,
  3650. nameLinks = []
  3651. }) {
  3652. try {
  3653. if (!this.#initialized) {
  3654. scripts_echoLog({
  3655. text: i18n('needInit')
  3656. });
  3657. return false;
  3658. }
  3659. const prom = [];
  3660. if (doTask && !globalOptions.doTask.vk.names || !doTask && !globalOptions.undoTask.vk.names) {
  3661. scripts_echoLog({
  3662. type: 'globalOptionsSkip',
  3663. text: 'vk.names'
  3664. });
  3665. } else {
  3666. const realNames = this.getRealParams('names', nameLinks, doTask, link => link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1]);
  3667. if (realNames.length > 0) {
  3668. for (const name of realNames) {
  3669. prom.push(this.#toggleVk({
  3670. name: name,
  3671. doTask: doTask
  3672. }));
  3673. await delay(1e3);
  3674. }
  3675. }
  3676. }
  3677. return Promise.all(prom).then(() => true);
  3678. } catch (error) {
  3679. throwError(error, 'Vk.toggle');
  3680. return false;
  3681. }
  3682. }
  3683. #setCache(name, postId) {
  3684. try {
  3685. this.#cache[name] = postId;
  3686. GM_setValue('vkCache', this.#cache);
  3687. } catch (error) {
  3688. throwError(error, 'Vk.setCache');
  3689. }
  3690. }
  3691. }
  3692. const social_Vk = Vk;
  3693. const getInfo = async function(link, type) {
  3694. try {
  3695. const logStatus = scripts_echoLog({
  3696. text: i18n('gettingYtbToken')
  3697. });
  3698. const {
  3699. result,
  3700. statusText,
  3701. status,
  3702. data
  3703. } = await tools_httpRequest({
  3704. url: link,
  3705. method: 'GET'
  3706. });
  3707. if (result === 'Success') {
  3708. if (data?.status === 200) {
  3709. if (data.responseText.includes('accounts.google.com/ServiceLogin?service=youtube')) {
  3710. logStatus.error(`Error:${i18n('loginYtb')}`, true);
  3711. return {
  3712. needLogin: true
  3713. };
  3714. }
  3715. const apiKey = data.responseText.match(/"INNERTUBE_API_KEY":"(.*?)"/)?.[1];
  3716. const context = (data.responseText.match(/\(\{"INNERTUBE_CONTEXT":([\w\W]*?)\}\)/) || data.responseText.match(/"INNERTUBE_CONTEXT":([\w\W]*?\}),"INNERTUBE/))?.[1] || '{}';
  3717. const {
  3718. client,
  3719. request
  3720. } = JSON.parse(context);
  3721. if (apiKey && client && request) {
  3722. client.hl = 'en';
  3723. if (type === 'channel') {
  3724. const channelId = data.responseText.match(/"channelId":"(.+?)"/)?.[1];
  3725. if (channelId) {
  3726. logStatus.success();
  3727. return {
  3728. params: {
  3729. apiKey: apiKey,
  3730. client: client,
  3731. request: request,
  3732. channelId: channelId
  3733. }
  3734. };
  3735. }
  3736. logStatus.error('Error: Get "channelId" failed!');
  3737. return {};
  3738. } else if (type === 'likeVideo') {
  3739. const videoId = data.responseText.match(/<link rel="shortlinkUrl" href="https:\/\/youtu\.be\/(.*?)">/)?.[1];
  3740. const likeParams = data.responseText.match(/"likeParams":"(.*?)"/)?.[1];
  3741. if (videoId) {
  3742. logStatus.success();
  3743. return {
  3744. params: {
  3745. apiKey: apiKey,
  3746. client: client,
  3747. request: request,
  3748. videoId: videoId,
  3749. likeParams: likeParams
  3750. }
  3751. };
  3752. }
  3753. logStatus.error('Error: Get "videoId" failed!');
  3754. return {};
  3755. }
  3756. logStatus.error('Error: Unknown type');
  3757. return {};
  3758. }
  3759. logStatus.error('Error: Parameter "apiKey" not found!');
  3760. return {};
  3761. }
  3762. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3763. return {};
  3764. }
  3765. logStatus.error(`${result}:${statusText}(${status})`);
  3766. return {};
  3767. } catch (error) {
  3768. throwError(error, 'Youtube.getInfo');
  3769. return {};
  3770. }
  3771. };
  3772. class Youtube extends social_Social {
  3773. tasks;
  3774. whiteList;
  3775. #auth = GM_getValue('youtubeAuth') || {};
  3776. #initialized = false;
  3777. #verifyChannel = `https://www.youtube.com/channel/${globalOptions.other.youtubeVerifyChannel}`;
  3778. constructor() {
  3779. super();
  3780. const defaultTasksTemplate = {
  3781. channels: [],
  3782. likes: []
  3783. };
  3784. this.tasks = defaultTasksTemplate;
  3785. this.whiteList = {
  3786. ...defaultTasksTemplate,
  3787. ...GM_getValue('whiteList')?.youtube || {}
  3788. };
  3789. }
  3790. async init() {
  3791. try {
  3792. if (this.#initialized) {
  3793. return true;
  3794. }
  3795. if (!this.#auth.PAPISID) {
  3796. if (await this.#updateAuth()) {
  3797. this.#initialized = true;
  3798. return true;
  3799. }
  3800. return false;
  3801. }
  3802. const isVerified = await this.#verifyAuth();
  3803. if (isVerified) {
  3804. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  3805. this.#initialized = true;
  3806. return true;
  3807. }
  3808. GM_setValue('youtubeAuth', null);
  3809. if (await this.#updateAuth()) {
  3810. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  3811. this.#initialized = true;
  3812. return true;
  3813. }
  3814. scripts_echoLog({}).error(i18n('initFailed', 'Youtube'));
  3815. return false;
  3816. } catch (error) {
  3817. throwError(error, 'Youtube.init');
  3818. return false;
  3819. }
  3820. }
  3821. async #verifyAuth() {
  3822. try {
  3823. return await this.#toggleChannel({
  3824. link: this.#verifyChannel,
  3825. doTask: true,
  3826. verify: true
  3827. });
  3828. } catch (error) {
  3829. throwError(error, 'Youtube.verifyAuth');
  3830. return false;
  3831. }
  3832. }
  3833. async #updateAuth() {
  3834. try {
  3835. const logStatus = scripts_echoLog({
  3836. text: i18n('updatingAuth', 'Youtube')
  3837. });
  3838. return await new Promise(resolve => {
  3839. GM_cookie.list({
  3840. url: 'https://www.youtube.com/@YouTube'
  3841. }, async (cookies, error) => {
  3842. if (!error) {
  3843. const PAPISID = cookies.find(cookie => cookie.name === '__Secure-3PAPISID')?.value;
  3844. if (PAPISID) {
  3845. GM_setValue('youtubeAuth', {
  3846. PAPISID: PAPISID
  3847. });
  3848. this.#auth = {
  3849. PAPISID: PAPISID
  3850. };
  3851. logStatus.success();
  3852. resolve(await this.#verifyAuth());
  3853. } else {
  3854. logStatus.error(i18n('needLogin'));
  3855. resolve(false);
  3856. }
  3857. } else {
  3858. logStatus.error('Error: Update youtube auth failed!');
  3859. resolve(false);
  3860. }
  3861. });
  3862. });
  3863. } catch (error) {
  3864. throwError(error, 'Youtube.updateAuth');
  3865. return false;
  3866. }
  3867. }
  3868. #getInfo(link, type) {
  3869. return getInfo(link, type);
  3870. }
  3871. async #toggleChannel({
  3872. link,
  3873. doTask = true,
  3874. verify = false
  3875. }) {
  3876. try {
  3877. const {
  3878. params,
  3879. needLogin
  3880. } = await this.#getInfo(link, 'channel');
  3881. const {
  3882. apiKey,
  3883. client,
  3884. request,
  3885. channelId
  3886. } = params || {};
  3887. if (needLogin) {
  3888. scripts_echoLog({
  3889. html: i18n('loginYtb')
  3890. });
  3891. return false;
  3892. }
  3893. if (!(apiKey && client && request && channelId)) {
  3894. scripts_echoLog({
  3895. text: '"getYtbToken" failed'
  3896. });
  3897. return false;
  3898. }
  3899. if (!doTask && !verify && this.whiteList.channels.includes(channelId)) {
  3900. scripts_echoLog({
  3901. type: 'whiteList',
  3902. text: 'Youtube.unfollowChannel',
  3903. id: channelId
  3904. });
  3905. return true;
  3906. }
  3907. const logStatus = verify ? scripts_echoLog({
  3908. text: i18n('verifyingAuth', 'Youtube')
  3909. }) : scripts_echoLog({
  3910. type: doTask ? 'followingYtbChannel' : 'unfollowingYtbChannel',
  3911. text: channelId
  3912. });
  3913. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  3914. const {
  3915. result,
  3916. statusText,
  3917. status,
  3918. data
  3919. } = await tools_httpRequest({
  3920. url: `https://www.youtube.com/youtubei/v1/subscription/${doTask ? '' : 'un'}subscribe?key=${apiKey}&prettyPrint=false`,
  3921. method: 'POST',
  3922. headers: {
  3923. origin: 'https://www.youtube.com',
  3924. referer: `https://www.youtube.com/channel/${channelId}`,
  3925. 'content-type': 'application/json',
  3926. 'x-goog-authuser': '0',
  3927. 'x-goog-visitor-id': client?.visitorData,
  3928. 'x-origin': 'https://www.youtube.com',
  3929. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  3930. },
  3931. data: JSON.stringify({
  3932. context: {
  3933. client: client,
  3934. request: {
  3935. sessionId: request?.sessionId,
  3936. internalExperimentFlags: [],
  3937. consistencyTokenJars: []
  3938. },
  3939. user: {}
  3940. },
  3941. channelIds: [ channelId ],
  3942. params: doTask ? 'EgIIAhgA' : 'CgIIAhgA'
  3943. })
  3944. });
  3945. if (result === 'Success') {
  3946. if (data?.status === 200) {
  3947. if (doTask && (/"subscribed":true/.test(data.responseText) || data.responseText.includes('The subscription already exists')) || !doTask && /"subscribed":false/.test(data.responseText)) {
  3948. logStatus.success();
  3949. if (doTask && !verify) {
  3950. this.tasks.channels = unique([ ...this.tasks.channels, link ]);
  3951. }
  3952. return true;
  3953. }
  3954. if (verify && data.responseText.includes('You may not subscribe to yourself')) {
  3955. logStatus.success();
  3956. return true;
  3957. }
  3958. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  3959. return false;
  3960. }
  3961. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3962. return false;
  3963. }
  3964. logStatus.error(`${result}:${statusText}(${status})`);
  3965. return false;
  3966. } catch (error) {
  3967. throwError(error, 'Youtube.toggleChannel');
  3968. return false;
  3969. }
  3970. }
  3971. async #toggleLikeVideo({
  3972. link,
  3973. doTask = true
  3974. }) {
  3975. try {
  3976. const {
  3977. params,
  3978. needLogin
  3979. } = await this.#getInfo(link, 'likeVideo');
  3980. const {
  3981. apiKey,
  3982. client,
  3983. request,
  3984. videoId,
  3985. likeParams
  3986. } = params || {};
  3987. if (needLogin) {
  3988. scripts_echoLog({
  3989. html: `${i18n('loginYtb')}`
  3990. });
  3991. return false;
  3992. }
  3993. if (!(apiKey && client && request && videoId && likeParams)) {
  3994. scripts_echoLog({
  3995. text: '"getYtbToken" failed'
  3996. });
  3997. return false;
  3998. }
  3999. if (!doTask && this.whiteList.likes.includes(videoId)) {
  4000. scripts_echoLog({
  4001. type: 'whiteList',
  4002. text: 'Youtube.unlikeVideo',
  4003. id: videoId
  4004. });
  4005. return true;
  4006. }
  4007. const logStatus = scripts_echoLog({
  4008. type: doTask ? 'likingYtbVideo' : 'unlikingYtbVideo',
  4009. text: videoId
  4010. });
  4011. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  4012. const likeVideoData = {
  4013. context: {
  4014. client: client,
  4015. request: {
  4016. sessionId: request.sessionId,
  4017. internalExperimentFlags: [],
  4018. consistencyTokenJars: []
  4019. },
  4020. user: {}
  4021. },
  4022. target: {
  4023. videoId: videoId
  4024. }
  4025. };
  4026. if (doTask) {
  4027. if (likeParams) {
  4028. likeVideoData.params = likeParams;
  4029. } else {
  4030. logStatus.error('Empty likeParams');
  4031. return false;
  4032. }
  4033. }
  4034. const {
  4035. result,
  4036. statusText,
  4037. status,
  4038. data
  4039. } = await tools_httpRequest({
  4040. url: `https://www.youtube.com/youtubei/v1/like/${doTask ? '' : 'remove'}like?key=${apiKey}`,
  4041. method: 'POST',
  4042. headers: {
  4043. origin: 'https://www.youtube.com',
  4044. referer: `https://www.youtube.com/watch?v=${videoId}`,
  4045. 'content-type': 'application/json',
  4046. 'x-goog-authuser': '0',
  4047. 'x-goog-visitor-id': client.visitorData,
  4048. 'x-origin': 'https://www.youtube.com',
  4049. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  4050. },
  4051. data: JSON.stringify(likeVideoData)
  4052. });
  4053. if (result === 'Success') {
  4054. if (data?.status === 200) {
  4055. if (doTask && data.responseText.includes('Added to Liked videos') || !doTask && (data.responseText.includes('Removed from Liked videos') || data.responseText.includes('Dislike removed'))) {
  4056. logStatus.success();
  4057. if (doTask) {
  4058. this.tasks.likes = unique([ ...this.tasks.likes, link ]);
  4059. }
  4060. return true;
  4061. }
  4062. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4063. return false;
  4064. }
  4065. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4066. return false;
  4067. }
  4068. logStatus.error(`${result}:${statusText}(${status})`);
  4069. return false;
  4070. } catch (error) {
  4071. throwError(error, 'Youtube.toggleLikeVideo');
  4072. return false;
  4073. }
  4074. }
  4075. async toggle({
  4076. doTask = true,
  4077. channelLinks = [],
  4078. videoLinks = []
  4079. }) {
  4080. try {
  4081. if (!this.#initialized) {
  4082. scripts_echoLog({
  4083. text: i18n('needInit')
  4084. });
  4085. return false;
  4086. }
  4087. const prom = [];
  4088. if (doTask && !globalOptions.doTask.youtube.channels || !doTask && !globalOptions.undoTask.youtube.channels) {
  4089. scripts_echoLog({
  4090. type: 'globalOptionsSkip',
  4091. text: 'youtube.channels'
  4092. });
  4093. } else {
  4094. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => {
  4095. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4096. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4097. }
  4098. return link;
  4099. });
  4100. if (realChannels.length > 0) {
  4101. for (const channel of realChannels) {
  4102. prom.push(this.#toggleChannel({
  4103. link: channel,
  4104. doTask: doTask
  4105. }));
  4106. await delay(1e3);
  4107. }
  4108. }
  4109. }
  4110. if (doTask && !globalOptions.doTask.youtube.likes || !doTask && !globalOptions.undoTask.youtube.likes) {
  4111. scripts_echoLog({
  4112. type: 'globalOptionsSkip',
  4113. text: 'youtube.likes'
  4114. });
  4115. } else {
  4116. const realLikes = this.getRealParams('likes', videoLinks, doTask, link => {
  4117. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4118. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4119. }
  4120. return link;
  4121. });
  4122. if (realLikes.length > 0) {
  4123. for (const video of realLikes) {
  4124. prom.push(this.#toggleLikeVideo({
  4125. link: video,
  4126. doTask: doTask
  4127. }));
  4128. await delay(1e3);
  4129. }
  4130. }
  4131. }
  4132. return Promise.all(prom).then(() => true);
  4133. } catch (error) {
  4134. throwError(error, 'Youtube.toggle');
  4135. return false;
  4136. }
  4137. }
  4138. }
  4139. class SteamASF {
  4140. #asfOptions;
  4141. #botName = 'asf';
  4142. #groupInfo;
  4143. async init() {
  4144. try {
  4145. const asfCommandsUrl = new URL('/Api/Command/', globalOptions.ASF.AsfIpcUrl);
  4146. this.#asfOptions = {
  4147. url: asfCommandsUrl.href,
  4148. method: 'POST',
  4149. responseType: 'json',
  4150. headers: {
  4151. accept: 'application/json',
  4152. 'Content-Type': 'application/json',
  4153. Host: asfCommandsUrl.host,
  4154. Origin: asfCommandsUrl.origin,
  4155. Referer: asfCommandsUrl.href,
  4156. Authentication: globalOptions.ASF.AsfIpcPassword
  4157. }
  4158. };
  4159. if (globalOptions.ASF.AsfBotname) {
  4160. this.#botName = globalOptions.ASF.AsfBotname;
  4161. }
  4162. const logStatus = scripts_echoLog({
  4163. text: i18n('initingASF')
  4164. });
  4165. const {
  4166. result,
  4167. statusText,
  4168. status,
  4169. data
  4170. } = await tools_httpRequest({
  4171. ...this.#asfOptions,
  4172. data: '{"Command":"!stats"}'
  4173. });
  4174. if (result === 'Success') {
  4175. if (data?.response?.Success === true && data.response.Message === 'OK' && data.response.Result) {
  4176. logStatus.success();
  4177. return true;
  4178. }
  4179. if (data?.response?.Result || data?.response?.Message) {
  4180. logStatus.error(data?.response?.Result || data.response.Message);
  4181. return false;
  4182. }
  4183. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4184. return false;
  4185. }
  4186. logStatus.error(`${result}:${statusText}(${status})`);
  4187. return false;
  4188. } catch (error) {
  4189. throwError(error, 'SteamASF.init');
  4190. return false;
  4191. }
  4192. }
  4193. async joinGroup(groupName) {
  4194. try {
  4195. const logStatus = scripts_echoLog({
  4196. type: 'joiningSteamGroup',
  4197. text: groupName
  4198. });
  4199. const {
  4200. result,
  4201. statusText,
  4202. status,
  4203. data
  4204. } = await tools_httpRequest({
  4205. ...this.#asfOptions,
  4206. data: JSON.stringify({
  4207. Command: `!JOINGROUP ${this.#botName} ${groupName}`
  4208. })
  4209. });
  4210. if (result === 'Success') {
  4211. if (data?.status === 200 && [ '已加入', '已申请', 'Joined', 'Applied', 'Присоединился', 'costs' ].find(text => data.response?.Result?.includes(text))) {
  4212. logStatus.success();
  4213. return true;
  4214. }
  4215. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4216. return false;
  4217. }
  4218. logStatus.error(`${result}:${statusText}(${status})`);
  4219. return false;
  4220. } catch (error) {
  4221. throwError(error, 'SteamASF.joinGroup');
  4222. return false;
  4223. }
  4224. }
  4225. async leaveGroup(groupName) {
  4226. try {
  4227. if (!this.#groupInfo) {
  4228. if (!await this.#getGroupId()) {
  4229. return false;
  4230. }
  4231. }
  4232. const groupId = await this.#groupInfo[groupName];
  4233. if (!groupId) {
  4234. return false;
  4235. }
  4236. const logStatus = scripts_echoLog({
  4237. type: 'leavingSteamGroup',
  4238. text: groupName
  4239. });
  4240. const {
  4241. result,
  4242. statusText,
  4243. status,
  4244. data
  4245. } = await tools_httpRequest({
  4246. ...this.#asfOptions,
  4247. data: JSON.stringify({
  4248. Command: `!LEAVEGROUP ${this.#botName} ${groupId}`
  4249. })
  4250. });
  4251. if (result === 'Success') {
  4252. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4253. logStatus.success();
  4254. return true;
  4255. }
  4256. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4257. return false;
  4258. }
  4259. logStatus.error(`${result}:${statusText}(${status})`);
  4260. return false;
  4261. } catch (error) {
  4262. throwError(error, 'SteamASF.leaveGroup');
  4263. return false;
  4264. }
  4265. }
  4266. async #getGroupId() {
  4267. try {
  4268. const logStatus = scripts_echoLog({
  4269. type: 'gettingSteamGroupId',
  4270. text: 'All'
  4271. });
  4272. const {
  4273. result,
  4274. statusText,
  4275. status,
  4276. data
  4277. } = await tools_httpRequest({
  4278. ...this.#asfOptions,
  4279. data: JSON.stringify({
  4280. Command: `!GROUPLIST ${this.#botName}`
  4281. })
  4282. });
  4283. if (result === 'Success') {
  4284. if (data?.status === 200 && data.response?.Result?.includes('|')) {
  4285. this.#groupInfo = Object.fromEntries(data.response.Result.split('\n').map(line => {
  4286. const [ , name, id ] = line.trim().split('|');
  4287. if (name && id) {
  4288. return [ name, id ];
  4289. }
  4290. return null;
  4291. }).filter(ele => ele));
  4292. logStatus.success();
  4293. return true;
  4294. }
  4295. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4296. return false;
  4297. }
  4298. logStatus.error(`${result}:${statusText}(${status})`);
  4299. return false;
  4300. } catch (error) {
  4301. throwError(error, 'SteamASF.getGroupID');
  4302. return false;
  4303. }
  4304. }
  4305. async addToWishlist(gameId) {
  4306. try {
  4307. const logStatus = scripts_echoLog({
  4308. type: 'addingToWishlist',
  4309. text: gameId
  4310. });
  4311. if ((await this.#checkGame(gameId)).wishlist === true) {
  4312. logStatus.success();
  4313. return true;
  4314. }
  4315. const {
  4316. result,
  4317. statusText,
  4318. status,
  4319. data
  4320. } = await tools_httpRequest({
  4321. ...this.#asfOptions,
  4322. data: JSON.stringify({
  4323. Command: `!ADDWISHLIST ${this.#botName} ${gameId}`
  4324. })
  4325. });
  4326. if (result === 'Success') {
  4327. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4328. logStatus.success();
  4329. return true;
  4330. }
  4331. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4332. return false;
  4333. }
  4334. logStatus.error(`${result}:${statusText}(${status})`);
  4335. return false;
  4336. } catch (error) {
  4337. throwError(error, 'SteamASF.addToWishlist');
  4338. return false;
  4339. }
  4340. }
  4341. async removeFromWishlist(gameId) {
  4342. try {
  4343. const logStatus = scripts_echoLog({
  4344. type: 'removingFromWishlist',
  4345. text: gameId
  4346. });
  4347. if ((await this.#checkGame(gameId)).wishlist === false) {
  4348. logStatus.success();
  4349. return true;
  4350. }
  4351. const {
  4352. result,
  4353. statusText,
  4354. status,
  4355. data
  4356. } = await tools_httpRequest({
  4357. ...this.#asfOptions,
  4358. data: JSON.stringify({
  4359. Command: `!REMOVEWISHLIST ${this.#botName} ${gameId}`
  4360. })
  4361. });
  4362. if (result === 'Success') {
  4363. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4364. logStatus.success();
  4365. return true;
  4366. }
  4367. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4368. return false;
  4369. }
  4370. logStatus.error(`${result}:${statusText}(${status})`);
  4371. return false;
  4372. } catch (error) {
  4373. throwError(error, 'SteamASF.removeFromWishlist');
  4374. return false;
  4375. }
  4376. }
  4377. async toggleFollowGame(gameId, doTask) {
  4378. try {
  4379. const logStatus = scripts_echoLog({
  4380. type: `${doTask ? '' : 'un'}followingGame`,
  4381. text: gameId
  4382. });
  4383. if (doTask && (await this.#checkGame(gameId)).followed === true || !doTask && (await this.#checkGame(gameId)).followed === false) {
  4384. logStatus.success();
  4385. return true;
  4386. }
  4387. const {
  4388. result,
  4389. statusText,
  4390. status,
  4391. data
  4392. } = await tools_httpRequest({
  4393. ...this.#asfOptions,
  4394. data: JSON.stringify({
  4395. Command: `!${doTask ? '' : 'UN'}FOLLOWGAME ${this.#botName} ${gameId}`
  4396. })
  4397. });
  4398. if (result === 'Success') {
  4399. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4400. logStatus.success();
  4401. return true;
  4402. }
  4403. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4404. return false;
  4405. }
  4406. logStatus.error(`${result}:${statusText}(${status})`);
  4407. return false;
  4408. } catch (error) {
  4409. throwError(error, 'SteamASF.toggleFollowGame');
  4410. return false;
  4411. }
  4412. }
  4413. async #checkGame(gameId) {
  4414. try {
  4415. const {
  4416. result,
  4417. data
  4418. } = await tools_httpRequest({
  4419. ...this.#asfOptions,
  4420. data: JSON.stringify({
  4421. Command: `!CHECK ${this.#botName} ${gameId}`
  4422. })
  4423. });
  4424. if (result === 'Success') {
  4425. if (data?.status === 200 && data.response?.Result?.includes(gameId)) {
  4426. const matchedResult = data.response.Result.split('\n').find(result => result.includes(gameId))?.split('|');
  4427. if (matchedResult?.length > 3) {
  4428. return {
  4429. wishlist: matchedResult.at(-3).trim() === '√' || matchedResult.at(-2).trim() === '√',
  4430. followed: matchedResult.at(-1).trim() === '√'
  4431. };
  4432. }
  4433. return {};
  4434. }
  4435. return {};
  4436. }
  4437. return {};
  4438. } catch (error) {
  4439. throwError(error, 'SteamASF.checkGame');
  4440. return {};
  4441. }
  4442. }
  4443. async toggleCurator(curatorId, doTask = true) {
  4444. try {
  4445. const logStatus = scripts_echoLog({
  4446. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  4447. text: curatorId
  4448. });
  4449. const {
  4450. result,
  4451. statusText,
  4452. status,
  4453. data
  4454. } = await tools_httpRequest({
  4455. ...this.#asfOptions,
  4456. data: JSON.stringify({
  4457. Command: `!${doTask ? '' : 'UN'}FOLLOWCURATOR ${this.#botName} ${curatorId}`
  4458. })
  4459. });
  4460. if (result === 'Success') {
  4461. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4462. logStatus.success();
  4463. return true;
  4464. }
  4465. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4466. return false;
  4467. }
  4468. logStatus.error(`${result}:${statusText}(${status})`);
  4469. return false;
  4470. } catch (error) {
  4471. throwError(error, 'Steam.toggleCurator');
  4472. return false;
  4473. }
  4474. }
  4475. async addLicense(id) {
  4476. try {
  4477. const [ type, ids ] = id.split('-');
  4478. if (type === 'appid') {
  4479. const logStatus = scripts_echoLog({
  4480. type: 'addingFreeLicense',
  4481. text: ids
  4482. });
  4483. const {
  4484. result,
  4485. statusText,
  4486. status,
  4487. data
  4488. } = await tools_httpRequest({
  4489. ...this.#asfOptions,
  4490. data: JSON.stringify({
  4491. Command: `!addlicense ${this.#botName} app/${ids}`
  4492. })
  4493. });
  4494. if (result === 'Success') {
  4495. if (data?.status === 200 && [ 'AlreadyPurchased', 'OK' ].find(text => data.response?.Result?.includes(text))) {
  4496. logStatus.success();
  4497. return true;
  4498. }
  4499. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4500. return false;
  4501. }
  4502. logStatus.error(`${result}:${statusText}(${status})`);
  4503. return false;
  4504. } else if (type === 'subid') {
  4505. const idsArr = ids.split(',');
  4506. const logStatus = scripts_echoLog({
  4507. type: 'addingFreeLicenseSubid',
  4508. text: ids
  4509. });
  4510. const {
  4511. result,
  4512. statusText,
  4513. status,
  4514. data
  4515. } = await tools_httpRequest({
  4516. ...this.#asfOptions,
  4517. data: JSON.stringify({
  4518. Command: `!addlicense ${this.#botName} ${idsArr.map(id => `sub/${id}`).join(',')}`
  4519. })
  4520. });
  4521. if (result === 'Success') {
  4522. if (data?.status === 200 && data.response?.Result) {
  4523. const resultLines = data.response.Result.split('\n');
  4524. idsArr.forEach(subid => {
  4525. const targetLine = resultLines.find(text => text.includes(subid));
  4526. if (targetLine && [ '成功', 'Success', 'Успех' ].find(text => targetLine.includes(text))) {
  4527. scripts_echoLog({}).success(targetLine);
  4528. } else {
  4529. scripts_echoLog({}).error(targetLine);
  4530. }
  4531. });
  4532. return true;
  4533. }
  4534. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4535. return false;
  4536. }
  4537. logStatus.error(`${result}:${statusText}(${status})`);
  4538. return false;
  4539. }
  4540. return false;
  4541. } catch (error) {
  4542. throwError(error, 'SteamASF.addLicense');
  4543. return false;
  4544. }
  4545. }
  4546. async requestPlayTestAccess(id) {
  4547. try {
  4548. const logStatus = scripts_echoLog({
  4549. type: 'requestingPlayTestAccess',
  4550. text: id
  4551. });
  4552. const {
  4553. result,
  4554. statusText,
  4555. status,
  4556. data
  4557. } = await tools_httpRequest({
  4558. ...this.#asfOptions,
  4559. data: JSON.stringify({
  4560. Command: `!REQUESTACCESS ${this.#botName} ${id}`
  4561. })
  4562. });
  4563. if (result === 'Success') {
  4564. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4565. logStatus.success();
  4566. return true;
  4567. }
  4568. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4569. return false;
  4570. }
  4571. logStatus.error(`${result}:${statusText}(${status})`);
  4572. return false;
  4573. } catch (error) {
  4574. throwError(error, 'Steam.requestPlayTestAccess');
  4575. return false;
  4576. }
  4577. }
  4578. }
  4579. const social_SteamASF = SteamASF;
  4580. class Steam extends social_Social {
  4581. tasks;
  4582. whiteList;
  4583. #cache = {
  4584. ...{
  4585. group: {},
  4586. officialGroup: {},
  4587. forum: {},
  4588. workshop: {},
  4589. curator: {}
  4590. },
  4591. ...GM_getValue('steamCache')
  4592. };
  4593. #auth = {};
  4594. #storeInitialized = false;
  4595. #communityInitialized = false;
  4596. #area = 'CN';
  4597. #oldArea;
  4598. #areaStatus = 'end';
  4599. #ASF;
  4600. constructor() {
  4601. super();
  4602. const defaultTasksTemplate = {
  4603. groups: [],
  4604. officialGroups: [],
  4605. wishlists: [],
  4606. follows: [],
  4607. forums: [],
  4608. workshops: [],
  4609. workshopVotes: [],
  4610. curators: [],
  4611. curatorLikes: [],
  4612. announcements: [],
  4613. licenses: [],
  4614. playtests: []
  4615. };
  4616. this.tasks = defaultTasksTemplate;
  4617. this.whiteList = {
  4618. ...defaultTasksTemplate,
  4619. ...GM_getValue('whiteList')?.steam || {}
  4620. };
  4621. }
  4622. async init(type = 'all') {
  4623. try {
  4624. if (globalOptions.ASF.AsfEnabled && globalOptions.ASF.AsfIpcUrl && globalOptions.ASF.AsfIpcPassword) {
  4625. this.#ASF = new social_SteamASF();
  4626. if (await this.#ASF.init()) {
  4627. this.#storeInitialized = true;
  4628. this.#communityInitialized = true;
  4629. return true;
  4630. }
  4631. return false;
  4632. }
  4633. if (type === 'store') {
  4634. if (this.#storeInitialized) {
  4635. return true;
  4636. }
  4637. let storeInitialized = await this.#updateStoreAuth();
  4638. if (!storeInitialized) {
  4639. storeInitialized = await this.#updateStoreAuthTab();
  4640. }
  4641. this.#storeInitialized = storeInitialized;
  4642. if (!this.#storeInitialized) {
  4643. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4644. return false;
  4645. }
  4646. scripts_echoLog({}).success(i18n('initSuccess', 'SteamStore'));
  4647. return true;
  4648. }
  4649. if (type === 'community') {
  4650. if (this.#communityInitialized) {
  4651. return true;
  4652. }
  4653. let communityInitialized = await this.#updateCommunityAuth();
  4654. if (!communityInitialized) {
  4655. communityInitialized = await this.#updateCommunityAuthTab();
  4656. GM_setValue('steamCommunityAuth', null);
  4657. }
  4658. this.#communityInitialized = communityInitialized;
  4659. if (!this.#communityInitialized) {
  4660. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4661. return false;
  4662. }
  4663. scripts_echoLog({}).success(i18n('initSuccess', 'SteamCommunity'));
  4664. return true;
  4665. }
  4666. if (this.#storeInitialized && this.#communityInitialized) {
  4667. scripts_echoLog({}).success(i18n('initSuccess', 'Steam'));
  4668. return true;
  4669. }
  4670. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4671. return false;
  4672. } catch (error) {
  4673. throwError(error, 'Steam.init');
  4674. return false;
  4675. }
  4676. }
  4677. async #refreshToken(type = 'steamStore') {
  4678. try {
  4679. const host = {
  4680. steamStore: 'store.steampowered.com',
  4681. steamCommunity: 'steamcommunity.com'
  4682. };
  4683. const logStatus = scripts_echoLog({
  4684. text: i18n('refreshingToken', i18n(type))
  4685. });
  4686. const formData = new FormData();
  4687. formData.append('redir', `https://${host[type]}/`);
  4688. const {
  4689. result,
  4690. statusText,
  4691. status,
  4692. data
  4693. } = await tools_httpRequest({
  4694. url: 'https://login.steampowered.com/jwt/ajaxrefresh',
  4695. method: 'POST',
  4696. responseType: 'json',
  4697. headers: {
  4698. Host: 'login.steampowered.com',
  4699. Origin: `https://${host[type]}`,
  4700. Referer: `https://${host[type]}/`
  4701. },
  4702. data: formData
  4703. });
  4704. if (result === 'Success') {
  4705. if (data?.response?.success) {
  4706. if (await this.#setStoreToken(data.response, type)) {
  4707. logStatus.success();
  4708. return true;
  4709. }
  4710. logStatus.error('Error');
  4711. return false;
  4712. }
  4713. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4714. return false;
  4715. }
  4716. logStatus.error(`${result}:${statusText}(${status})`);
  4717. return false;
  4718. } catch (error) {
  4719. throwError(error, 'Steam.refreshToken');
  4720. return false;
  4721. }
  4722. }
  4723. async #setStoreToken(param, type) {
  4724. try {
  4725. const host = {
  4726. steamStore: 'store.steampowered.com',
  4727. steamCommunity: 'steamcommunity.com'
  4728. };
  4729. const logStatus = scripts_echoLog({
  4730. text: i18n('settingToken', i18n(type))
  4731. });
  4732. const formData = new FormData();
  4733. formData.append('steamID', param.steamID);
  4734. formData.append('nonce', param.nonce);
  4735. formData.append('redir', param.redir);
  4736. formData.append('auth', param.auth);
  4737. const {
  4738. result,
  4739. statusText,
  4740. status,
  4741. data
  4742. } = await tools_httpRequest({
  4743. url: `https://${host[type]}/login/settoken`,
  4744. method: 'POST',
  4745. headers: {
  4746. Accept: 'application/json, text/plain, */*',
  4747. Host: host[type],
  4748. Origin: `https://${host[type]}`
  4749. },
  4750. data: formData
  4751. });
  4752. if (result === 'Success') {
  4753. if (data?.status === 200) {
  4754. logStatus.success();
  4755. return true;
  4756. }
  4757. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4758. return false;
  4759. }
  4760. logStatus.error(`${result}:${statusText}(${status})`);
  4761. return false;
  4762. } catch (error) {
  4763. throwError(error, 'Steam.setStoreToken');
  4764. return false;
  4765. }
  4766. }
  4767. async #updateStoreAuth(retry = false) {
  4768. try {
  4769. const logStatus = scripts_echoLog({
  4770. text: i18n('updatingAuth', i18n('steamStore'))
  4771. });
  4772. const {
  4773. result,
  4774. statusText,
  4775. status,
  4776. data
  4777. } = await tools_httpRequest({
  4778. url: 'https://store.steampowered.com/',
  4779. method: 'GET',
  4780. headers: {
  4781. 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',
  4782. 'Sec-Fetch-Dest': 'document',
  4783. 'Sec-Fetch-Mode': 'navigate',
  4784. 'Upgrade-Insecure-Requests': '1'
  4785. },
  4786. fetch: false,
  4787. redirect: 'manual'
  4788. });
  4789. if (data?.status === 200) {
  4790. if (!data.responseText.includes('data-miniprofile=')) {
  4791. if (await this.#refreshToken('steamStore')) {
  4792. logStatus.warning(i18n('retry'));
  4793. if (retry) {
  4794. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4795. return false;
  4796. }
  4797. return this.#updateStoreAuth(true);
  4798. }
  4799. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4800. return false;
  4801. }
  4802. const storeSessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  4803. if (storeSessionID) {
  4804. this.#auth.storeSessionID = storeSessionID;
  4805. logStatus.success();
  4806. return true;
  4807. }
  4808. logStatus.error('Error: Get "sessionID" failed');
  4809. return false;
  4810. }
  4811. if ([ 301, 302 ].includes(data?.status)) {
  4812. if (await this.#refreshToken('steamStore')) {
  4813. logStatus.warning(i18n('retry'));
  4814. if (retry) {
  4815. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4816. return false;
  4817. }
  4818. return this.#updateStoreAuth(true);
  4819. }
  4820. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4821. return false;
  4822. }
  4823. logStatus.error(`${result}:${statusText}(${status})`);
  4824. return false;
  4825. } catch (error) {
  4826. throwError(error, 'Steam.updateStoreAuth');
  4827. return false;
  4828. }
  4829. }
  4830. async #updateStoreAuthTab() {
  4831. try {
  4832. const logStatus = scripts_echoLog({
  4833. text: i18n('updatingAuth', i18n('steamStoreTab'))
  4834. });
  4835. return await new Promise(resolve => {
  4836. GM_deleteValue('steamStoreAuth');
  4837. GM_setValue('ATv4_updateStoreAuth', true);
  4838. const newTab = GM_openInTab('https://store.steampowered.com/', {
  4839. active: true,
  4840. setParent: true
  4841. });
  4842. newTab.name = 'ATv4_updateStoreAuth';
  4843. const listenerId = GM_addValueChangeListener('steamStoreAuth', (key, oldValue, newValue) => {
  4844. GM_removeValueChangeListener(listenerId);
  4845. GM_deleteValue('ATv4_updateStoreAuth');
  4846. newTab?.close();
  4847. window.focus();
  4848. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  4849. this.#auth.storeSessionID = newValue.storeSessionID;
  4850. logStatus.success();
  4851. resolve(true);
  4852. return;
  4853. }
  4854. logStatus.error('Failed');
  4855. resolve(false);
  4856. });
  4857. newTab.onclose = () => {
  4858. GM_deleteValue('ATv4_updateStoreAuth');
  4859. };
  4860. });
  4861. } catch (error) {
  4862. throwError(error, 'Steam.updateStoreAuthTab');
  4863. return false;
  4864. }
  4865. }
  4866. async #updateCommunityAuthTab() {
  4867. try {
  4868. const logStatus = scripts_echoLog({
  4869. text: i18n('updatingAuth', i18n('steamCommunityTab'))
  4870. });
  4871. return await new Promise(resolve => {
  4872. GM_deleteValue('steamCommunityAuth');
  4873. GM_setValue('ATv4_updateCommunityAuth', true);
  4874. const newTab = GM_openInTab('https://steamcommunity.com/my', {
  4875. active: true,
  4876. setParent: true
  4877. });
  4878. newTab.name = 'ATv4_updateCommunityAuth';
  4879. const listenerId = GM_addValueChangeListener('steamCommunityAuth', (key, oldValue, newValue) => {
  4880. GM_removeValueChangeListener(listenerId);
  4881. GM_deleteValue('ATv4_updateCommunityAuth');
  4882. newTab?.close();
  4883. window.focus();
  4884. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  4885. this.#auth.steam64Id = newValue.steam64Id;
  4886. this.#auth.communitySessionID = newValue.communitySessionID;
  4887. logStatus.success();
  4888. resolve(true);
  4889. return;
  4890. }
  4891. logStatus.error('Failed');
  4892. resolve(false);
  4893. });
  4894. newTab.onclose = () => {
  4895. GM_deleteValue('ATv4_updateCommunityAuth');
  4896. };
  4897. });
  4898. } catch (error) {
  4899. throwError(error, 'Steam.updateCommunityAuthTab');
  4900. return false;
  4901. }
  4902. }
  4903. async #updateCommunityAuth() {
  4904. try {
  4905. const logStatus = scripts_echoLog({
  4906. text: i18n('gettingUserLink')
  4907. });
  4908. const {
  4909. result,
  4910. statusText,
  4911. status,
  4912. data
  4913. } = await tools_httpRequest({
  4914. url: 'https://steamcommunity.com/my',
  4915. method: 'GET',
  4916. headers: {
  4917. 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',
  4918. Host: 'steamcommunity.com',
  4919. 'Sec-Fetch-Dest': 'document',
  4920. 'Sec-Fetch-Mode': 'navigate'
  4921. },
  4922. fetch: false
  4923. });
  4924. if (data?.status === 200) {
  4925. if (data.finalUrl.includes('https://steamcommunity.com/login/home')) {
  4926. logStatus.error(`Error:${i18n('needLoginSteamCommunity')}`, true);
  4927. return false;
  4928. }
  4929. const steam64Id = data.responseText.match(/g_steamID = "(.+?)";/)?.[1];
  4930. const communitySessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  4931. if (steam64Id && communitySessionID) {
  4932. this.#auth.steam64Id = steam64Id;
  4933. this.#auth.communitySessionID = communitySessionID;
  4934. logStatus.success();
  4935. return true;
  4936. }
  4937. logStatus.error('Error: Get "sessionID" failed');
  4938. return false;
  4939. }
  4940. logStatus.error(`${result}:${statusText}(${status})`);
  4941. return false;
  4942. } catch (error) {
  4943. throwError(error, 'Steam.updateCommunityAuth');
  4944. return false;
  4945. }
  4946. }
  4947. async #getAreaInfo() {
  4948. try {
  4949. const logStatus = scripts_echoLog({
  4950. text: i18n('gettingAreaInfo')
  4951. });
  4952. const {
  4953. result,
  4954. statusText,
  4955. status,
  4956. data
  4957. } = await tools_httpRequest({
  4958. url: 'https://store.steampowered.com/cart/',
  4959. method: 'GET'
  4960. });
  4961. if (result === 'Success') {
  4962. if (data?.status === 200) {
  4963. const cartConfigRaw = data.responseText.match(/data-cart_config="(.*?)"/)?.[1];
  4964. const temp = document.createElement('div');
  4965. temp.innerHTML = cartConfigRaw || '{}';
  4966. const cartConfigStr = temp.textContent || temp.innerText;
  4967. let cartConfig;
  4968. try {
  4969. cartConfig = JSON.parse(cartConfigStr);
  4970. } catch (error) {
  4971. logStatus.error('Error: get country info filed');
  4972. console.error(error);
  4973. return {};
  4974. }
  4975. if (!cartConfig.rgUserCountryOptions) {
  4976. logStatus.warning('Warning: Area cannot be changed');
  4977. return {};
  4978. }
  4979. const userInfoRaw = data.responseText.match(/data-userinfo="(.*?)"/)?.[1];
  4980. const temp1 = document.createElement('div');
  4981. temp1.innerHTML = userInfoRaw || '{}';
  4982. const userInfoStr = temp1.textContent || temp1.innerText;
  4983. let userInfo;
  4984. try {
  4985. userInfo = JSON.parse(userInfoStr);
  4986. } catch (error) {
  4987. logStatus.error('Error: get country info filed');
  4988. console.error(error);
  4989. return {};
  4990. }
  4991. const currentArea = userInfo.country_code;
  4992. const areas = Object.keys(cartConfig.rgUserCountryOptions).filter(area => area !== 'help');
  4993. if (currentArea && areas.length > 0) {
  4994. this.#area = currentArea;
  4995. logStatus.success();
  4996. return {
  4997. currentArea: currentArea,
  4998. areas: areas
  4999. };
  5000. }
  5001. logStatus.error('Error: get country info filed');
  5002. return {};
  5003. }
  5004. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5005. return {};
  5006. }
  5007. logStatus.error(`${result}:${statusText}(${status})`);
  5008. return {};
  5009. } catch (error) {
  5010. throwError(error, 'Steam.getAreaInfo');
  5011. return {};
  5012. }
  5013. }
  5014. async #changeArea(area) {
  5015. try {
  5016. if (this.#areaStatus === 'waiting') {
  5017. await new Promise(resolve => {
  5018. const checker = setInterval(() => {
  5019. if (this.#areaStatus !== 'waiting') {
  5020. clearInterval(checker);
  5021. resolve(true);
  5022. }
  5023. });
  5024. });
  5025. }
  5026. if (this.#area === area || !area && this.#area !== 'CN') {
  5027. return true;
  5028. }
  5029. this.#areaStatus = 'waiting';
  5030. let aimedArea = area;
  5031. if (!aimedArea) {
  5032. const {
  5033. currentArea,
  5034. areas
  5035. } = await this.#getAreaInfo();
  5036. if (!currentArea || !areas) {
  5037. this.#areaStatus = 'error';
  5038. return false;
  5039. }
  5040. if (currentArea !== 'CN') {
  5041. this.#areaStatus = 'skip';
  5042. scripts_echoLog({
  5043. text: 'notNeededChangeArea'
  5044. });
  5045. return 'skip';
  5046. }
  5047. const anotherArea = areas.filter(area => area && area !== 'CN');
  5048. if (!anotherArea || anotherArea.length === 0) {
  5049. this.#areaStatus = 'noAnotherArea';
  5050. scripts_echoLog({
  5051. text: 'noAnotherArea'
  5052. });
  5053. return false;
  5054. }
  5055. [ aimedArea ] = anotherArea;
  5056. }
  5057. const logStatus = scripts_echoLog({
  5058. text: i18n('changingArea', aimedArea)
  5059. });
  5060. const {
  5061. result,
  5062. statusText,
  5063. status,
  5064. data
  5065. } = await tools_httpRequest({
  5066. url: 'https://store.steampowered.com/country/setcountry',
  5067. method: 'POST',
  5068. headers: {
  5069. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5070. },
  5071. data: $.param({
  5072. cc: aimedArea,
  5073. sessionid: this.#auth.storeSessionID
  5074. })
  5075. });
  5076. if (result === 'Success') {
  5077. if (data?.status === 200 && data.responseText === 'true') {
  5078. const {
  5079. currentArea
  5080. } = await this.#getAreaInfo();
  5081. if (currentArea) {
  5082. this.#area = currentArea;
  5083. if (!this.#oldArea) {
  5084. this.#oldArea = currentArea;
  5085. }
  5086. }
  5087. if (currentArea === aimedArea) {
  5088. this.#areaStatus = 'success';
  5089. logStatus.success();
  5090. return currentArea;
  5091. }
  5092. this.#areaStatus = 'error';
  5093. logStatus.error('Error: change country filed');
  5094. return 'CN';
  5095. }
  5096. this.#areaStatus = 'error';
  5097. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5098. return 'CN';
  5099. }
  5100. this.#areaStatus = 'error';
  5101. logStatus.error(`${result}:${statusText}(${status})`);
  5102. return 'CN';
  5103. } catch (error) {
  5104. this.#areaStatus = 'error';
  5105. throwError(error, 'Steam.changeArea');
  5106. return false;
  5107. }
  5108. }
  5109. async #joinGroup(groupName) {
  5110. try {
  5111. if (this.#ASF) {
  5112. if (await this.#ASF.joinGroup(groupName)) {
  5113. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5114. return true;
  5115. }
  5116. return false;
  5117. }
  5118. const logStatus = scripts_echoLog({
  5119. type: 'joiningSteamGroup',
  5120. text: groupName
  5121. });
  5122. const {
  5123. result,
  5124. statusText,
  5125. status,
  5126. data
  5127. } = await tools_httpRequest({
  5128. url: `https://steamcommunity.com/groups/${groupName}`,
  5129. method: 'POST',
  5130. headers: {
  5131. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5132. },
  5133. data: $.param({
  5134. action: 'join',
  5135. sessionID: this.#auth.communitySessionID
  5136. })
  5137. });
  5138. if (result === 'Success') {
  5139. if (data?.status === 200 && !data.responseText.includes('grouppage_join_area')) {
  5140. logStatus.success();
  5141. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5142. return true;
  5143. }
  5144. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5145. return false;
  5146. }
  5147. logStatus.error(`${result}:${statusText}(${status})`);
  5148. return false;
  5149. } catch (error) {
  5150. throwError(error, 'Steam.joinGroup');
  5151. return false;
  5152. }
  5153. }
  5154. async #leaveGroup(groupName) {
  5155. try {
  5156. if (this.whiteList.groups.includes(groupName)) {
  5157. scripts_echoLog({
  5158. type: 'whiteList',
  5159. text: 'Steam.leaveGroup',
  5160. id: groupName
  5161. });
  5162. return true;
  5163. }
  5164. if (this.#ASF) {
  5165. return await this.#ASF.leaveGroup(groupName);
  5166. }
  5167. const groupId = await this.#getGroupId(groupName);
  5168. if (!groupId) {
  5169. return false;
  5170. }
  5171. const logStatus = scripts_echoLog({
  5172. type: 'leavingSteamGroup',
  5173. text: groupName
  5174. });
  5175. const {
  5176. result,
  5177. statusText,
  5178. status,
  5179. data
  5180. } = await tools_httpRequest({
  5181. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5182. method: 'POST',
  5183. headers: {
  5184. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5185. },
  5186. data: $.param({
  5187. sessionID: this.#auth.communitySessionID,
  5188. action: 'leaveGroup',
  5189. groupId: groupId
  5190. })
  5191. });
  5192. if (result === 'Success') {
  5193. 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) {
  5194. logStatus.success();
  5195. return true;
  5196. }
  5197. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5198. return false;
  5199. }
  5200. logStatus.error(`${result}:${statusText}(${status})`);
  5201. return false;
  5202. } catch (error) {
  5203. throwError(error, 'Steam.leaveGroup');
  5204. return false;
  5205. }
  5206. }
  5207. async #getGroupId(groupName) {
  5208. try {
  5209. const logStatus = scripts_echoLog({
  5210. type: 'gettingSteamGroupId',
  5211. text: groupName
  5212. });
  5213. const groupId = this.#cache.group[groupName];
  5214. if (groupId) {
  5215. logStatus.success();
  5216. return groupId;
  5217. }
  5218. const {
  5219. result,
  5220. statusText,
  5221. status,
  5222. data
  5223. } = await tools_httpRequest({
  5224. url: `https://steamcommunity.com/groups/${groupName}`,
  5225. method: 'GET',
  5226. headers: {
  5227. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5228. }
  5229. });
  5230. if (result === 'Success') {
  5231. if (data?.status === 200) {
  5232. const groupId = data.responseText.match(/OpenGroupChat\( '([0-9]+)'/)?.[1];
  5233. if (groupId) {
  5234. this.#setCache('group', groupName, groupId);
  5235. logStatus.success();
  5236. return groupId;
  5237. }
  5238. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5239. return false;
  5240. }
  5241. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5242. return false;
  5243. }
  5244. logStatus.error(`${result}:${statusText}(${status})`);
  5245. return false;
  5246. } catch (error) {
  5247. throwError(error, 'Steam.getGroupID');
  5248. return false;
  5249. }
  5250. }
  5251. async #joinOfficialGroup(gameId) {
  5252. try {
  5253. if (this.#ASF) {
  5254. if (await this.#ASF.joinGroup(gameId)) {
  5255. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5256. return true;
  5257. }
  5258. return false;
  5259. }
  5260. const logStatus = scripts_echoLog({
  5261. type: 'joiningSteamOfficialGroup',
  5262. text: gameId
  5263. });
  5264. const {
  5265. result,
  5266. statusText,
  5267. status,
  5268. data
  5269. } = await tools_httpRequest({
  5270. url: `https://steamcommunity.com/games/${gameId}?action=join&sessionID=${this.#auth.communitySessionID}`,
  5271. method: 'GET',
  5272. headers: {
  5273. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5274. }
  5275. });
  5276. if (result === 'Success') {
  5277. if (data?.status === 200 && !data.responseText.includes('id="publicGroupJoin"')) {
  5278. logStatus.success();
  5279. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5280. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5281. if (groupId) {
  5282. this.#setCache('officialGroup', gameId, groupId);
  5283. }
  5284. return true;
  5285. }
  5286. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5287. return false;
  5288. }
  5289. logStatus.error(`${result}:${statusText}(${status})`);
  5290. return false;
  5291. } catch (error) {
  5292. throwError(error, 'Steam.joinOfficialGroup');
  5293. return false;
  5294. }
  5295. }
  5296. async #leaveOfficialGroup(gameId) {
  5297. try {
  5298. if (this.whiteList.officialGroups.includes(gameId)) {
  5299. scripts_echoLog({
  5300. type: 'whiteList',
  5301. text: 'Steam.leaveOfficialGroup',
  5302. id: gameId
  5303. });
  5304. return true;
  5305. }
  5306. if (this.#ASF) {
  5307. return await this.#ASF.leaveGroup(gameId);
  5308. }
  5309. const groupId = await this.#getOfficialGroupId(gameId);
  5310. if (!groupId) {
  5311. return false;
  5312. }
  5313. const logStatus = scripts_echoLog({
  5314. type: 'leavingSteamOfficialGroup',
  5315. text: gameId
  5316. });
  5317. const {
  5318. result,
  5319. statusText,
  5320. status,
  5321. data
  5322. } = await tools_httpRequest({
  5323. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5324. method: 'POST',
  5325. headers: {
  5326. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5327. },
  5328. data: $.param({
  5329. sessionID: this.#auth.communitySessionID,
  5330. action: 'leaveGroup',
  5331. groupId: groupId
  5332. })
  5333. });
  5334. if (result === 'Success') {
  5335. if (data?.status === 200) {
  5336. const {
  5337. result: resultR,
  5338. statusText: statusTextR,
  5339. status: statusR,
  5340. data: dataR
  5341. } = await tools_httpRequest({
  5342. url: `https://steamcommunity.com/games/${gameId}`,
  5343. method: 'GET',
  5344. headers: {
  5345. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5346. }
  5347. });
  5348. if (resultR === 'Success') {
  5349. if (dataR?.status === 200 && dataR.responseText.includes('id="publicGroupJoin"')) {
  5350. logStatus.success();
  5351. return true;
  5352. }
  5353. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5354. return false;
  5355. }
  5356. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5357. return false;
  5358. }
  5359. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5360. return false;
  5361. }
  5362. logStatus.error(`${result}:${statusText}(${status})`);
  5363. return false;
  5364. } catch (error) {
  5365. throwError(error, 'Steam.leaveOfficialGroup');
  5366. return false;
  5367. }
  5368. }
  5369. async #getOfficialGroupId(gameId) {
  5370. try {
  5371. const logStatus = scripts_echoLog({
  5372. type: 'gettingSteamOfficialGroupId',
  5373. text: gameId
  5374. });
  5375. const groupId = this.#cache.officialGroup[gameId];
  5376. if (groupId) {
  5377. logStatus.success();
  5378. return groupId;
  5379. }
  5380. const {
  5381. result,
  5382. statusText,
  5383. status,
  5384. data
  5385. } = await tools_httpRequest({
  5386. url: `https://steamcommunity.com/games/${gameId}`,
  5387. method: 'GET',
  5388. headers: {
  5389. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5390. }
  5391. });
  5392. if (result === 'Success') {
  5393. if (data?.status === 200) {
  5394. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5395. if (groupId) {
  5396. this.#setCache('officialGroup', gameId, groupId);
  5397. logStatus.success();
  5398. return groupId;
  5399. }
  5400. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5401. return false;
  5402. }
  5403. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5404. return false;
  5405. }
  5406. logStatus.error(`${result}:${statusText}(${status})`);
  5407. return false;
  5408. } catch (error) {
  5409. throwError(error, 'Steam.getGroupID');
  5410. return false;
  5411. }
  5412. }
  5413. async #addToWishlist(gameId) {
  5414. try {
  5415. if (this.#ASF) {
  5416. if (await this.#ASF.addToWishlist(gameId)) {
  5417. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5418. return true;
  5419. }
  5420. return false;
  5421. }
  5422. const logStatus = scripts_echoLog({
  5423. type: 'addingToWishlist',
  5424. text: gameId
  5425. });
  5426. const {
  5427. result,
  5428. data
  5429. } = await tools_httpRequest({
  5430. url: 'https://store.steampowered.com/api/addtowishlist',
  5431. method: 'POST',
  5432. headers: {
  5433. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5434. },
  5435. data: $.param({
  5436. sessionid: this.#auth.storeSessionID,
  5437. appid: gameId
  5438. }),
  5439. dataType: 'json'
  5440. });
  5441. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  5442. logStatus.success();
  5443. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5444. return true;
  5445. }
  5446. const {
  5447. result: resultR,
  5448. statusText: statusTextR,
  5449. status: statusR,
  5450. data: dataR
  5451. } = await tools_httpRequest({
  5452. url: `https://store.steampowered.com/app/${gameId}`,
  5453. method: 'GET'
  5454. });
  5455. if (resultR === 'Success') {
  5456. if (dataR?.status === 200) {
  5457. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  5458. logStatus.warning(i18n('changeAreaNotice'));
  5459. if (!await this.#changeArea()) {
  5460. return false;
  5461. }
  5462. return await this.#addToWishlist(gameId);
  5463. }
  5464. if (dataR.responseText.includes('class="queue_actions_ctn"') && dataR.responseText.includes('class="already_in_library"')) {
  5465. logStatus.success();
  5466. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5467. return true;
  5468. } 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"')) {
  5469. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  5470. return false;
  5471. }
  5472. logStatus.success();
  5473. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5474. return true;
  5475. }
  5476. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5477. return false;
  5478. }
  5479. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5480. return false;
  5481. } catch (error) {
  5482. throwError(error, 'Steam.addToWishlist');
  5483. return false;
  5484. }
  5485. }
  5486. async #removeFromWishlist(gameId) {
  5487. try {
  5488. if (this.whiteList.wishlists.includes(gameId)) {
  5489. scripts_echoLog({
  5490. type: 'whiteList',
  5491. text: 'Steam.removeFromWishlist',
  5492. id: gameId
  5493. });
  5494. return true;
  5495. }
  5496. if (this.#ASF) {
  5497. return await this.#ASF.removeFromWishlist(gameId);
  5498. }
  5499. const logStatus = scripts_echoLog({
  5500. type: 'removingFromWishlist',
  5501. text: gameId
  5502. });
  5503. const {
  5504. result,
  5505. data
  5506. } = await tools_httpRequest({
  5507. url: 'https://store.steampowered.com/api/removefromwishlist',
  5508. method: 'POST',
  5509. headers: {
  5510. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5511. },
  5512. data: $.param({
  5513. sessionid: this.#auth.storeSessionID,
  5514. appid: gameId
  5515. }),
  5516. dataType: 'json'
  5517. });
  5518. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  5519. logStatus.success();
  5520. return true;
  5521. }
  5522. const {
  5523. result: resultR,
  5524. statusText: statusTextR,
  5525. status: statusR,
  5526. data: dataR
  5527. } = await tools_httpRequest({
  5528. url: `https://store.steampowered.com/app/${gameId}`,
  5529. method: 'GET'
  5530. });
  5531. if (resultR === 'Success') {
  5532. if (dataR?.status === 200) {
  5533. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  5534. logStatus.warning(i18n('changeAreaNotice'));
  5535. const result = await this.#changeArea();
  5536. if (!result || result === 'CN' || result === 'skip') {
  5537. return false;
  5538. }
  5539. return await this.#removeFromWishlist(gameId);
  5540. }
  5541. if (dataR.responseText.includes('class="queue_actions_ctn"') && (dataR.responseText.includes('ds_owned_flag ds_flag') || dataR.responseText.includes('add_to_wishlist_area'))) {
  5542. logStatus.success();
  5543. return true;
  5544. }
  5545. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  5546. return false;
  5547. }
  5548. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5549. return false;
  5550. }
  5551. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5552. return false;
  5553. } catch (error) {
  5554. throwError(error, 'Steam.removeFromWishlist');
  5555. return false;
  5556. }
  5557. }
  5558. async #toggleFollowGame(gameId, doTask) {
  5559. try {
  5560. if (!doTask && this.whiteList.follows.includes(gameId)) {
  5561. scripts_echoLog({
  5562. type: 'whiteList',
  5563. text: 'Steam.unfollowGame',
  5564. id: gameId
  5565. });
  5566. return true;
  5567. }
  5568. if (this.#ASF) {
  5569. if (await this.#ASF.toggleFollowGame(gameId, doTask)) {
  5570. if (doTask) {
  5571. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  5572. }
  5573. return true;
  5574. }
  5575. return false;
  5576. }
  5577. const logStatus = scripts_echoLog({
  5578. type: `${doTask ? '' : 'un'}followingGame`,
  5579. text: gameId
  5580. });
  5581. const requestData = {
  5582. sessionid: this.#auth.storeSessionID,
  5583. appid: gameId
  5584. };
  5585. if (!doTask) {
  5586. requestData.unfollow = '1';
  5587. }
  5588. const {
  5589. result,
  5590. data
  5591. } = await tools_httpRequest({
  5592. url: 'https://store.steampowered.com/explore/followgame/',
  5593. method: 'POST',
  5594. headers: {
  5595. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5596. },
  5597. data: $.param(requestData)
  5598. });
  5599. if (result === 'Success' && data?.status === 200 && data.responseText === 'true') {
  5600. logStatus.success();
  5601. return true;
  5602. }
  5603. const followed = await this.#isFollowedGame(gameId);
  5604. if (this.#area === 'CN' && followed === 'areaLocked') {
  5605. logStatus.warning(i18n('changeAreaNotice'));
  5606. if (!await this.#changeArea()) {
  5607. return false;
  5608. }
  5609. return await this.#toggleFollowGame(gameId, doTask);
  5610. }
  5611. if (doTask === followed) {
  5612. logStatus.success();
  5613. if (doTask) {
  5614. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  5615. }
  5616. return true;
  5617. }
  5618. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5619. return false;
  5620. } catch (error) {
  5621. throwError(error, 'Steam.toggleFollowGame');
  5622. return false;
  5623. }
  5624. }
  5625. async #isFollowedGame(gameId) {
  5626. try {
  5627. const {
  5628. result,
  5629. data
  5630. } = await tools_httpRequest({
  5631. url: `https://store.steampowered.com/app/${gameId}`,
  5632. method: 'GET'
  5633. });
  5634. if (result === 'Success') {
  5635. if (data?.status === 200) {
  5636. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  5637. return 'areaLocked';
  5638. }
  5639. if ($(data.responseText.replace(/<img.*?>/g, '')).find('.queue_control_button.queue_btn_follow>.btnv6_blue_hoverfade.btn_medium.queue_btn_active').css('display') !== 'none') {
  5640. return true;
  5641. }
  5642. return false;
  5643. }
  5644. return false;
  5645. }
  5646. return false;
  5647. } catch (error) {
  5648. throwError(error, 'Steam.isFollowedGame');
  5649. return false;
  5650. }
  5651. }
  5652. async #toggleForum(gameId, doTask = true) {
  5653. try {
  5654. if (!doTask && this.whiteList.forums.includes(gameId)) {
  5655. scripts_echoLog({
  5656. type: 'whiteList',
  5657. text: 'Steam.unsubscribeForum',
  5658. id: gameId
  5659. });
  5660. return true;
  5661. }
  5662. const forumId = await this.#getForumId(gameId);
  5663. if (!forumId) {
  5664. return false;
  5665. }
  5666. const logStatus = scripts_echoLog({
  5667. type: `${doTask ? '' : 'un'}subscribingForum`,
  5668. text: gameId
  5669. });
  5670. const [ id, feature ] = forumId.split('_');
  5671. const {
  5672. result,
  5673. statusText,
  5674. status,
  5675. data
  5676. } = await tools_httpRequest({
  5677. url: `https://steamcommunity.com/forum/${id}/General/${doTask ? '' : 'un'}subscribe/${feature || '0'}/`,
  5678. method: 'POST',
  5679. responseType: 'json',
  5680. headers: {
  5681. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5682. },
  5683. data: $.param({
  5684. sessionid: this.#auth.communitySessionID
  5685. })
  5686. });
  5687. if (result === 'Success') {
  5688. if (data?.status === 200 && (data.response?.success === 1 || data.response?.success === 29)) {
  5689. if (doTask) {
  5690. this.tasks.forums = unique([ ...this.tasks.forums, gameId ]);
  5691. }
  5692. logStatus.success();
  5693. return true;
  5694. }
  5695. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5696. return true;
  5697. }
  5698. logStatus.error(`${result}:${statusText}(${status})`);
  5699. return true;
  5700. } catch (error) {
  5701. throwError(error, 'Steam.toggleForum');
  5702. return true;
  5703. }
  5704. }
  5705. async #getForumId(gameId) {
  5706. try {
  5707. const logStatus = scripts_echoLog({
  5708. type: 'gettingForumId',
  5709. text: gameId
  5710. });
  5711. const forumId = this.#cache.forum[gameId];
  5712. if (forumId) {
  5713. logStatus.success();
  5714. return forumId;
  5715. }
  5716. const {
  5717. result,
  5718. statusText,
  5719. status,
  5720. data
  5721. } = await tools_httpRequest({
  5722. url: `https://steamcommunity.com/app/${gameId}/discussions/`,
  5723. method: 'GET'
  5724. });
  5725. if (result === 'Success') {
  5726. if (data?.status === 200) {
  5727. const forumId = data.responseText?.match(/General_([\d]+(_[\d]+)?)/)?.[1];
  5728. if (forumId) {
  5729. this.#setCache('forum', gameId, forumId);
  5730. logStatus.success();
  5731. return forumId;
  5732. }
  5733. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5734. return false;
  5735. }
  5736. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5737. return false;
  5738. }
  5739. logStatus.error(`${result}:${statusText}(${status})`);
  5740. return false;
  5741. } catch (error) {
  5742. throwError(error, 'Steam.getForumId');
  5743. return false;
  5744. }
  5745. }
  5746. async #toggleFavoriteWorkshop(id, doTask = true) {
  5747. try {
  5748. if (!doTask && this.whiteList.workshops.includes(id)) {
  5749. scripts_echoLog({
  5750. type: 'whiteList',
  5751. text: 'Steam.unfavoriteWorkshop',
  5752. id: id
  5753. });
  5754. return true;
  5755. }
  5756. const appid = await this.#getWorkshopAppId(id);
  5757. if (!appid) {
  5758. return false;
  5759. }
  5760. const logStatus = scripts_echoLog({
  5761. type: doTask ? 'favoritingWorkshop' : 'unfavoritingWorkshop',
  5762. text: id
  5763. });
  5764. const {
  5765. result,
  5766. statusText,
  5767. status,
  5768. data
  5769. } = await tools_httpRequest({
  5770. url: `https://steamcommunity.com/sharedfiles/${doTask ? '' : 'un'}favorite`,
  5771. method: 'POST',
  5772. headers: {
  5773. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5774. },
  5775. data: $.param({
  5776. id: id,
  5777. appid: appid,
  5778. sessionid: this.#auth.communitySessionID
  5779. })
  5780. });
  5781. if (result === 'Success') {
  5782. if (data?.status === 200 && !data.responseText) {
  5783. if (doTask) {
  5784. this.tasks.workshops = unique([ ...this.tasks.workshops, id ]);
  5785. }
  5786. logStatus.success();
  5787. return true;
  5788. }
  5789. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5790. return false;
  5791. }
  5792. logStatus.error(`${result}:${statusText}(${status})`);
  5793. return false;
  5794. } catch (error) {
  5795. throwError(error, 'Steam.toggleFavoriteWorkshop');
  5796. return false;
  5797. }
  5798. }
  5799. async #getWorkshopAppId(id) {
  5800. try {
  5801. const logStatus = scripts_echoLog({
  5802. type: 'gettingWorkshopAppId',
  5803. text: id
  5804. });
  5805. const appId = this.#cache.workshop[id];
  5806. if (appId) {
  5807. logStatus.success();
  5808. return appId;
  5809. }
  5810. const {
  5811. result,
  5812. statusText,
  5813. status,
  5814. data
  5815. } = await tools_httpRequest({
  5816. url: `https://steamcommunity.com/sharedfiles/filedetails/?id=${id}`,
  5817. method: 'GET'
  5818. });
  5819. if (result === 'Success') {
  5820. if (data?.status === 200) {
  5821. const appId = data.responseText.match(/<input type="hidden" name="appid" value="([\d]+?)" \/>/)?.[1];
  5822. if (appId) {
  5823. this.#setCache('workshop', id, appId);
  5824. logStatus.success();
  5825. return appId;
  5826. }
  5827. logStatus.error('Error: getWorkshopAppId failed');
  5828. return false;
  5829. }
  5830. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5831. return false;
  5832. }
  5833. logStatus.error(`${result}:${statusText}(${status})`);
  5834. return false;
  5835. } catch (error) {
  5836. throwError(error, 'Steam.getWorkshopAppId');
  5837. return false;
  5838. }
  5839. }
  5840. async #voteUpWorkshop(id) {
  5841. try {
  5842. const logStatus = scripts_echoLog({
  5843. type: 'votingUpWorkshop',
  5844. text: id
  5845. });
  5846. const {
  5847. result,
  5848. statusText,
  5849. status,
  5850. data
  5851. } = await tools_httpRequest({
  5852. url: 'https://steamcommunity.com/sharedfiles/voteup',
  5853. method: 'POST',
  5854. responseType: 'json',
  5855. headers: {
  5856. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5857. },
  5858. data: $.param({
  5859. id: id,
  5860. sessionid: this.#auth.communitySessionID
  5861. })
  5862. });
  5863. if (result === 'Success') {
  5864. if (data?.status === 200 && data.response?.success === 1) {
  5865. logStatus.success();
  5866. return true;
  5867. }
  5868. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5869. return true;
  5870. }
  5871. logStatus.error(`${result}:${statusText}(${status})`);
  5872. return true;
  5873. } catch (error) {
  5874. throwError(error, 'Steam.voteupWorkshop');
  5875. return true;
  5876. }
  5877. }
  5878. async #toggleCurator(curatorId, doTask = true) {
  5879. try {
  5880. if (!doTask && this.whiteList.curators.includes(curatorId)) {
  5881. scripts_echoLog({
  5882. type: 'whiteList',
  5883. text: 'Steam.unfollowCurator',
  5884. id: curatorId
  5885. });
  5886. return true;
  5887. }
  5888. if (this.#ASF) {
  5889. return await this.#ASF.toggleCurator(curatorId, doTask);
  5890. }
  5891. const logStatus = scripts_echoLog({
  5892. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  5893. text: curatorId
  5894. });
  5895. const {
  5896. result,
  5897. statusText,
  5898. status,
  5899. data
  5900. } = await tools_httpRequest({
  5901. url: 'https://store.steampowered.com/curators/ajaxfollow',
  5902. method: 'POST',
  5903. headers: {
  5904. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5905. },
  5906. data: $.param({
  5907. clanid: curatorId,
  5908. sessionid: this.#auth.storeSessionID,
  5909. follow: doTask
  5910. }),
  5911. dataType: 'json'
  5912. });
  5913. if (result === 'Success') {
  5914. if (data?.status === 200 && data.response?.success?.success === 1) {
  5915. logStatus.success();
  5916. return true;
  5917. }
  5918. logStatus.error(`Error:${data?.statusText}(${data?.response?.success}` || `${data?.status})`);
  5919. return false;
  5920. }
  5921. logStatus.error(`${result}:${statusText}(${status})`);
  5922. return false;
  5923. } catch (error) {
  5924. throwError(error, 'Steam.toggleCurator');
  5925. return false;
  5926. }
  5927. }
  5928. async getCuratorId(path, name) {
  5929. try {
  5930. const logStatus = scripts_echoLog({
  5931. type: 'gettingCuratorId',
  5932. text: `${path}/${name}`
  5933. });
  5934. const curatorId = this.#cache.curator[`${path}/${name}`];
  5935. if (curatorId) {
  5936. logStatus.success();
  5937. return curatorId;
  5938. }
  5939. const {
  5940. result,
  5941. statusText,
  5942. status,
  5943. data
  5944. } = await tools_httpRequest({
  5945. url: `https://store.steampowered.com/${path}/${name}`,
  5946. method: 'GET',
  5947. headers: {
  5948. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5949. }
  5950. });
  5951. if (result === 'Success') {
  5952. if (data?.status === 200) {
  5953. const curatorId = data.responseText.match(/g_pagingData.*?"clanid":([\d]+)/)?.[1];
  5954. if (curatorId) {
  5955. this.#setCache('curator', `${path}/${name}`, curatorId);
  5956. logStatus.success();
  5957. return curatorId;
  5958. }
  5959. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5960. return false;
  5961. }
  5962. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5963. return false;
  5964. }
  5965. logStatus.error(`${result}:${statusText}(${status})`);
  5966. return false;
  5967. } catch (error) {
  5968. throwError(error, 'Steam.getCuratorID');
  5969. return false;
  5970. }
  5971. }
  5972. async #toggleCuratorLike(link, doTask = true) {
  5973. try {
  5974. const [ path, name ] = link.split('/');
  5975. if (!(path && name)) {
  5976. scripts_echoLog({
  5977. text: i18n('errorLink', link)
  5978. });
  5979. return false;
  5980. }
  5981. const curatorId = await this.getCuratorId(path, name);
  5982. if (curatorId) {
  5983. return await this.#toggleCurator(curatorId, doTask);
  5984. }
  5985. return false;
  5986. } catch (error) {
  5987. throwError(error, 'Steam.toggleCuratorLike');
  5988. return false;
  5989. }
  5990. }
  5991. async #getAnnouncementParams(appId, viewId) {
  5992. try {
  5993. const logStatus = scripts_echoLog({
  5994. type: 'gettingAnnouncementParams',
  5995. text: appId,
  5996. id: viewId
  5997. });
  5998. const {
  5999. result,
  6000. statusText,
  6001. status,
  6002. data
  6003. } = await tools_httpRequest({
  6004. 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`,
  6005. method: 'GET',
  6006. responseType: 'json',
  6007. headers: {
  6008. Host: 'store.steampowered.com',
  6009. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6010. }
  6011. });
  6012. if (result === 'Success') {
  6013. if (data?.status === 200 && data?.response?.success === 1) {
  6014. const {
  6015. clanid,
  6016. gid
  6017. } = data.response.event?.announcement_body || {};
  6018. if (clanid) {
  6019. logStatus.success();
  6020. return {
  6021. clanId: clanid,
  6022. gid: gid
  6023. };
  6024. }
  6025. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6026. return {};
  6027. }
  6028. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6029. return {};
  6030. }
  6031. logStatus.error(`${result}:${statusText}(${status})`);
  6032. return {};
  6033. } catch (error) {
  6034. throwError(error, 'Steam.likeAnnouncement');
  6035. return {};
  6036. }
  6037. }
  6038. async #likeAnnouncement(id) {
  6039. try {
  6040. const [ appId, viewId ] = id.split('/');
  6041. if (!(appId && viewId)) {
  6042. scripts_echoLog({}).error(`${i18n('missParams')}(id)`);
  6043. return false;
  6044. }
  6045. const {
  6046. clanId,
  6047. gid
  6048. } = await this.#getAnnouncementParams(appId, viewId);
  6049. if (!clanId) {
  6050. return false;
  6051. }
  6052. const logStatus = scripts_echoLog({
  6053. type: 'likingAnnouncement',
  6054. text: appId,
  6055. id: viewId
  6056. });
  6057. const {
  6058. result,
  6059. statusText,
  6060. status,
  6061. data
  6062. } = await tools_httpRequest({
  6063. url: `https://store.steampowered.com/updated/ajaxrateupdate/${gid || viewId}`,
  6064. method: 'POST',
  6065. headers: {
  6066. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6067. Host: 'store.steampowered.com',
  6068. Origin: 'https://store.steampowered.com',
  6069. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6070. },
  6071. data: $.param({
  6072. sessionid: this.#auth.storeSessionID,
  6073. voteup: 1,
  6074. clanid: clanId,
  6075. ajax: 1
  6076. }),
  6077. dataType: 'json'
  6078. });
  6079. if (result === 'Success') {
  6080. if (data?.status === 200 && data.response.success === 1) {
  6081. logStatus.success();
  6082. return true;
  6083. }
  6084. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6085. return false;
  6086. }
  6087. logStatus.error(`${result}:${statusText}(${status})`);
  6088. return false;
  6089. } catch (error) {
  6090. throwError(error, 'Steam.likeAnnouncement');
  6091. return false;
  6092. }
  6093. }
  6094. async #appid2subid(id) {
  6095. try {
  6096. const logStatus = scripts_echoLog({
  6097. type: 'gettingSubid',
  6098. text: id
  6099. });
  6100. const {
  6101. result,
  6102. statusText,
  6103. status,
  6104. data
  6105. } = await tools_httpRequest({
  6106. url: `https://store.steampowered.com/app/${id}`,
  6107. method: 'GET',
  6108. headers: {
  6109. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6110. }
  6111. });
  6112. if (result === 'Success') {
  6113. if (data?.status === 200) {
  6114. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6115. logStatus.success(i18n('owned'));
  6116. return false;
  6117. }
  6118. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6119. logStatus.warning(i18n('changeAreaNotice'));
  6120. const result = await this.#changeArea();
  6121. if (!result || result === 'CN' || result === 'skip') {
  6122. return false;
  6123. }
  6124. return await this.#appid2subid(id);
  6125. }
  6126. let subid = data.responseText.match(/name="subid" value="([\d]+?)"/)?.[1];
  6127. if (subid) {
  6128. logStatus.success();
  6129. return subid;
  6130. }
  6131. subid = data.responseText.match(/AddFreeLicense\(\s*(\d+)/)?.[1];
  6132. if (subid) {
  6133. logStatus.success();
  6134. return subid;
  6135. }
  6136. logStatus.error(`Error:${i18n('noSubid')}`);
  6137. return false;
  6138. }
  6139. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6140. return false;
  6141. }
  6142. logStatus.error(`${result}:${statusText}(${status})`);
  6143. return false;
  6144. } catch (error) {
  6145. throwError(error, 'Steam.appid2subid');
  6146. return false;
  6147. }
  6148. }
  6149. async #getLicenses() {
  6150. try {
  6151. const logStatus = scripts_echoLog({
  6152. text: i18n('gettingLicenses')
  6153. });
  6154. const {
  6155. result,
  6156. statusText,
  6157. status,
  6158. data
  6159. } = await tools_httpRequest({
  6160. url: `https://store.steampowered.com/dynamicstore/userdata/?t=${new Date().getTime()}`,
  6161. method: 'GET',
  6162. responseType: 'json'
  6163. });
  6164. if (result === 'Success') {
  6165. if (data?.status === 200) {
  6166. logStatus.success();
  6167. return data.response?.rgOwnedPackages;
  6168. }
  6169. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6170. return false;
  6171. }
  6172. logStatus.error(`${result}:${statusText}(${status})`);
  6173. return false;
  6174. } catch (error) {
  6175. throwError(error, 'Steam.getLicenses');
  6176. return false;
  6177. }
  6178. }
  6179. async #addLicense(id) {
  6180. try {
  6181. if (this.#ASF) {
  6182. return await this.#ASF.addLicense(id);
  6183. }
  6184. const [ type, ids ] = id.split('-');
  6185. if (type === 'appid') {
  6186. const subid = await this.#appid2subid(ids);
  6187. if (!subid) {
  6188. return false;
  6189. }
  6190. const logStatus = scripts_echoLog({
  6191. type: 'addingFreeLicense',
  6192. text: ids
  6193. });
  6194. if (!await this.#addFreeLicense(subid, logStatus)) {
  6195. return false;
  6196. }
  6197. const {
  6198. result,
  6199. statusText,
  6200. status,
  6201. data
  6202. } = await tools_httpRequest({
  6203. url: `https://store.steampowered.com/app/${ids}`,
  6204. method: 'GET'
  6205. });
  6206. if (result === 'Success') {
  6207. if (data?.status === 200) {
  6208. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6209. logStatus.success();
  6210. return true;
  6211. }
  6212. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6213. return false;
  6214. }
  6215. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6216. return false;
  6217. }
  6218. logStatus.error(`${result}:${statusText}(${status})`);
  6219. return false;
  6220. } else if (type === 'subid') {
  6221. if (this.#area === 'CN') {
  6222. scripts_echoLog({}).success(i18n('tryChangeAreaNotice'));
  6223. await this.#changeArea();
  6224. }
  6225. const logStatusArr = {};
  6226. const idsArr = ids.split(',');
  6227. for (const subid of idsArr) {
  6228. const logStatus = scripts_echoLog({
  6229. type: 'addingFreeLicenseSubid',
  6230. text: subid
  6231. });
  6232. if (!await this.#addFreeLicense(subid, logStatus)) {
  6233. return false;
  6234. }
  6235. logStatusArr[subid] = logStatus;
  6236. }
  6237. const licenses = await this.#getLicenses();
  6238. if (!licenses) {
  6239. return false;
  6240. }
  6241. for (const subid of idsArr) {
  6242. if (licenses.includes(parseInt(subid, 10))) {
  6243. logStatusArr[subid].success();
  6244. } else {
  6245. logStatusArr[subid].error();
  6246. }
  6247. }
  6248. return true;
  6249. }
  6250. return false;
  6251. } catch (error) {
  6252. throwError(error, 'Steam.addLicense');
  6253. return false;
  6254. }
  6255. }
  6256. async #addFreeLicense(id, logStatusPre) {
  6257. try {
  6258. const logStatus = logStatusPre || scripts_echoLog({
  6259. type: 'addingFreeLicenseSubid',
  6260. text: id
  6261. });
  6262. const {
  6263. result,
  6264. statusText,
  6265. status,
  6266. data
  6267. } = await tools_httpRequest({
  6268. url: `https://store.steampowered.com/freelicense/addfreelicense/${id}`,
  6269. method: 'POST',
  6270. headers: {
  6271. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6272. Host: 'store.steampowered.com',
  6273. Origin: 'https://store.steampowered.com',
  6274. Referer: 'https://store.steampowered.com/account/licenses/'
  6275. },
  6276. data: $.param({
  6277. ajax: true,
  6278. sessionid: this.#auth.storeSessionID
  6279. }),
  6280. dataType: 'json'
  6281. });
  6282. if (result === 'Success') {
  6283. if (data?.status === 200) {
  6284. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6285. logStatus.warning(i18n('changeAreaNotice'));
  6286. const result = await this.#changeArea();
  6287. if (!result || [ 'CN', 'skip' ].includes(result)) {
  6288. return false;
  6289. }
  6290. return await this.#addFreeLicense(id);
  6291. }
  6292. logStatus.success();
  6293. return true;
  6294. }
  6295. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6296. return false;
  6297. }
  6298. logStatus.error(`${result}:${statusText}(${status})`);
  6299. return false;
  6300. } catch (error) {
  6301. throwError(error, 'Steam.addFreeLicense');
  6302. return false;
  6303. }
  6304. }
  6305. async #requestPlayTestAccess(id) {
  6306. try {
  6307. if (this.#ASF) {
  6308. return await this.#ASF.requestPlayTestAccess(id);
  6309. }
  6310. const logStatus = scripts_echoLog({
  6311. type: 'requestingPlayTestAccess',
  6312. text: id
  6313. });
  6314. const {
  6315. result,
  6316. statusText,
  6317. status,
  6318. data
  6319. } = await tools_httpRequest({
  6320. url: `https://store.steampowered.com/ajaxrequestplaytestaccess/${id}`,
  6321. method: 'POST',
  6322. headers: {
  6323. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6324. Host: 'store.steampowered.com',
  6325. Origin: 'https://store.steampowered.com',
  6326. Referer: `https://store.steampowered.com/app/${id}`
  6327. },
  6328. data: $.param({
  6329. sessionid: this.#auth.storeSessionID
  6330. }),
  6331. dataType: 'json'
  6332. });
  6333. if (result === 'Success') {
  6334. if (data?.status === 200 && data?.response?.success === 1) {
  6335. logStatus.success();
  6336. return true;
  6337. }
  6338. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6339. return false;
  6340. }
  6341. logStatus.error(`${result}:${statusText}(${status})`);
  6342. return false;
  6343. } catch (error) {
  6344. throwError(error, 'Steam.requestPlayTestAccess');
  6345. return false;
  6346. }
  6347. }
  6348. async toggle({
  6349. doTask = true,
  6350. groupLinks = [],
  6351. officialGroupLinks = [],
  6352. wishlistLinks = [],
  6353. followLinks = [],
  6354. forumLinks = [],
  6355. workshopLinks = [],
  6356. workshopVoteLinks = [],
  6357. curatorLinks = [],
  6358. curatorLikeLinks = [],
  6359. announcementLinks = [],
  6360. licenseLinks = [],
  6361. playtestLinks = []
  6362. }) {
  6363. try {
  6364. if ([ ...groupLinks, ...officialGroupLinks, ...forumLinks, ...workshopLinks, ...workshopVoteLinks ].length > 0 && !this.#communityInitialized) {
  6365. scripts_echoLog({
  6366. text: i18n('needInit')
  6367. });
  6368. return false;
  6369. }
  6370. if ([ ...wishlistLinks, ...followLinks, ...curatorLinks, ...curatorLikeLinks, ...announcementLinks, ...licenseLinks, ...playtestLinks ].length > 0 && !this.#storeInitialized) {
  6371. scripts_echoLog({
  6372. text: i18n('needInit')
  6373. });
  6374. return false;
  6375. }
  6376. const prom = [];
  6377. if (doTask && !globalOptions.doTask.steam.groups || !doTask && !globalOptions.undoTask.steam.groups) {
  6378. scripts_echoLog({
  6379. type: 'globalOptionsSkip',
  6380. text: 'steam.groups'
  6381. });
  6382. } else {
  6383. const realGroups = this.getRealParams('groups', groupLinks, doTask, link => link.match(/groups\/(.+)\/?/)?.[1]);
  6384. if (realGroups.length > 0) {
  6385. for (const group of realGroups) {
  6386. if (doTask) {
  6387. prom.push(this.#joinGroup(group));
  6388. } else {
  6389. prom.push(this.#leaveGroup(group));
  6390. }
  6391. await delay(1e3);
  6392. }
  6393. }
  6394. }
  6395. if (doTask && !globalOptions.doTask.steam.officialGroups || !doTask && !globalOptions.undoTask.steam.officialGroups) {
  6396. scripts_echoLog({
  6397. type: 'globalOptionsSkip',
  6398. text: 'steam.officialGroups'
  6399. });
  6400. } else {
  6401. const realOfficialGroups = this.getRealParams('officialGroups', officialGroupLinks, doTask, link => link.match(/games\/(.+)\/?/)?.[1]);
  6402. if (realOfficialGroups.length > 0) {
  6403. for (const officialGroup of realOfficialGroups) {
  6404. if (doTask) {
  6405. prom.push(this.#joinOfficialGroup(officialGroup));
  6406. } else {
  6407. prom.push(this.#leaveOfficialGroup(officialGroup));
  6408. }
  6409. await delay(1e3);
  6410. }
  6411. }
  6412. }
  6413. if (doTask && !globalOptions.doTask.steam.wishlists || !doTask && !globalOptions.undoTask.steam.wishlists) {
  6414. scripts_echoLog({
  6415. type: 'globalOptionsSkip',
  6416. text: 'steam.wishlists'
  6417. });
  6418. } else {
  6419. const realWishlists = this.getRealParams('wishlists', wishlistLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6420. if (realWishlists.length > 0) {
  6421. for (const game of realWishlists) {
  6422. if (doTask) {
  6423. prom.push(this.#addToWishlist(game));
  6424. } else {
  6425. prom.push(this.#removeFromWishlist(game));
  6426. }
  6427. await delay(1e3);
  6428. }
  6429. }
  6430. }
  6431. if (doTask && !globalOptions.doTask.steam.follows || !doTask && !globalOptions.undoTask.steam.follows) {
  6432. scripts_echoLog({
  6433. type: 'globalOptionsSkip',
  6434. text: 'steam.follows'
  6435. });
  6436. } else {
  6437. const realFollows = this.getRealParams('follows', followLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6438. if (realFollows.length > 0) {
  6439. for (const game of realFollows) {
  6440. prom.push(this.#toggleFollowGame(game, doTask));
  6441. await delay(1e3);
  6442. }
  6443. }
  6444. }
  6445. if (doTask && !globalOptions.doTask.steam.forums || !doTask && !globalOptions.undoTask.steam.forums) {
  6446. scripts_echoLog({
  6447. type: 'globalOptionsSkip',
  6448. text: 'steam.forums'
  6449. });
  6450. } else {
  6451. const realForums = this.getRealParams('forums', forumLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6452. if (realForums.length > 0) {
  6453. for (const forum of realForums) {
  6454. prom.push(this.#toggleForum(forum, doTask));
  6455. await delay(1e3);
  6456. }
  6457. }
  6458. }
  6459. if (doTask && !globalOptions.doTask.steam.workshops || !doTask && !globalOptions.undoTask.steam.workshops) {
  6460. scripts_echoLog({
  6461. type: 'globalOptionsSkip',
  6462. text: 'steam.workshops'
  6463. });
  6464. } else {
  6465. const realWorkshops = this.getRealParams('workshops', workshopLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  6466. if (realWorkshops.length > 0) {
  6467. for (const workshop of realWorkshops) {
  6468. prom.push(this.#toggleFavoriteWorkshop(workshop, doTask));
  6469. await delay(1e3);
  6470. }
  6471. }
  6472. }
  6473. if (doTask && !globalOptions.doTask.steam.workshopVotes) {
  6474. scripts_echoLog({
  6475. type: 'globalOptionsSkip',
  6476. text: 'steam.workshopVotes'
  6477. });
  6478. } else {
  6479. const realworkshopVotes = this.getRealParams('workshopVotes', workshopVoteLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  6480. if (doTask && realworkshopVotes.length > 0) {
  6481. for (const workshop of realworkshopVotes) {
  6482. prom.push(this.#voteUpWorkshop(workshop));
  6483. await delay(1e3);
  6484. }
  6485. }
  6486. }
  6487. if (doTask && !globalOptions.doTask.steam.curators || !doTask && !globalOptions.undoTask.steam.curators) {
  6488. scripts_echoLog({
  6489. type: 'globalOptionsSkip',
  6490. text: 'steam.curators'
  6491. });
  6492. } else {
  6493. const realCurators = this.getRealParams('curators', curatorLinks, doTask, link => link.match(/curator\/([\d]+)/)?.[1]);
  6494. const realCuratorLikes = this.getRealParams('curatorLikes', curatorLikeLinks, doTask, link => link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3).join('/'));
  6495. if (realCurators.length > 0) {
  6496. for (const curator of realCurators) {
  6497. prom.push(this.#toggleCurator(curator, doTask));
  6498. await delay(1e3);
  6499. }
  6500. }
  6501. if (realCuratorLikes.length > 0) {
  6502. for (const curatorLike of realCuratorLikes) {
  6503. prom.push(this.#toggleCuratorLike(curatorLike, doTask));
  6504. await delay(1e3);
  6505. }
  6506. }
  6507. }
  6508. if (doTask && !globalOptions.doTask.steam.announcements) {
  6509. scripts_echoLog({
  6510. type: 'globalOptionsSkip',
  6511. text: 'steam.announcements'
  6512. });
  6513. } else {
  6514. const realAnnouncements = this.getRealParams('announcements', announcementLinks, doTask, link => {
  6515. if (link.includes('store.steampowered.com')) {
  6516. return link.match(/store\.steampowered\.com\/news\/app\/([\d]+)\/view\/([\d]+)/)?.slice(1, 3).join('/');
  6517. }
  6518. return link.match(/steamcommunity\.com\/games\/([\d]+)\/announcements\/detail\/([\d]+)/)?.slice(1, 3).join('/');
  6519. });
  6520. if (doTask && realAnnouncements.length > 0) {
  6521. for (const id of realAnnouncements) {
  6522. prom.push(this.#likeAnnouncement(id));
  6523. await delay(1e3);
  6524. }
  6525. }
  6526. }
  6527. if (doTask && !globalOptions.doTask.steam.licenses) {
  6528. scripts_echoLog({
  6529. type: 'globalOptionsSkip',
  6530. text: 'steam.licenses'
  6531. });
  6532. } else if (doTask && globalOptions.doTask.steam.licenses && licenseLinks.length > 0) {
  6533. for (const ids of licenseLinks) {
  6534. const [ type, idsStr ] = ids.split('-');
  6535. const idsArr = idsStr.split(',');
  6536. for (const id of idsArr) {
  6537. prom.push(this.#addLicense(`${type}-${id}`));
  6538. await delay(1e3);
  6539. }
  6540. }
  6541. }
  6542. if (doTask && !globalOptions.doTask.steam.playtests) {
  6543. scripts_echoLog({
  6544. type: 'globalOptionsSkip',
  6545. text: 'steam.playtests'
  6546. });
  6547. } else {
  6548. const realPlaytests = this.getRealParams('playtests', playtestLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6549. if (doTask && globalOptions.doTask.steam.playtests && realPlaytests.length > 0) {
  6550. for (const id of realPlaytests) {
  6551. prom.push(this.#requestPlayTestAccess(id));
  6552. await delay(1e3);
  6553. }
  6554. }
  6555. }
  6556. return Promise.all(prom).then(async () => {
  6557. if (this.#oldArea && this.#area !== this.#oldArea) {
  6558. scripts_echoLog({}).warning(i18n('steamFinishNotice') + this.#oldArea);
  6559. await this.#changeArea(this.#oldArea);
  6560. }
  6561. return true;
  6562. });
  6563. } catch (error) {
  6564. throwError(error, 'Steam.toggle');
  6565. return false;
  6566. }
  6567. }
  6568. #setCache(type, name, id) {
  6569. try {
  6570. this.#cache[type][name] = id;
  6571. GM_setValue('steamCache', this.#cache);
  6572. } catch (error) {
  6573. throwError(error, 'Steam.setCache');
  6574. }
  6575. }
  6576. }
  6577. const social_Steam = Steam;
  6578. class Website {
  6579. undoneTasks;
  6580. socialTasks;
  6581. giveawayId;
  6582. socialInitialized = {
  6583. discord: false,
  6584. instagram: false,
  6585. reddit: false,
  6586. twitch: false,
  6587. twitter: false,
  6588. vk: false,
  6589. youtube: false,
  6590. steamStore: false,
  6591. steamCommunity: false
  6592. };
  6593. initialized = false;
  6594. social = {};
  6595. async #bind(name, init) {
  6596. try {
  6597. return {
  6598. name: name,
  6599. result: await init
  6600. };
  6601. } catch (error) {
  6602. throwError(error, 'Website.bind');
  6603. return {
  6604. name: name,
  6605. result: false
  6606. };
  6607. }
  6608. }
  6609. async initSocial(action) {
  6610. try {
  6611. const pro = [];
  6612. const tasks = action === 'do' ? this.undoneTasks : this.socialTasks;
  6613. if (tasks.discord) {
  6614. const hasDiscord = Object.values(tasks.discord).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6615. if (hasDiscord && (!this.socialInitialized.discord || !this.social.discord)) {
  6616. this.social.discord = new social_Discord();
  6617. pro.push(this.#bind('discord', this.social.discord.init(action)));
  6618. }
  6619. }
  6620. if (tasks.instagram) {
  6621. const hasInstagram = Object.values(tasks.instagram).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6622. if (hasInstagram && (!this.socialInitialized.instagram || !this.social.instagram)) {
  6623. this.social.instagram = new social_Instagram();
  6624. pro.push(this.#bind('instagram', this.social.instagram.init()));
  6625. }
  6626. }
  6627. if (tasks.reddit) {
  6628. const hasReddit = Object.values(tasks.reddit).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6629. if (hasReddit && (!this.socialInitialized.reddit || !this.social.reddit)) {
  6630. this.social.reddit = new social_Reddit();
  6631. pro.push(this.#bind('reddit', this.social.reddit.init()));
  6632. }
  6633. }
  6634. if (tasks.twitch) {
  6635. const hasTwitch = Object.values(tasks.twitch).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6636. if (hasTwitch && (!this.socialInitialized.twitch || !this.social.twitch)) {
  6637. this.social.twitch = new social_Twitch();
  6638. pro.push(this.#bind('twitch', this.social.twitch.init()));
  6639. }
  6640. }
  6641. if (tasks.twitter) {
  6642. const hasTwitter = Object.values(tasks.twitter).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6643. if (hasTwitter && (!this.socialInitialized.twitter || !this.social.twitter)) {
  6644. this.social.twitter = new social_Twitter();
  6645. pro.push(this.#bind('twitter', this.social.twitter.init()));
  6646. }
  6647. }
  6648. if (tasks.vk) {
  6649. const hasVk = Object.values(tasks.vk).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6650. if (hasVk && (!this.socialInitialized.vk || !this.social.vk)) {
  6651. this.social.vk = new social_Vk();
  6652. pro.push(this.#bind('vk', this.social.vk.init()));
  6653. }
  6654. }
  6655. if (tasks.youtube) {
  6656. const hasYoutube = Object.values(tasks.youtube).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6657. if (hasYoutube && (!this.socialInitialized.youtube || !this.social.youtube)) {
  6658. this.social.youtube = new Youtube();
  6659. pro.push(this.#bind('youtube', this.social.youtube.init()));
  6660. }
  6661. }
  6662. if (tasks.steam) {
  6663. const steamLength = Object.values(tasks.steam).reduce((total, arr) => [ ...total, ...arr ]).length;
  6664. if (steamLength > 0) {
  6665. if (!this.social.steam) {
  6666. this.social.steam = new social_Steam();
  6667. }
  6668. 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);
  6669. if (steamLength - steamCommunityLength > 0 && !this.socialInitialized.steamStore) {
  6670. pro.push(this.#bind('steamStore', this.social.steam.init('store')));
  6671. }
  6672. if (steamCommunityLength > 0 && !this.socialInitialized.steamCommunity) {
  6673. pro.push(this.#bind('steamCommunity', this.social.steam.init('community')));
  6674. }
  6675. }
  6676. }
  6677. if (tasks.links && tasks.links.length > 0) {
  6678. this.social.visitLink = visitLink;
  6679. }
  6680. return await Promise.all(pro).then(result => {
  6681. let checked = true;
  6682. for (const data of result) {
  6683. if (data.result) {
  6684. this.socialInitialized[data.name] = data.result;
  6685. } else {
  6686. checked = false;
  6687. }
  6688. }
  6689. return checked;
  6690. });
  6691. } catch (error) {
  6692. throwError(error, 'Website.initSocial');
  6693. return false;
  6694. }
  6695. }
  6696. uniqueTasks(allTasks) {
  6697. try {
  6698. const result = {};
  6699. for (const [ social, types ] of Object.entries(allTasks)) {
  6700. result[social] = {};
  6701. for (const [ type, tasks ] of Object.entries(types)) {
  6702. result[social][type] = unique(tasks);
  6703. }
  6704. }
  6705. return result;
  6706. } catch (error) {
  6707. throwError(error, 'Website.uniqueTasks');
  6708. return allTasks;
  6709. }
  6710. }
  6711. async toggleTask(action) {
  6712. try {
  6713. if (!this.initialized && !this.init()) {
  6714. return false;
  6715. }
  6716. if (!await this.classifyTask(action)) {
  6717. return false;
  6718. }
  6719. if (!await this.initSocial(action)) {
  6720. return false;
  6721. }
  6722. const pro = [];
  6723. const doTask = action === 'do';
  6724. const tasks = doTask ? this.undoneTasks : this.socialTasks;
  6725. if (this.socialInitialized.discord !== 'skip' && this.social.discord) {
  6726. pro.push(this.social.discord.toggle({
  6727. doTask: doTask,
  6728. ...tasks.discord
  6729. }));
  6730. }
  6731. if (this.social.instagram) {
  6732. pro.push(this.social.instagram.toggle({
  6733. doTask: doTask,
  6734. ...tasks.instagram
  6735. }));
  6736. }
  6737. if (this.social.reddit) {
  6738. pro.push(this.social.reddit.toggle({
  6739. doTask: doTask,
  6740. ...tasks.reddit
  6741. }));
  6742. }
  6743. if (this.social.twitch) {
  6744. pro.push(this.social.twitch.toggle({
  6745. doTask: doTask,
  6746. ...tasks.twitch
  6747. }));
  6748. }
  6749. if (this.social.twitter) {
  6750. pro.push(this.social.twitter.toggle({
  6751. doTask: doTask,
  6752. ...tasks.twitter
  6753. }));
  6754. }
  6755. if (this.social.vk) {
  6756. pro.push(this.social.vk.toggle({
  6757. doTask: doTask,
  6758. ...tasks.vk
  6759. }));
  6760. }
  6761. if (this.social.youtube) {
  6762. pro.push(this.social.youtube.toggle({
  6763. doTask: doTask,
  6764. ...tasks.youtube
  6765. }));
  6766. }
  6767. if (this.social.steam) {
  6768. pro.push(this.social.steam.toggle({
  6769. doTask: doTask,
  6770. ...tasks.steam
  6771. }));
  6772. }
  6773. if (this.social.visitLink && tasks.links && doTask) {
  6774. for (const link of tasks.links) {
  6775. pro.push(this.social.visitLink(link));
  6776. }
  6777. }
  6778. if (doTask && tasks.extra && this.extraDoTask) {
  6779. const hasExtra = Object.values(tasks.extra).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6780. if (hasExtra) {
  6781. pro.push(this.extraDoTask(tasks.extra));
  6782. }
  6783. }
  6784. await Promise.all(pro);
  6785. scripts_echoLog({}).success(i18n('allTasksComplete'));
  6786. return true;
  6787. } catch (error) {
  6788. throwError(error, 'Website.toggleTask');
  6789. return false;
  6790. }
  6791. }
  6792. async doTask() {
  6793. try {
  6794. return await this.toggleTask('do');
  6795. } catch (error) {
  6796. throwError(error, 'Website.doTask');
  6797. return false;
  6798. }
  6799. }
  6800. async undoTask() {
  6801. try {
  6802. return await this.toggleTask('undo');
  6803. } catch (error) {
  6804. throwError(error, 'Website.undoTask');
  6805. return false;
  6806. }
  6807. }
  6808. }
  6809. const website_Website = Website;
  6810. const defaultTasksTemplate = {
  6811. steam: {
  6812. groupLinks: [],
  6813. wishlistLinks: [],
  6814. curatorLinks: [],
  6815. followLinks: []
  6816. },
  6817. vk: {
  6818. nameLinks: []
  6819. }
  6820. };
  6821. const defaultTasks = JSON.stringify(defaultTasksTemplate);
  6822. class FreeAnyWhere extends website_Website {
  6823. name = 'FreeAnyWhere';
  6824. tasks = [];
  6825. socialTasks = JSON.parse(defaultTasks);
  6826. undoneTasks = JSON.parse(defaultTasks);
  6827. buttons = [ 'doTask', 'undoTask', 'verifyTask', 'getKey' ];
  6828. static test() {
  6829. return window.location.host === 'freeanywhere.net';
  6830. }
  6831. async init() {
  6832. try {
  6833. const logStatus = scripts_echoLog({
  6834. text: i18n('initing')
  6835. });
  6836. if ($('a[href="#/login"]').length > 0) {
  6837. window.open('/#/login', '_self');
  6838. logStatus.warning(i18n('needLogin'));
  6839. return false;
  6840. }
  6841. if (window.location.href.includes('/login')) {
  6842. logStatus.warning(i18n('needLogin'));
  6843. return false;
  6844. }
  6845. if (!/^https?:\/\/freeanywhere\.net\/#\/giveaway\/[\d]+/.test(window.location.href)) {
  6846. const id = window.location.href.match(/https?:\/\/freeanywhere\.net\/.*?#\/giveaway\/([\d]+)/)?.[1];
  6847. if (!id) {
  6848. logStatus.error(i18n('getFailed', 'Id'));
  6849. return false;
  6850. }
  6851. window.location.href = `https://freeanywhere.net/#/giveaway/${id}`;
  6852. }
  6853. if (!this.#getGiveawayId()) {
  6854. return false;
  6855. }
  6856. if (!await this.#checkLeftKey()) {
  6857. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  6858. }
  6859. this.initialized = true;
  6860. logStatus.success();
  6861. return true;
  6862. } catch (error) {
  6863. throwError(error, 'Freeanywhere.init');
  6864. return false;
  6865. }
  6866. }
  6867. async classifyTask(action) {
  6868. try {
  6869. const logStatus = scripts_echoLog({
  6870. text: i18n('getTasksInfo')
  6871. });
  6872. if (action === 'undo') {
  6873. this.socialTasks = GM_getValue(`fawTasks-${this.giveawayId}`)?.tasks || JSON.parse(defaultTasks);
  6874. }
  6875. const {
  6876. result,
  6877. statusText,
  6878. status,
  6879. data
  6880. } = await tools_httpRequest({
  6881. url: `https://freeanywhere.net/api/v1/giveaway/${this.giveawayId}/?format=json`,
  6882. method: 'GET',
  6883. headers: {
  6884. authorization: `Token ${window.localStorage.getItem('token')}`,
  6885. 'x-csrftoken': external_Cookies_default().get('csrftoken')
  6886. },
  6887. responseType: 'json'
  6888. });
  6889. if (result === 'Success') {
  6890. const tasks = data?.response?.challenges;
  6891. if (tasks) {
  6892. if (action === 'verify') {
  6893. this.tasks = [];
  6894. }
  6895. for (const task of tasks) {
  6896. const type = task.challenge;
  6897. const social = task.challenge_provider;
  6898. const taskInfo = {
  6899. id: task.id,
  6900. title: task.title
  6901. };
  6902. if (action === 'verify' && !task.is_success) {
  6903. this.tasks.push(taskInfo);
  6904. continue;
  6905. }
  6906. switch (social) {
  6907. case 'steam':
  6908. taskInfo.social = 'steam';
  6909. switch (type) {
  6910. case 'WL':
  6911. if (action === 'undo') {
  6912. this.socialTasks.steam.wishlistLinks.push(task.link);
  6913. }
  6914. if (action === 'do' && !task.is_success) {
  6915. this.undoneTasks.steam.wishlistLinks.push(task.link);
  6916. }
  6917. break;
  6918.  
  6919. case 'JTG':
  6920. if (action === 'undo') {
  6921. this.socialTasks.steam.groupLinks.push(task.link);
  6922. }
  6923. if (action === 'do' && !task.is_success) {
  6924. this.undoneTasks.steam.groupLinks.push(task.link);
  6925. }
  6926. break;
  6927.  
  6928. case 'STC':
  6929. if (action === 'undo') {
  6930. this.socialTasks.steam.curatorLinks.push(task.link);
  6931. }
  6932. if (action === 'do' && !task.is_success) {
  6933. this.undoneTasks.steam.curatorLinks.push(task.link);
  6934. }
  6935. break;
  6936.  
  6937. case 'GF':
  6938. if (action === 'undo') {
  6939. this.socialTasks.steam.followLinks.push(task.link);
  6940. }
  6941. if (action === 'do' && !task.is_success) {
  6942. this.undoneTasks.steam.followLinks.push(task.link);
  6943. }
  6944. break;
  6945. }
  6946. break;
  6947.  
  6948. case 'vk-oauth2':
  6949. if (action === 'undo') {
  6950. this.socialTasks.vk.nameLinks.push(task.link);
  6951. }
  6952. if (action === 'do' && !task.is_success) {
  6953. this.undoneTasks.vk.nameLinks.push(task.link);
  6954. }
  6955. break;
  6956.  
  6957. case 'website':
  6958. break;
  6959.  
  6960. default:
  6961. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${social}`);
  6962. break;
  6963. }
  6964. }
  6965. logStatus.success();
  6966. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  6967. this.socialTasks = this.uniqueTasks(this.socialTasks);
  6968. if (window.DEBUG) {
  6969. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  6970. }
  6971. GM_setValue(`fawTasks-${this.giveawayId}`, {
  6972. tasks: this.socialTasks,
  6973. time: new Date().getTime()
  6974. });
  6975. return true;
  6976. }
  6977. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6978. return false;
  6979. }
  6980. logStatus.error(`${result}:${statusText}(${status})`);
  6981. return false;
  6982. } catch (error) {
  6983. throwError(error, 'Freeanywhere.classifyTask');
  6984. return false;
  6985. }
  6986. }
  6987. async verifyTask() {
  6988. try {
  6989. if (!this.initialized && !this.init()) {
  6990. return false;
  6991. }
  6992. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  6993. return false;
  6994. }
  6995. const pro = [];
  6996. for (const task of this.tasks) {
  6997. pro.push(this.#verify(task));
  6998. await delay(1e3);
  6999. }
  7000. await Promise.all(pro);
  7001. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7002. return !!await this.getKey(true);
  7003. } catch (error) {
  7004. throwError(error, 'Freeanywhere.verifyTask');
  7005. return false;
  7006. }
  7007. }
  7008. async getKey(initialized) {
  7009. try {
  7010. if (!initialized && !this.initialized && !this.init()) {
  7011. return false;
  7012. }
  7013. const logStatus = scripts_echoLog({
  7014. text: i18n('gettingKey')
  7015. });
  7016. const {
  7017. result,
  7018. statusText,
  7019. status,
  7020. data
  7021. } = await tools_httpRequest({
  7022. url: `https://freeanywhere.net/api/v1/giveaway/${this.giveawayId}/reward/?format=json`,
  7023. method: 'GET',
  7024. dataType: 'json',
  7025. headers: {
  7026. authorization: `Token ${window.localStorage.getItem('token')}`
  7027. }
  7028. });
  7029. if (result === 'Success') {
  7030. if (data?.response?.reward) {
  7031. logStatus.success();
  7032. scripts_echoLog({}).success(data.response.reward);
  7033. return data.response.reward;
  7034. }
  7035. if (data?.response?.completed === false) {
  7036. logStatus.error(i18n('tasksNotCompleted'));
  7037. return false;
  7038. }
  7039. if (data?.response?.completed === true) {
  7040. await this.#checkLeftKey();
  7041. }
  7042. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7043. return false;
  7044. }
  7045. logStatus.error(`${result}:${statusText}(${status})`);
  7046. return false;
  7047. } catch (error) {
  7048. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7049. return false;
  7050. }
  7051. }
  7052. #getGiveawayId() {
  7053. try {
  7054. const giveawayId = window.location.href.match(/\/giveaway\/([\d]+)/)?.[1];
  7055. if (giveawayId) {
  7056. this.giveawayId = giveawayId;
  7057. return true;
  7058. }
  7059. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  7060. return false;
  7061. } catch (error) {
  7062. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7063. return false;
  7064. }
  7065. }
  7066. async #verify(task) {
  7067. try {
  7068. const logStatus = scripts_echoLog({
  7069. html: `<li>${i18n('verifyingTask')}${task.title.trim()}...<font></font></li>`
  7070. });
  7071. const {
  7072. result,
  7073. statusText,
  7074. status,
  7075. data
  7076. } = await tools_httpRequest({
  7077. url: `https://freeanywhere.net/api/v1/giveaway/${this.giveawayId}/challenge-status/${task.id}/?format=json`,
  7078. method: 'GET',
  7079. dataType: 'json',
  7080. headers: {
  7081. authorization: `Token ${window.localStorage.getItem('token')}`,
  7082. 'x-csrftoken': external_Cookies_default().get('csrftoken')
  7083. }
  7084. });
  7085. if (result === 'Success') {
  7086. if (data?.response?.status) {
  7087. logStatus.success();
  7088. return true;
  7089. }
  7090. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7091. return false;
  7092. }
  7093. logStatus.error(`${result}:${statusText}(${status})`);
  7094. return false;
  7095. } catch (error) {
  7096. throwError(error, 'Freeanywhere.verify');
  7097. return false;
  7098. }
  7099. }
  7100. async #checkLeftKey() {
  7101. try {
  7102. if (!globalOptions.other.checkLeftKey) {
  7103. return true;
  7104. }
  7105. const {
  7106. data
  7107. } = await tools_httpRequest({
  7108. url: 'https://freeanywhere.net/api/v1/widget/?format=json',
  7109. method: 'GET',
  7110. dataType: 'json',
  7111. headers: {
  7112. authorization: `Token ${window.localStorage.getItem('token')}`
  7113. }
  7114. });
  7115. if (data?.response?.giveaways.find(giveaway => `${giveaway?.id}` === this.giveawayId)) {
  7116. return true;
  7117. }
  7118. await external_Swal_default().fire({
  7119. icon: 'warning',
  7120. title: i18n('notice'),
  7121. text: i18n('noKeysLeft'),
  7122. confirmButtonText: i18n('confirm'),
  7123. cancelButtonText: i18n('cancel'),
  7124. showCancelButton: true
  7125. }).then(({
  7126. value
  7127. }) => {
  7128. if (value) {
  7129. window.close();
  7130. }
  7131. });
  7132. return true;
  7133. } catch (error) {
  7134. throwError(error, 'Giveawaysu.checkLeftKey');
  7135. return false;
  7136. }
  7137. }
  7138. }
  7139. const Freeanywhere = FreeAnyWhere;
  7140. const Giveawaysu_defaultTasks = {
  7141. steam: {
  7142. groupLinks: [],
  7143. wishlistLinks: [],
  7144. curatorLinks: [],
  7145. curatorLikeLinks: [],
  7146. followLinks: [],
  7147. forumLinks: [],
  7148. announcementLinks: [],
  7149. workshopVoteLinks: [],
  7150. playtestLinks: []
  7151. },
  7152. discord: {
  7153. serverLinks: []
  7154. },
  7155. instagram: {
  7156. userLinks: []
  7157. },
  7158. vk: {
  7159. nameLinks: []
  7160. },
  7161. twitch: {
  7162. channelLinks: []
  7163. },
  7164. reddit: {
  7165. redditLinks: []
  7166. },
  7167. youtube: {
  7168. channelLinks: [],
  7169. likeLinks: []
  7170. },
  7171. twitter: {
  7172. userLinks: [],
  7173. retweetLinks: []
  7174. }
  7175. };
  7176. class GiveawaySu extends website_Website {
  7177. name = 'GiveawaySu';
  7178. socialTasks = Giveawaysu_defaultTasks;
  7179. undoneTasks = Giveawaysu_defaultTasks;
  7180. buttons = [ 'doTask', 'undoTask' ];
  7181. static test() {
  7182. return /^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(window.location.href);
  7183. }
  7184. async after() {
  7185. try {
  7186. if (!this.#checkLogin()) {
  7187. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7188. }
  7189. if (!await this.#checkLeftKey()) {
  7190. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7191. }
  7192. scripts_echoLog({}).warning(i18n('gsNotice'));
  7193. } catch (error) {
  7194. throwError(error, 'Giveawaysu.after');
  7195. }
  7196. }
  7197. init() {
  7198. try {
  7199. const logStatus = scripts_echoLog({
  7200. text: i18n('initing')
  7201. });
  7202. if ($('a.steam-login').length > 0) {
  7203. window.open('/steam/redirect', '_self');
  7204. logStatus.warning(i18n('needLogin'));
  7205. return false;
  7206. }
  7207. if (!this.#getGiveawayId()) {
  7208. return false;
  7209. }
  7210. this.initialized = true;
  7211. logStatus.success();
  7212. return true;
  7213. } catch (error) {
  7214. throwError(error, 'Giveawaysu.init');
  7215. return false;
  7216. }
  7217. }
  7218. async classifyTask(action) {
  7219. try {
  7220. const logStatus = scripts_echoLog({
  7221. text: i18n('getTasksInfo')
  7222. });
  7223. if (action === 'undo') {
  7224. this.socialTasks = GM_getValue(`gasTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  7225. return true;
  7226. }
  7227. const pro = [];
  7228. const tasks = $('#actions tr');
  7229. if ($('div.bind-discord').is(':visible')) {
  7230. $('div.bind-discord a')[0].click();
  7231. }
  7232. if ($('div.bind-twitch').is(':visible')) {
  7233. $('div.bind-twitch a')[0].click();
  7234. }
  7235. for (const task of tasks) {
  7236. pro.push(new Promise(resolve => {
  7237. const td = $(task).find('td:not(".hidden")');
  7238. const colorfulTask = td.eq(1).find('a:not([data-trigger="link"])');
  7239. const colorlessTask = td.eq(2).find('a:not([data-trigger="link"])');
  7240. const taskDes = colorfulTask.length > 0 ? colorfulTask : colorlessTask;
  7241. const taskIcon = td.eq(0).find('i').attr('class') || '';
  7242. const taskName = taskDes.text().trim();
  7243. if (taskIcon.includes('ban') || /disable adblock/gi.test(taskName)) {
  7244. return resolve(true);
  7245. }
  7246. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  7247. if (!taskLink) {
  7248. return resolve(false);
  7249. }
  7250. if (taskIcon.includes('steam') && /join/gi.test(taskName)) {
  7251. this.undoneTasks.steam.groupLinks.push(taskLink);
  7252. } else if (/like.*announcement/gi.test(taskName)) {
  7253. this.undoneTasks.steam.announcementLinks.push(taskLink);
  7254. } else if (/(follow|subscribe).*curator/gim.test(taskName) && /^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  7255. this.undoneTasks.steam.curatorLinks.push(taskLink);
  7256. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  7257. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  7258. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  7259. this.undoneTasks.steam.forumLinks.push(taskLink);
  7260. } else if (taskIcon.includes('thumbs-up') && /^https?:\/\/steamcommunity\.com\/sharedfiles\/filedetails\/\?id=[\d]+/.test(taskLink)) {
  7261. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7262. } else if (taskIcon.includes('plus') && /request.*playtest/gim.test(taskName)) {
  7263. this.undoneTasks.steam.playtestLinks.push(taskLink);
  7264. } else if (taskIcon.includes('discord') || /join.*discord/gim.test(taskName)) {
  7265. this.undoneTasks.discord.serverLinks.push(taskLink);
  7266. } else if (taskIcon.includes('instagram') || /follow.*instagram/gim.test(taskName)) {
  7267. this.undoneTasks.instagram.userLinks.push(taskLink);
  7268. } else if (taskIcon.includes('twitch') || /follow.*twitch.*channel/gim.test(taskName)) {
  7269. this.undoneTasks.twitch.channelLinks.push(taskLink);
  7270. } else if (taskIcon.includes('reddit') || /subscribe.*subreddit/gim.test(taskName) || /follow.*reddit/gim.test(taskName)) {
  7271. this.undoneTasks.reddit.redditLinks.push(taskLink);
  7272. } else if (/watch.*art/gim.test(taskName)) {
  7273. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7274. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  7275. this.undoneTasks.youtube.channelLinks.push(taskLink);
  7276. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  7277. this.undoneTasks.youtube.likeLinks.push(taskLink);
  7278. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  7279. this.undoneTasks.vk.nameLinks.push(taskLink);
  7280. } else {
  7281. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  7282. if (/wishlist.*game|add.*wishlist/gim.test(taskName)) {
  7283. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  7284. }
  7285. if (/follow.*button/gim.test(taskName)) {
  7286. this.undoneTasks.steam.followLinks.push(taskLink);
  7287. }
  7288. }
  7289. }
  7290. resolve(true);
  7291. }).catch(error => {
  7292. throwError(error, 'Giveawaysu.classifyTask->getRedirectLink');
  7293. return false;
  7294. });
  7295. }));
  7296. }
  7297. await Promise.all(pro);
  7298. logStatus.success();
  7299. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7300. this.socialTasks = this.undoneTasks;
  7301. if (window.DEBUG) {
  7302. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7303. }
  7304. GM_setValue(`gasTasks-${this.giveawayId}`, {
  7305. tasks: this.socialTasks,
  7306. time: new Date().getTime()
  7307. });
  7308. return true;
  7309. } catch (error) {
  7310. throwError(error, 'Giveawaysu.classifyTask');
  7311. return false;
  7312. }
  7313. }
  7314. #checkLogin() {
  7315. try {
  7316. if (!globalOptions.other.checkLogin) {
  7317. return true;
  7318. }
  7319. if ($('a.steam-login').length > 0) {
  7320. window.open('/steam/redirect', '_self');
  7321. }
  7322. return true;
  7323. } catch (error) {
  7324. throwError(error, 'Giveawaysu.checkLogin');
  7325. return false;
  7326. }
  7327. }
  7328. async #checkLeftKey() {
  7329. try {
  7330. if (!globalOptions.other.checkLeftKey) {
  7331. return true;
  7332. }
  7333. if ($('.giveaway-ended').length > 0 && $('.giveaway-key').length === 0) {
  7334. await external_Swal_default().fire({
  7335. icon: 'warning',
  7336. title: i18n('notice'),
  7337. text: i18n('noKeysLeft'),
  7338. confirmButtonText: i18n('confirm'),
  7339. cancelButtonText: i18n('cancel'),
  7340. showCancelButton: true
  7341. }).then(({
  7342. value
  7343. }) => {
  7344. if (value) {
  7345. window.close();
  7346. }
  7347. });
  7348. }
  7349. return true;
  7350. } catch (error) {
  7351. throwError(error, 'Giveawaysu.checkLeftKey');
  7352. return false;
  7353. }
  7354. }
  7355. #getGiveawayId() {
  7356. try {
  7357. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  7358. if (giveawayId) {
  7359. this.giveawayId = giveawayId;
  7360. return true;
  7361. }
  7362. scripts_echoLog({
  7363. text: i18n('getFailed', 'GiveawayId')
  7364. });
  7365. return false;
  7366. } catch (error) {
  7367. throwError(error, 'Giveawaysu.getGiveawayId');
  7368. return false;
  7369. }
  7370. }
  7371. }
  7372. class Indiedb {
  7373. name = 'Indiedb';
  7374. buttons = [ 'doTask' ];
  7375. static test() {
  7376. return window.location.host === 'www.indiedb.com';
  7377. }
  7378. async after() {
  7379. try {
  7380. if (!this.#checkLogin()) {
  7381. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7382. }
  7383. if (!await this.#checkLeftKey()) {
  7384. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7385. }
  7386. } catch (error) {
  7387. throwError(error, 'Indiedb.after');
  7388. }
  7389. }
  7390. async doTask() {
  7391. try {
  7392. if (!await this.#join()) {
  7393. return false;
  7394. }
  7395. return await this.#do();
  7396. } catch (error) {
  7397. throwError(error, 'Indiedb.doTask');
  7398. return false;
  7399. }
  7400. }
  7401. async #join() {
  7402. try {
  7403. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7404. scripts_echoLog({}).error(i18n('needLogin'));
  7405. return false;
  7406. }
  7407. const currentoption = $('a.buttonenter.buttongiveaway');
  7408. if (/join giveaway/gim.test(currentoption.text())) {
  7409. const logStatus = scripts_echoLog({
  7410. text: `${i18n('joiningGiveaway')}...`
  7411. });
  7412. const {
  7413. result,
  7414. statusText,
  7415. status,
  7416. data
  7417. } = await tools_httpRequest({
  7418. url: currentoption.attr('href'),
  7419. method: 'POST',
  7420. data: 'ajax=t',
  7421. dataType: 'json',
  7422. headers: {
  7423. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  7424. Accept: 'application/json, text/javascript, */*; q=0.01',
  7425. Origin: window.location.origin,
  7426. referer: window.location.href
  7427. }
  7428. });
  7429. if (result === 'Success') {
  7430. if (data?.status === 200) {
  7431. if (data.response?.success) {
  7432. currentoption.addClass('buttonentered').text('Success - Giveaway joined');
  7433. $('#giveawaysjoined').slideDown();
  7434. $('#giveawaysrecommend').slideDown();
  7435. logStatus.success(`Success${data.response?.text ? `:${data.response?.text}` : ''}`);
  7436. return true;
  7437. }
  7438. logStatus.error(`Error${data.response?.text ? `:${data.response?.text}` : ''}`);
  7439. return false;
  7440. }
  7441. if (await this.#join2()) {
  7442. logStatus.success('Success');
  7443. return true;
  7444. }
  7445. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7446. return false;
  7447. }
  7448. logStatus.error(`${result}:${statusText}(${status})`);
  7449. return false;
  7450. } else if (/success/gim.test($('a.buttonenter.buttongiveaway').text())) {
  7451. return true;
  7452. }
  7453. scripts_echoLog({}).warning(i18n('needJoinGiveaway'));
  7454. return false;
  7455. } catch (error) {
  7456. throwError(error, 'Indiedb.join');
  7457. return false;
  7458. }
  7459. }
  7460. async #join2() {
  7461. try {
  7462. return await new Promise(resolve => {
  7463. const targetNode = document.getElementById('giveawaysjoined');
  7464. const config = {
  7465. attributes: true
  7466. };
  7467. const observer = new MutationObserver(() => {
  7468. if ($('#giveawaysjoined').is(':visible')) {
  7469. resolve(true);
  7470. observer.disconnect();
  7471. }
  7472. });
  7473. observer.observe(targetNode, config);
  7474. $('a.buttonenter.buttongiveaway')[0]?.click();
  7475. setTimeout(() => {
  7476. resolve(false);
  7477. observer.disconnect();
  7478. }, 3e4);
  7479. });
  7480. } catch (error) {
  7481. throwError(error, 'Indiedb.join2');
  7482. return false;
  7483. }
  7484. }
  7485. async #do() {
  7486. try {
  7487. const id = $('script').map((index, script) => {
  7488. if (/\$\(document\)/gim.test(script.innerHTML)) {
  7489. return [ script.innerHTML.match(/"\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0], script.innerHTML.match(/"\/newsletter\/ajax\/subscribeprofile\/optin\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0] ];
  7490. }
  7491. return null;
  7492. });
  7493. if (id.length === 2) {
  7494. const pro = [];
  7495. const tasks = $('#giveawaysjoined a[class*=promo]');
  7496. for (const task of tasks) {
  7497. const promo = $(task);
  7498. if (!promo.hasClass('buttonentered')) {
  7499. const status = scripts_echoLog({
  7500. text: `${i18n('doing')}:${promo.parents('p').text()}...`
  7501. });
  7502. if (/facebookpromo|twitterpromo|visitpromo/gim.test(task.className)) {
  7503. let text = '';
  7504. if (promo.hasClass('facebookpromo')) {
  7505. text = 'facebookpromo';
  7506. } else if (promo.hasClass('twitterpromo')) {
  7507. text = 'twitterpromo';
  7508. } else {
  7509. text = 'visitpromo';
  7510. }
  7511. pro.push(new Promise(resolve => {
  7512. $.ajax({
  7513. type: 'POST',
  7514. url: urlPath(`/giveaways/ajax/${text}/${id[0]}`),
  7515. timeout: 6e4,
  7516. dataType: 'json',
  7517. data: {
  7518. ajax: 't'
  7519. },
  7520. error(response, error, exception) {
  7521. if (window.DEBUG) {
  7522. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7523. response: response,
  7524. error: error,
  7525. exception: exception
  7526. });
  7527. }
  7528. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7529. resolve(true);
  7530. },
  7531. success(response) {
  7532. if (response.success) {
  7533. status.success(`Success:${response.text}`);
  7534. promo.addClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7535. resolve(true);
  7536. } else {
  7537. status.error(`Error:${response.text}`);
  7538. resolve(true);
  7539. }
  7540. }
  7541. });
  7542. }));
  7543. } else if (promo.hasClass('emailoptinpromo')) {
  7544. pro.push(new Promise(resolve => {
  7545. $.ajax({
  7546. type: 'POST',
  7547. url: urlPath(`/newsletter/ajax/subscribeprofile/optin/${id[1]}`),
  7548. timeout: 6e4,
  7549. dataType: 'json',
  7550. data: {
  7551. ajax: 't',
  7552. emailsystoggle: 4
  7553. },
  7554. error(response, error, exception) {
  7555. if (window.DEBUG) {
  7556. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7557. response: response,
  7558. error: error,
  7559. exception: exception
  7560. });
  7561. }
  7562. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7563. resolve(true);
  7564. },
  7565. success(response) {
  7566. if (response.success) {
  7567. status.success(`Success:${response.text}`);
  7568. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7569. resolve(true);
  7570. } else {
  7571. status.error(`Error:${response.text}`);
  7572. resolve(true);
  7573. }
  7574. }
  7575. });
  7576. }));
  7577. } else if (promo.hasClass('watchingpromo')) {
  7578. pro.push(new Promise(resolve => {
  7579. const data = getUrlQuery(promo.attr('href'));
  7580. data.ajax = 't';
  7581. $.ajax({
  7582. type: 'POST',
  7583. url: urlPath(promo.attr('href')?.split(/[?#]/)[0]),
  7584. timeout: 6e4,
  7585. dataType: 'json',
  7586. data: data,
  7587. error(response, error, exception) {
  7588. if (window.DEBUG) {
  7589. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7590. response: response,
  7591. error: error,
  7592. exception: exception
  7593. });
  7594. }
  7595. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7596. resolve(true);
  7597. },
  7598. success(response) {
  7599. if (response.success) {
  7600. status.success(`Success:${response.text}`);
  7601. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7602. resolve(true);
  7603. } else {
  7604. status.error(`Error:${response.text}`);
  7605. resolve(true);
  7606. }
  7607. }
  7608. });
  7609. }));
  7610. } else if (!/the-challenge-of-adblock/gim.test(promo.attr('href'))) {
  7611. pro.push(new Promise(resolve => {
  7612. $.ajax({
  7613. type: 'POST',
  7614. url: urlPath(promo.attr('href')),
  7615. timeout: 6e4,
  7616. dataType: 'json',
  7617. data: {
  7618. ajax: 't'
  7619. },
  7620. error(response, error, exception) {
  7621. if (window.DEBUG) {
  7622. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7623. response: response,
  7624. error: error,
  7625. exception: exception
  7626. });
  7627. }
  7628. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7629. resolve(true);
  7630. },
  7631. success(response) {
  7632. if (response.success) {
  7633. status.success(`Success:${response.text}`);
  7634. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7635. resolve(true);
  7636. } else {
  7637. status.error(`Error:${response.text}`);
  7638. resolve(true);
  7639. }
  7640. }
  7641. });
  7642. }));
  7643. } else {
  7644. status.error(`Error:${i18n('unKnownTaskType')}`);
  7645. }
  7646. }
  7647. }
  7648. await Promise.all(pro);
  7649. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7650. return true;
  7651. }
  7652. scripts_echoLog({}).error(i18n('getFailed', 'TaskId'));
  7653. return false;
  7654. } catch (error) {
  7655. throwError(error, 'Indiedb.classifyTask');
  7656. return false;
  7657. }
  7658. }
  7659. #checkLogin() {
  7660. try {
  7661. if (!globalOptions.other.checkLogin) {
  7662. return true;
  7663. }
  7664. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7665. window.open('/members/login', '_self');
  7666. }
  7667. return true;
  7668. } catch (error) {
  7669. throwError(error, 'Indiedb.checkLogin');
  7670. return false;
  7671. }
  7672. }
  7673. async #checkLeftKey() {
  7674. try {
  7675. if (!globalOptions.other.checkLeftKey) {
  7676. return true;
  7677. }
  7678. if ($('a.buttonenter:contains("next time"), a.buttonenter:contains("Giveaway is closed")').length > 0) {
  7679. await external_Swal_default().fire({
  7680. icon: 'warning',
  7681. title: i18n('notice'),
  7682. text: i18n('giveawayEnded'),
  7683. confirmButtonText: i18n('confirm'),
  7684. cancelButtonText: i18n('cancel'),
  7685. showCancelButton: true
  7686. }).then(({
  7687. value
  7688. }) => {
  7689. if (value) {
  7690. window.close();
  7691. }
  7692. });
  7693. }
  7694. return true;
  7695. } catch (error) {
  7696. throwError(error, 'Indiedb.checkLeftKey');
  7697. return false;
  7698. }
  7699. }
  7700. }
  7701. const website_Indiedb = Indiedb;
  7702. const Keyhub_defaultTasksTemplate = {
  7703. steam: {
  7704. groupLinks: [],
  7705. officialGroupLinks: [],
  7706. wishlistLinks: [],
  7707. curatorLinks: []
  7708. },
  7709. discord: {
  7710. serverLinks: []
  7711. },
  7712. extra: {
  7713. videoTasks: []
  7714. },
  7715. links: []
  7716. };
  7717. const Keyhub_defaultTasks = JSON.stringify(Keyhub_defaultTasksTemplate);
  7718. class Keyhub extends website_Website {
  7719. name = 'Keyhub';
  7720. socialTasks = JSON.parse(Keyhub_defaultTasks);
  7721. undoneTasks = JSON.parse(Keyhub_defaultTasks);
  7722. buttons = [ 'doTask', 'undoTask' ];
  7723. static test() {
  7724. return window.location.host === 'key-hub.eu';
  7725. }
  7726. async after() {
  7727. try {
  7728. if (!this.#checkLogin()) {
  7729. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7730. }
  7731. if (!await this.#checkLeftKey()) {
  7732. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7733. }
  7734. $('.NSFW').hide();
  7735. } catch (error) {
  7736. throwError(error, 'Keyhub.after');
  7737. }
  7738. }
  7739. init() {
  7740. try {
  7741. const logStatus = scripts_echoLog({
  7742. text: i18n('initing')
  7743. });
  7744. if ($('a[href*="/connect/steam"]').length > 0) {
  7745. window.open('/connect/steam', '_self');
  7746. logStatus.warning(i18n('needLogin'));
  7747. return false;
  7748. }
  7749. if (!this.#getGiveawayId()) {
  7750. return false;
  7751. }
  7752. $('#VPNoverlay').hide();
  7753. $('#mainArticleSection').show();
  7754. this.initialized = true;
  7755. logStatus.success();
  7756. return true;
  7757. } catch (error) {
  7758. throwError(error, 'Keyhub.init');
  7759. return false;
  7760. }
  7761. }
  7762. async classifyTask(action) {
  7763. try {
  7764. const logStatus = scripts_echoLog({
  7765. text: i18n('getTasksInfo')
  7766. });
  7767. if (action === 'undo') {
  7768. this.socialTasks = GM_getValue(`khTasks-${this.giveawayId}`)?.tasks || JSON.parse(Keyhub_defaultTasks);
  7769. }
  7770. const tasks = $('.task:not(".googleads")').filter((index, element) => action === 'do' ? $(element).find('i.fa-check-circle:visible').length === 0 : true).find('a');
  7771. for (const task of tasks) {
  7772. let link = $(task).attr('href');
  7773. const taskDes = $(task).text().trim();
  7774. if (!link) {
  7775. continue;
  7776. }
  7777. if (/\/away\?data=/.test(link) || /steamcommunity\.com\/gid\//.test(link)) {
  7778. link = await getRedirectLink(link) || link;
  7779. }
  7780. if (/https?:\/\/key-hub\.eu\/connect\/discord/.test(link)) {
  7781. GM_openInTab(link, {
  7782. active: true
  7783. });
  7784. } else if (/steamcommunity\.com\/groups\//.test(link)) {
  7785. if (action === 'undo') {
  7786. this.socialTasks.steam.groupLinks.push(link);
  7787. }
  7788. if (action === 'do') {
  7789. this.undoneTasks.steam.groupLinks.push(link);
  7790. }
  7791. } else if (/steamcommunity\.com\/games\/[\d]+/.test(link)) {
  7792. if (action === 'undo') {
  7793. this.socialTasks.steam.officialGroupLinks.push(link);
  7794. }
  7795. if (action === 'do') {
  7796. this.undoneTasks.steam.officialGroupLinks.push(link);
  7797. }
  7798. } else if (/store\.steampowered\.com\/app\//.test(link) && /wishlist/gim.test(taskDes)) {
  7799. if (action === 'undo') {
  7800. this.socialTasks.steam.wishlistLinks.push(link);
  7801. }
  7802. if (action === 'do') {
  7803. this.undoneTasks.steam.wishlistLinks.push(link);
  7804. }
  7805. } else if (/store\.steampowered\.com\/curator\//.test(link)) {
  7806. if (action === 'undo') {
  7807. this.socialTasks.steam.curatorLinks.push(link);
  7808. }
  7809. if (action === 'do') {
  7810. this.undoneTasks.steam.curatorLinks.push(link);
  7811. }
  7812. } else if (/^https?:\/\/discord\.com\/invite\//.test(link)) {
  7813. if (action === 'undo') {
  7814. this.socialTasks.discord.serverLinks.push(link);
  7815. }
  7816. if (action === 'do') {
  7817. this.undoneTasks.discord.serverLinks.push(link);
  7818. }
  7819. } else if (/^javascript:videoTask.+/.test(link)) {
  7820. if (action === 'do') {
  7821. const taskData = link.match(/javascript:videoTask\('.+?','(.+?)'/)?.[1];
  7822. if (taskData) {
  7823. this.undoneTasks.extra.videoTasks.push(taskData);
  7824. }
  7825. }
  7826. } 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 {
  7827. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  7828. }
  7829. }
  7830. logStatus.success();
  7831. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7832. this.socialTasks = this.uniqueTasks(this.socialTasks);
  7833. if (window.DEBUG) {
  7834. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7835. }
  7836. GM_setValue(`khTasks-${this.giveawayId}`, {
  7837. tasks: this.socialTasks,
  7838. time: new Date().getTime()
  7839. });
  7840. return true;
  7841. } catch (error) {
  7842. throwError(error, 'Keyhub.classifyTask');
  7843. return false;
  7844. }
  7845. }
  7846. async #doScriptTask(data) {
  7847. try {
  7848. const logStatus = scripts_echoLog({
  7849. text: i18n('doingKeyhubTask')
  7850. });
  7851. const {
  7852. result,
  7853. statusText,
  7854. status,
  7855. data: response
  7856. } = await tools_httpRequest({
  7857. url: `/away?data=${data}`,
  7858. method: 'GET',
  7859. headers: {
  7860. origin: 'https://key-hub.eu',
  7861. referer: 'https://key-hub.eu/'
  7862. }
  7863. });
  7864. if (result === 'Success') {
  7865. if (response?.status === 200) {
  7866. logStatus.success();
  7867. return true;
  7868. }
  7869. logStatus.error(`Error:${response?.statusText}(${response?.status})`);
  7870. return false;
  7871. }
  7872. logStatus.error(`${result}:${statusText}(${status})`);
  7873. return false;
  7874. } catch (error) {
  7875. throwError(error, 'Keyhub.doScriptTask');
  7876. return false;
  7877. }
  7878. }
  7879. async extraDoTask({
  7880. videoTasks
  7881. }) {
  7882. try {
  7883. const pro = [];
  7884. for (const data of videoTasks) {
  7885. pro.push(this.#doScriptTask(data));
  7886. }
  7887. return Promise.all(pro).then(() => true);
  7888. } catch (error) {
  7889. throwError(error, 'Keyhub.extraDoTask');
  7890. return false;
  7891. }
  7892. }
  7893. #getGiveawayId() {
  7894. try {
  7895. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  7896. if (giveawayId) {
  7897. this.giveawayId = giveawayId;
  7898. return true;
  7899. }
  7900. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  7901. return false;
  7902. } catch (error) {
  7903. throwError(error, 'Keyhub.getGiveawayId');
  7904. return false;
  7905. }
  7906. }
  7907. async #checkLeftKey() {
  7908. try {
  7909. if (!globalOptions.other.checkLeftKey) {
  7910. return true;
  7911. }
  7912. const leftKey = $('#keysleft').text().trim();
  7913. if (leftKey === '0') {
  7914. await external_Swal_default().fire({
  7915. icon: 'warning',
  7916. title: i18n('notice'),
  7917. text: i18n('noKeysLeft'),
  7918. confirmButtonText: i18n('confirm'),
  7919. cancelButtonText: i18n('cancel'),
  7920. showCancelButton: true
  7921. }).then(({
  7922. value
  7923. }) => {
  7924. if (value) {
  7925. window.close();
  7926. }
  7927. });
  7928. }
  7929. return true;
  7930. } catch (error) {
  7931. throwError(error, 'Keyhub.checkLeftKey');
  7932. return false;
  7933. }
  7934. }
  7935. #checkLogin() {
  7936. try {
  7937. if (!globalOptions.other.checkLogin) {
  7938. return true;
  7939. }
  7940. if ($('a[href*="/connect/steam"]').length > 0) {
  7941. window.open('/connect/steam', '_self');
  7942. }
  7943. return true;
  7944. } catch (error) {
  7945. throwError(error, 'Keyhub.checkLogin');
  7946. return false;
  7947. }
  7948. }
  7949. }
  7950. const website_Keyhub = Keyhub;
  7951. const Givekey_defaultTasksTemplate = {
  7952. steam: {
  7953. groupLinks: [],
  7954. wishlistLinks: [],
  7955. curatorLinks: [],
  7956. curatorLikeLinks: []
  7957. },
  7958. twitter: {
  7959. userLinks: []
  7960. },
  7961. vk: {
  7962. nameLinks: []
  7963. },
  7964. discord: {
  7965. serverLinks: []
  7966. }
  7967. };
  7968. const Givekey_defaultTasks = JSON.stringify(Givekey_defaultTasksTemplate);
  7969. class Givekey extends website_Website {
  7970. name = 'Givekey';
  7971. tasks = [];
  7972. socialTasks = JSON.parse(Givekey_defaultTasks);
  7973. undoneTasks = JSON.parse(Givekey_defaultTasks);
  7974. userId;
  7975. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  7976. static test() {
  7977. return window.location.host === 'givekey.ru';
  7978. }
  7979. async after() {
  7980. try {
  7981. await new Promise(resolve => {
  7982. const checker = setInterval(() => {
  7983. if ($('#navbarDropdown').length > 0) {
  7984. clearInterval(checker);
  7985. resolve(true);
  7986. }
  7987. }, 500);
  7988. });
  7989. if (!await this.#checkLeftKey()) {
  7990. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7991. }
  7992. } catch (error) {
  7993. throwError(error, 'Givekey.after');
  7994. }
  7995. }
  7996. init() {
  7997. try {
  7998. const logStatus = scripts_echoLog({
  7999. text: i18n('initing')
  8000. });
  8001. if ($('a[href*="/auth/steam"]').length > 0) {
  8002. window.open('/auth/steam', '_self');
  8003. logStatus.warning(i18n('needLogin'));
  8004. return false;
  8005. }
  8006. if (!this.#getGiveawayId()) {
  8007. return false;
  8008. }
  8009. const userId = $('meta[name="user-id"]').attr('content');
  8010. if (!userId) {
  8011. logStatus.error(i18n('getFailed', i18n('userId')));
  8012. return false;
  8013. }
  8014. this.userId = userId;
  8015. this.initialized = true;
  8016. logStatus.success();
  8017. return true;
  8018. } catch (error) {
  8019. throwError(error, 'Givekey.init');
  8020. return false;
  8021. }
  8022. }
  8023. async classifyTask(action) {
  8024. try {
  8025. const logStatus = scripts_echoLog({
  8026. text: i18n('getTasksInfo')
  8027. });
  8028. if (action === 'undo') {
  8029. this.socialTasks = GM_getValue(`gkTasks-${this.giveawayId}`)?.tasks || JSON.parse(Givekey_defaultTasks);
  8030. }
  8031. const tasks = $('.card-body:has("button") .row');
  8032. for (const task of tasks) {
  8033. const taskEle = $(task);
  8034. const isSuccess = /Complete/i.test(taskEle.find('button').text().trim());
  8035. if (isSuccess && action !== 'undo') {
  8036. continue;
  8037. }
  8038. const checkButton = taskEle.find('#task_check');
  8039. const taskId = checkButton.attr('data-id');
  8040. if (taskId) {
  8041. this.tasks.push(taskId);
  8042. }
  8043. if (action === 'verify') {
  8044. continue;
  8045. }
  8046. let href = taskEle.find('a').attr('href') || null;
  8047. const text = taskEle.find('a').text().trim();
  8048. const icon = taskEle.find('i');
  8049. if (!href || !text) {
  8050. continue;
  8051. }
  8052. if (/^https?:\/\/givekey\.ru\/giveaway\/[\d]+\/execution_task/.test(href)) {
  8053. href = await getRedirectLink(href);
  8054. }
  8055. if (!href) {
  8056. continue;
  8057. }
  8058. if (/^https?:\/\/vk\.com\//.test(href)) {
  8059. this.socialTasks.vk.nameLinks.push(href);
  8060. if (action === 'do' && !isSuccess) {
  8061. this.undoneTasks.vk.nameLinks.push(href);
  8062. }
  8063. } else if (/^https?:\/\/steamcommunity\.com\/groups/.test(href)) {
  8064. this.socialTasks.steam.groupLinks.push(href);
  8065. if (action === 'do' && !isSuccess) {
  8066. this.undoneTasks.steam.groupLinks.push(href);
  8067. }
  8068. } else if (/^https?:\/\/store\.steampowered\.com\/app\//.test(href)) {
  8069. this.socialTasks.steam.wishlistLinks.push(href);
  8070. if (action === 'do' && !isSuccess) {
  8071. this.undoneTasks.steam.wishlistLinks.push(href);
  8072. }
  8073. } else if (/Subscribe/gi.test(text) && icon.hasClass('fa-steam-square')) {
  8074. if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(href)) {
  8075. this.socialTasks.steam.curatorLinks.push(href);
  8076. if (action === 'do' && !isSuccess) {
  8077. this.undoneTasks.steam.curatorLinks.push(href);
  8078. }
  8079. } else {
  8080. this.socialTasks.steam.curatorLikeLinks.push(href);
  8081. if (action === 'do' && !isSuccess) {
  8082. this.undoneTasks.steam.curatorLikeLinks.push(href);
  8083. }
  8084. }
  8085. } else if (/^https?:\/\/twitter\.com\//.test(href) && /Subscribe/gi.test(text)) {
  8086. this.socialTasks.twitter.userLinks.push(href);
  8087. if (action === 'do' && !isSuccess) {
  8088. this.undoneTasks.twitter.userLinks.push(href);
  8089. }
  8090. } else if (icon.hasClass('fa-discord') || /^https?:\/\/discord\.com\/invite\//.test(href)) {
  8091. this.socialTasks.discord.serverLinks.push(href);
  8092. if (action === 'do' && !isSuccess) {
  8093. this.undoneTasks.discord.serverLinks.push(href);
  8094. }
  8095. } else {
  8096. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${text}(${href})`);
  8097. }
  8098. }
  8099. logStatus.success();
  8100. this.tasks = unique(this.tasks);
  8101. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8102. this.socialTasks = this.uniqueTasks(this.socialTasks);
  8103. if (window.DEBUG) {
  8104. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8105. }
  8106. GM_setValue(`gkTasks-${this.giveawayId}`, {
  8107. tasks: this.socialTasks,
  8108. time: new Date().getTime()
  8109. });
  8110. return true;
  8111. } catch (error) {
  8112. throwError(error, 'Givekey.classifyTask');
  8113. return false;
  8114. }
  8115. }
  8116. async verifyTask() {
  8117. try {
  8118. if (!this.initialized && !this.init()) {
  8119. return false;
  8120. }
  8121. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  8122. return false;
  8123. }
  8124. scripts_echoLog({}).warning(i18n('giveKeyNoticeBefore'));
  8125. const taskLength = this.tasks.length;
  8126. for (let i = 0; i < taskLength; i++) {
  8127. await this.#verify(this.tasks[i]);
  8128. if (i < taskLength - 1) {
  8129. await delay(15e3);
  8130. }
  8131. }
  8132. scripts_echoLog({}).success(i18n('allTasksComplete'));
  8133. scripts_echoLog({
  8134. html: `<li><font class="warning">${i18n('giveKeyNoticeAfter')}</font></li>`
  8135. });
  8136. return true;
  8137. } catch (error) {
  8138. throwError(error, 'Givekey.verifyTask');
  8139. return false;
  8140. }
  8141. }
  8142. async #verify(task) {
  8143. try {
  8144. const logStatus = scripts_echoLog({
  8145. html: `<li>${i18n('verifyingTask')}${task}...<font></font></li>`
  8146. });
  8147. return await new Promise(resolve => {
  8148. $.ajax({
  8149. url: 'https://givekey.ru/giveaway/task',
  8150. method: 'POST',
  8151. data: `id=${task}&user_id=${this.userId}`,
  8152. dataType: 'json',
  8153. headers: {
  8154. 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  8155. },
  8156. success: data => {
  8157. if (data.btn) {
  8158. $(`button[data-id=${this.userId}]`).html(data.btn);
  8159. }
  8160. if (data.status === 'ok') {
  8161. $(`.task_check_${data.id}`).html(`<button class="btn btn-success mb-2 btn-block" disabled>${data.btn}</button>`);
  8162. logStatus.success();
  8163. resolve(true);
  8164. } else if (data.status === 'end') {
  8165. logStatus.success();
  8166. scripts_echoLog({}).success(data.key);
  8167. resolve(true);
  8168. } else {
  8169. logStatus.error(`Error:${data.msg}`);
  8170. resolve(false);
  8171. }
  8172. },
  8173. error: xhr => {
  8174. logStatus.error(`Error:${xhr.statusText}(${xhr.status})`);
  8175. resolve(false);
  8176. }
  8177. });
  8178. });
  8179. } catch (error) {
  8180. throwError(error, 'Givekey.verify');
  8181. return false;
  8182. }
  8183. }
  8184. #getGiveawayId() {
  8185. try {
  8186. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  8187. if (giveawayId) {
  8188. this.giveawayId = giveawayId;
  8189. return true;
  8190. }
  8191. scripts_echoLog({
  8192. text: i18n('getFailed', 'GiveawayId')
  8193. });
  8194. return false;
  8195. } catch (error) {
  8196. throwError(error, 'Givekey.getGiveawayId');
  8197. return false;
  8198. }
  8199. }
  8200. async #checkLeftKey() {
  8201. try {
  8202. if (!globalOptions.other.checkLeftKey) {
  8203. return true;
  8204. }
  8205. if (!$('#keys_count').text()) {
  8206. await external_Swal_default().fire({
  8207. icon: 'warning',
  8208. title: i18n('notice'),
  8209. text: i18n('noKeysLeft'),
  8210. confirmButtonText: i18n('confirm'),
  8211. cancelButtonText: i18n('cancel'),
  8212. showCancelButton: true
  8213. }).then(({
  8214. value
  8215. }) => {
  8216. if (value) {
  8217. window.close();
  8218. }
  8219. });
  8220. }
  8221. return true;
  8222. } catch (error) {
  8223. throwError(error, 'Givekey.checkLeftKey');
  8224. return false;
  8225. }
  8226. }
  8227. }
  8228. const website_Givekey = Givekey;
  8229. class GiveeClub extends GiveawaySu {
  8230. name = 'GiveeClub';
  8231. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8232. static test() {
  8233. return /^https?:\/\/givee\.club\/.*?\/event\/[\d]+/.test(window.location.href);
  8234. }
  8235. async after() {
  8236. try {
  8237. if (!this.#checkLogin()) {
  8238. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8239. }
  8240. if (!await this.#checkLeftKey()) {
  8241. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8242. }
  8243. } catch (error) {
  8244. throwError(error, 'GiveeClub.after');
  8245. }
  8246. }
  8247. init() {
  8248. try {
  8249. const logStatus = scripts_echoLog({
  8250. text: i18n('initing')
  8251. });
  8252. if (!this.#checkLogin()) {
  8253. logStatus.warning(i18n('needLogin'));
  8254. return false;
  8255. }
  8256. if (!this.#getGiveawayId()) {
  8257. return false;
  8258. }
  8259. this.initialized = true;
  8260. logStatus.success();
  8261. return true;
  8262. } catch (error) {
  8263. throwError(error, 'GiveeClub.init');
  8264. return false;
  8265. }
  8266. }
  8267. async classifyTask(action) {
  8268. try {
  8269. const logStatus = scripts_echoLog({
  8270. text: i18n('getTasksInfo')
  8271. });
  8272. if (action === 'undo') {
  8273. this.socialTasks = GM_getValue(`gcTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  8274. return true;
  8275. }
  8276. this.undoneTasks = Giveawaysu_defaultTasks;
  8277. const pro = [];
  8278. const tasks = $('.event-actions tr');
  8279. for (const task of tasks) {
  8280. pro.push(new Promise(resolve => {
  8281. const taskDes = $(task).find('.event-action-label a');
  8282. const taskIcon = $(task).find('.event-action-icon i').attr('class') || '';
  8283. const taskName = taskDes.text().trim();
  8284. const taskType = $(task).find('button[data-type]')?.attr('data-type');
  8285. const taskFinished = $(task).find('.event-action-buttons .btn-success')?.length;
  8286. if (taskIcon.includes('ban') || /AdBlock/i.test(taskName) || taskIcon.includes('envelope') || taskFinished) {
  8287. return resolve(true);
  8288. }
  8289. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  8290. if (!taskLink) {
  8291. return resolve(false);
  8292. }
  8293. if (taskType === 'steam.group.join' && /^https?:\/\/steamcommunity\.com\/groups/.test(taskLink)) {
  8294. this.undoneTasks.steam.groupLinks.push(taskLink);
  8295. } else if (/like.*announcement/gi.test(taskName)) {
  8296. this.undoneTasks.steam.announcementLinks.push(taskLink);
  8297. } else if (taskType === 'steam.game.wishlist' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8298. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  8299. } else if (taskType === 'steam.game.wishlist' && taskDes.attr('data-steam-wishlist-appid')) {
  8300. this.undoneTasks.steam.wishlistLinks.push(`https://store.steampowered.com/app/${taskDes.attr('data-steam-wishlist-appid')}`);
  8301. } else if (taskType === 'steam.game.follow' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8302. this.undoneTasks.steam.followLinks.push(taskLink);
  8303. } else if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  8304. this.undoneTasks.steam.curatorLinks.push(taskLink);
  8305. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  8306. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  8307. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  8308. this.undoneTasks.steam.forumLinks.push(taskLink);
  8309. } else if (taskIcon.includes('discord')) {
  8310. this.undoneTasks.discord.serverLinks.push(taskLink);
  8311. } else if (taskIcon.includes('instagram')) {
  8312. this.undoneTasks.instagram.userLinks.push(taskLink);
  8313. } else if (taskIcon.includes('twitch')) {
  8314. this.undoneTasks.twitch.channelLinks.push(taskLink);
  8315. } else if (taskIcon.includes('reddit')) {
  8316. this.undoneTasks.reddit.redditLinks.push(taskLink);
  8317. } else if (/watch.*art/gim.test(taskName)) {
  8318. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  8319. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  8320. this.undoneTasks.youtube.channelLinks.push(taskLink);
  8321. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  8322. this.undoneTasks.youtube.likeLinks.push(taskLink);
  8323. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  8324. this.undoneTasks.vk.nameLinks.push(taskLink);
  8325. } else if (taskIcon.includes('twitter')) {
  8326. if (/https?:\/\/(twitter|x)\.com\/[^/]+\/?$/gim.test(taskLink)) {
  8327. this.undoneTasks.twitter.userLinks.push(taskLink);
  8328. } else if (/https?:\/\/(twitter|x)\.com\/[^/]+?\/status\/[\d]+/gim.test(taskLink)) {
  8329. this.undoneTasks.twitter.retweetLinks.push(taskLink);
  8330. }
  8331. } else {
  8332. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  8333. if (/follow.*button/gim.test(taskName)) {
  8334. this.undoneTasks.steam.followLinks.push(taskLink);
  8335. }
  8336. }
  8337. }
  8338. resolve(true);
  8339. }).catch(error => {
  8340. throwError(error, 'GiveeClub.classifyTask->getRedirectLink');
  8341. return false;
  8342. });
  8343. }));
  8344. }
  8345. await Promise.all(pro);
  8346. logStatus.success();
  8347. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8348. this.socialTasks = this.undoneTasks;
  8349. if (window.DEBUG) {
  8350. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8351. }
  8352. GM_setValue(`gcTasks-${this.giveawayId}`, {
  8353. tasks: this.socialTasks,
  8354. time: new Date().getTime()
  8355. });
  8356. return true;
  8357. } catch (error) {
  8358. throwError(error, 'GiveeClub.classifyTask');
  8359. return false;
  8360. }
  8361. }
  8362. async verifyTask() {
  8363. try {
  8364. const logStatus = scripts_echoLog({
  8365. text: i18n('giveeClubVerifyNotice')
  8366. });
  8367. const taskButtons = $('.event-actions tr button').has('i.glyphicon-refresh').not('[data-type="user.adblock"]');
  8368. for (const button of taskButtons) {
  8369. button.click();
  8370. if ($(button).attr('data-type') !== 'steam.game.wishlist') {
  8371. await delay(1e3);
  8372. }
  8373. }
  8374. logStatus.warning(i18n('giveeClubVerifyFinished'));
  8375. return true;
  8376. } catch (error) {
  8377. throwError(error, 'Givekey.verifyTask');
  8378. return false;
  8379. }
  8380. }
  8381. #checkLogin() {
  8382. try {
  8383. if (!globalOptions.other.checkLogin) {
  8384. return true;
  8385. }
  8386. if ($('a[href*="/account/auth"]').length > 0) {
  8387. window.open($('a[href*="/account/auth"]').attr('href'), '_self');
  8388. }
  8389. return true;
  8390. } catch (error) {
  8391. throwError(error, 'GiveeClub.checkLogin');
  8392. return false;
  8393. }
  8394. }
  8395. #getGiveawayId() {
  8396. const giveawayId = window.location.href.match(/\/event\/([\d]+)/)?.[1];
  8397. if (giveawayId) {
  8398. this.giveawayId = giveawayId;
  8399. return true;
  8400. }
  8401. scripts_echoLog({
  8402. text: i18n('getFailed', 'GiveawayId')
  8403. });
  8404. return false;
  8405. }
  8406. async #checkLeftKey() {
  8407. try {
  8408. if (!globalOptions.other.checkLeftKey) {
  8409. return true;
  8410. }
  8411. if ($('.event-ended').length > 0 && $('.event-winner').length === 0) {
  8412. await external_Swal_default().fire({
  8413. icon: 'warning',
  8414. title: i18n('notice'),
  8415. text: i18n('giveawayEnded'),
  8416. confirmButtonText: i18n('confirm'),
  8417. cancelButtonText: i18n('cancel'),
  8418. showCancelButton: true
  8419. }).then(({
  8420. value
  8421. }) => {
  8422. if (value) {
  8423. window.close();
  8424. }
  8425. });
  8426. }
  8427. return true;
  8428. } catch (error) {
  8429. throwError(error, 'Giveawaysu.checkLeftKey');
  8430. return false;
  8431. }
  8432. }
  8433. }
  8434. const website_GiveeClub = GiveeClub;
  8435. const defaultOptions = {
  8436. maxPoint: '99999999'
  8437. };
  8438. class OpiumPulses {
  8439. name = 'OpiumPulses';
  8440. options = {
  8441. ...defaultOptions,
  8442. ...GM_getValue('OpiumPulsesOptions')
  8443. };
  8444. maxPoints = 99999999;
  8445. myPoints = 0;
  8446. buttons = [ 'doFreeTask', 'doPointTask' ];
  8447. static test() {
  8448. return window.location.host === 'www.opiumpulses.com';
  8449. }
  8450. async after() {
  8451. try {
  8452. if (!this.#checkLogin()) {
  8453. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8454. }
  8455. this.maxPoints = parseInt(this.options.maxPoint, 10);
  8456. } catch (error) {
  8457. throwError(error, 'OpiumPulses.after');
  8458. }
  8459. }
  8460. async doFreeTask() {
  8461. try {
  8462. this.#toggleTask('FREE');
  8463. } catch (error) {
  8464. throwError(error, 'OpiumPulses.doFreeTask');
  8465. }
  8466. }
  8467. async doPointTask() {
  8468. try {
  8469. this.myPoints = parseInt($('.page-header__nav-func-user-nav-items.points-items').text().match(/[\d]+/gim)?.[0] || '0', 10);
  8470. this.#toggleTask('points');
  8471. } catch (error) {
  8472. throwError(error, 'OpiumPulses.doPointTask');
  8473. }
  8474. }
  8475. async #toggleTask(type) {
  8476. try {
  8477. const items = $(`.giveaways-page-item:contains('${type}'):not(:contains('ENTERED'))`);
  8478. for (const item of items) {
  8479. const needPoints = parseInt($(item).find('.giveaways-page-item-header-points').text().match(/[\d]+/gim)?.[0] || '999999', 10);
  8480. const name = $(item).find('.giveaways-page-item-footer-name').text().trim();
  8481. if (type === 'points' && needPoints > this.myPoints) {
  8482. scripts_echoLog({}).warning(`${i18n('noPoints')}: ${name}`);
  8483. } else if (type === 'points' && !needPoints) {
  8484. scripts_echoLog({}).warning(`${i18n('getNeedPointsFailed')}: ${name}`);
  8485. } else if (!(type === 'points' && needPoints > this.maxPoints)) {
  8486. const logStatus = scripts_echoLog({
  8487. text: `${i18n('joiningLottery')}<a href="${$(item).find('a.giveaways-page-item-img-btn-more').attr('href')}" target="_blank">${name}</a>...`
  8488. });
  8489. const aElement = $(item).find('a.giveaways-page-item-img-btn-enter:contains(\'enter\')');
  8490. if (aElement?.attr('onclick')?.includes('checkUser')) {
  8491. const giveawayId = aElement.attr('onclick')?.match(/[\d]+/)?.[0];
  8492. if (giveawayId) {
  8493. checkUser(giveawayId);
  8494. }
  8495. }
  8496. if (!aElement.attr('href')) {
  8497. logStatus.error('Error: No "href".');
  8498. continue;
  8499. }
  8500. const {
  8501. result,
  8502. statusText,
  8503. status,
  8504. data
  8505. } = await tools_httpRequest({
  8506. url: aElement.attr('href'),
  8507. method: 'GET'
  8508. });
  8509. if (result === 'Success') {
  8510. const {
  8511. result: result0,
  8512. statusText: statusText0,
  8513. status: status0,
  8514. data: data0
  8515. } = await tools_httpRequest({
  8516. url: data?.finalUrl,
  8517. method: 'GET'
  8518. });
  8519. if (data0?.responseText && /You've entered this giveaway/gim.test(data0.responseText)) {
  8520. logStatus.success();
  8521. const points = data0.responseText.match(/Points:[\s]*?([\d]+)/)?.[1];
  8522. if (type === 'points' && points) {
  8523. this.myPoints = parseInt(points, 10);
  8524. }
  8525. } else if (data0?.responseText && /You're not eligible to enter/gim.test(data0.responseText)) {
  8526. logStatus.error('You\'re not eligible to enter');
  8527. } else {
  8528. logStatus.error(`${result0}:${statusText0}(${status0})`);
  8529. }
  8530. } else {
  8531. logStatus.error(`${result}:${statusText}(${status})`);
  8532. }
  8533. }
  8534. }
  8535. scripts_echoLog({
  8536. text: '-----END-----'
  8537. });
  8538. } catch (error) {
  8539. throwError(error, 'OpiumPulses.toggleTask');
  8540. }
  8541. }
  8542. init() {
  8543. return true;
  8544. }
  8545. classifyTask() {
  8546. return true;
  8547. }
  8548. #checkLogin() {
  8549. try {
  8550. if (!globalOptions.other.checkLogin) {
  8551. return true;
  8552. }
  8553. if ($('a[href*="/site/login"]').length > 1) {
  8554. window.open('/site/login', '_self');
  8555. }
  8556. return true;
  8557. } catch (error) {
  8558. throwError(error, 'OpiumPulses.checkLogin');
  8559. return false;
  8560. }
  8561. }
  8562. }
  8563. const website_OpiumPulses = OpiumPulses;
  8564. const external_dayjs_namespaceObject = dayjs;
  8565. var external_dayjs_default = __webpack_require__.n(external_dayjs_namespaceObject);
  8566. const leftKeyChecker = {
  8567. async classify(link) {
  8568. try {
  8569. if (/^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(link)) {
  8570. return await this.giveawaySu(link);
  8571. }
  8572. if (/^https?:\/\/givee\.club\/[\w]+?\/event\/[\d]+/.test(link)) {
  8573. return await this.giveeClub(link);
  8574. }
  8575. if (/^https?:\/\/gleam\.io\/.+?\/.+/.test(link)) {
  8576. return await this.gleam(link);
  8577. }
  8578. if (/^https?:\/\/www\.indiedb\.com\/giveaways\/.+/.test(link)) {
  8579. return await this.indieDb(link);
  8580. }
  8581. if (/^https?:\/\/key-hub\.eu\/giveaway\/[\d]+/.test(link)) {
  8582. return await this.keyhub(link);
  8583. }
  8584. if (/^https?:\/\/opquests\.com\/quests\/[\d]+/.test(link)) {
  8585. return await this.opquests(link);
  8586. }
  8587. if (/^https?:\/\/itch\.io\/s\/[\d]+?\/.*/.test(link)) {
  8588. return await this.itch(link);
  8589. }
  8590. return false;
  8591. } catch (error) {
  8592. throwError(error, 'leftKeyChecker.classify');
  8593. return false;
  8594. }
  8595. },
  8596. async giveawaySu(link) {
  8597. try {
  8598. const {
  8599. result,
  8600. data
  8601. } = await tools_httpRequest({
  8602. url: link,
  8603. method: 'GET'
  8604. });
  8605. if (result === 'Success' && data?.status === 200) {
  8606. if (data.responseText.includes('class="steam-login"')) {
  8607. return false;
  8608. }
  8609. if (data.responseText.includes('class="giveaway-ended"')) {
  8610. return 'Ended';
  8611. }
  8612. return 'Active';
  8613. }
  8614. return false;
  8615. } catch (error) {
  8616. throwError(error, 'leftKeyChecker.giveawaySu');
  8617. return false;
  8618. }
  8619. },
  8620. async giveeClub(link) {
  8621. try {
  8622. const {
  8623. result,
  8624. data
  8625. } = await tools_httpRequest({
  8626. url: link,
  8627. method: 'GET'
  8628. });
  8629. if (result === 'Success' && data?.status === 200) {
  8630. if (data.responseText.includes('class="event-winner"')) {
  8631. return 'Won';
  8632. }
  8633. if (data.responseText.includes('class="event-ended"')) {
  8634. return 'Ended';
  8635. }
  8636. return 'Active';
  8637. }
  8638. return false;
  8639. } catch (error) {
  8640. throwError(error, 'leftKeyChecker.giveeClub');
  8641. return false;
  8642. }
  8643. },
  8644. async gleam(link) {
  8645. try {
  8646. const {
  8647. result,
  8648. data
  8649. } = await tools_httpRequest({
  8650. url: link,
  8651. method: 'GET'
  8652. });
  8653. if (result === 'Success' && data?.status === 200) {
  8654. if (/incentives&quot;:{&quot;[\d]+?&quot;:\[&quot;.+?&quot;\]/.test(data.responseText)) {
  8655. return 'Won';
  8656. }
  8657. const campaignDiv = data.responseText.match(/<div class='popup-blocks-container'[\w\W]+?'>/)?.[0];
  8658. if (!campaignDiv) {
  8659. return false;
  8660. }
  8661. const campaignString = $(campaignDiv).attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  8662. if (!campaignString) {
  8663. return false;
  8664. }
  8665. const {
  8666. campaign
  8667. } = JSON.parse(campaignString);
  8668. if (campaign.banned) {
  8669. return 'Banned';
  8670. }
  8671. if (campaign.finished) {
  8672. return 'Ended';
  8673. }
  8674. if (campaign.paused) {
  8675. return 'Paused';
  8676. }
  8677. if (new Date().getTime() < campaign.starts_at * 1e3) {
  8678. return 'NotStart';
  8679. }
  8680. return 'Active';
  8681. }
  8682. return false;
  8683. } catch (error) {
  8684. throwError(error, 'leftKeyChecker.gleam');
  8685. return false;
  8686. }
  8687. },
  8688. async indieDb(link) {
  8689. try {
  8690. const {
  8691. result,
  8692. data
  8693. } = await tools_httpRequest({
  8694. url: link,
  8695. method: 'GET'
  8696. });
  8697. if (result === 'Success' && data?.status === 200) {
  8698. if (data.responseText.includes('Congrats you WON')) {
  8699. return 'Won';
  8700. }
  8701. if (data.responseText.includes('Giveaway is closed') || data.responseText.includes('next time')) {
  8702. return 'Ended';
  8703. }
  8704. return 'Active';
  8705. }
  8706. return false;
  8707. } catch (error) {
  8708. throwError(error, 'leftKeyChecker.indieDb');
  8709. return false;
  8710. }
  8711. },
  8712. async keyhub(link) {
  8713. try {
  8714. const {
  8715. result,
  8716. data
  8717. } = await tools_httpRequest({
  8718. url: link,
  8719. method: 'GET'
  8720. });
  8721. if (result === 'Success' && data?.status === 200) {
  8722. const keysleft = data.responseText.match(/<span id="keysleft">([\d]+?)<\/span>/)?.[1];
  8723. if (!keysleft) {
  8724. return false;
  8725. }
  8726. if (keysleft === '0') {
  8727. return 'Ended';
  8728. }
  8729. return `Active(${keysleft})`;
  8730. }
  8731. return false;
  8732. } catch (error) {
  8733. throwError(error, 'leftKeyChecker.keyhub');
  8734. return false;
  8735. }
  8736. },
  8737. async opquests(link) {
  8738. try {
  8739. const {
  8740. result,
  8741. data
  8742. } = await tools_httpRequest({
  8743. url: link,
  8744. method: 'GET'
  8745. });
  8746. if (result === 'Success' && data?.status === 200) {
  8747. const keysleft = data.responseText.match(/<div class="">[\s]*?([\d]+?)[\s]*?of/)?.[1];
  8748. if (!keysleft) {
  8749. return false;
  8750. }
  8751. if (keysleft === '0') {
  8752. return 'Ended';
  8753. }
  8754. return `Active(${keysleft})`;
  8755. } else if (data?.status === 404) {
  8756. return 'Ended';
  8757. }
  8758. return false;
  8759. } catch (error) {
  8760. throwError(error, 'leftKeyChecker.opquests');
  8761. return false;
  8762. }
  8763. },
  8764. async itch(link) {
  8765. try {
  8766. const {
  8767. result,
  8768. data
  8769. } = await tools_httpRequest({
  8770. url: link,
  8771. method: 'GET'
  8772. });
  8773. if (result === 'Success' && data?.status === 200) {
  8774. const endDate = data.responseText.match(/{"start_date":"[0-9A-Z-:]+?".*?"end_date":"([0-9A-Z-:]+?)".*?}/)?.[1];
  8775. if (!endDate) {
  8776. return false;
  8777. }
  8778. if (new Date().getTime() > new Date(endDate).getTime()) {
  8779. return 'Ended';
  8780. }
  8781. return `Active(${external_dayjs_default()(endDate).format('YYYY-MM-DD HH:mm:ss')})`;
  8782. }
  8783. return false;
  8784. } catch (error) {
  8785. throwError(error, 'leftKeyChecker.itch');
  8786. return false;
  8787. }
  8788. }
  8789. };
  8790. const website_leftKeyChecker = leftKeyChecker;
  8791. const Keylol_defaultTasksTemplate = {
  8792. steam: {
  8793. groupLinks: [],
  8794. wishlistLinks: [],
  8795. curatorLinks: [],
  8796. curatorLikeLinks: [],
  8797. followLinks: [],
  8798. forumLinks: [],
  8799. announcementLinks: [],
  8800. workshopVoteLinks: [],
  8801. licenseLinks: []
  8802. },
  8803. discord: {
  8804. serverLinks: []
  8805. },
  8806. instagram: {
  8807. userLinks: []
  8808. },
  8809. vk: {
  8810. nameLinks: []
  8811. },
  8812. twitch: {
  8813. channelLinks: []
  8814. },
  8815. reddit: {
  8816. redditLinks: []
  8817. },
  8818. twitter: {
  8819. userLinks: [],
  8820. retweetLinks: []
  8821. },
  8822. youtube: {
  8823. channelLinks: [],
  8824. likeLinks: []
  8825. }
  8826. };
  8827. const Keylol_defaultTasks = JSON.stringify(Keylol_defaultTasksTemplate);
  8828. class Keylol extends website_Website {
  8829. name = 'Keylol';
  8830. socialTasks = JSON.parse(Keylol_defaultTasks);
  8831. undoneTasks = JSON.parse(Keylol_defaultTasks);
  8832. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect' ];
  8833. static test() {
  8834. 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'));
  8835. }
  8836. init() {
  8837. return true;
  8838. }
  8839. after() {
  8840. try {
  8841. const selector = this.name === 'Keylol' ? '#postlist>div[id^="post_"]:first' : 'div.container';
  8842. const mainPost = $(selector);
  8843. const discordLinks = mainPost.find('a[href*="discord.com"]:visible');
  8844. const redditLinks = mainPost.find('a[href*="reddit.com"]:visible');
  8845. const insLinks = mainPost.find('a[href*="instagram.com"]:visible');
  8846. const twitterLinks = mainPost.find('a[href*="twitter.com"]:visible,a[href*="x.com"]:visible');
  8847. const twitchLinks = mainPost.find('a[href*="twitch.tv"]:visible');
  8848. const vkLinks = mainPost.find('a[href*="vk.com"]:visible');
  8849. const steamStoreLinks = mainPost.find('a[href*="store.steampowered.com"]:visible');
  8850. const steamCommunityLinks = mainPost.find('a[href*="steamcommunity.com"]:visible');
  8851. const ytbLinks = mainPost.find('a[href*="youtube.com"]:visible');
  8852. if (discordLinks.length > 0) {
  8853. for (const discordLink of discordLinks) {
  8854. const link = $(discordLink).attr('href');
  8855. if (!(link && /^https?:\/\/discord\.com\/invite\/.+/.test(link))) {
  8856. continue;
  8857. }
  8858. this.#addBtn(discordLink, 'discord', 'serverLinks', link);
  8859. }
  8860. }
  8861. if (redditLinks.length > 0) {
  8862. for (const redditLink of redditLinks) {
  8863. const link = $(redditLink).attr('href');
  8864. if (!(link && /^https?:\/\/www\.reddit\.com\/(r|user)\/.+/.test(link))) {
  8865. continue;
  8866. }
  8867. this.#addBtn(redditLink, 'reddit', 'redditLinks', link);
  8868. }
  8869. }
  8870. if (insLinks.length > 0) {
  8871. for (const insLink of insLinks) {
  8872. const link = $(insLink).attr('href');
  8873. if (!(link && /^https:\/\/www\.instagram\.com\/.+/.test(link))) {
  8874. continue;
  8875. }
  8876. this.#addBtn(insLink, 'instagram', 'userLinks', link);
  8877. }
  8878. }
  8879. if (twitterLinks.length > 0) {
  8880. for (const twitterLink of twitterLinks) {
  8881. const link = $(twitterLink).attr('href');
  8882. if (!(link && /^https:\/\/twitter\.com\/.+/.test(link))) {
  8883. continue;
  8884. }
  8885. if (/https:\/\/twitter\.com\/.*?\/status\/[\d]+/.test(link)) {
  8886. this.#addBtn(twitterLink, 'twitter', 'retweetLinks', link);
  8887. } else {
  8888. this.#addBtn(twitterLink, 'twitter', 'userLinks', link);
  8889. }
  8890. }
  8891. }
  8892. if (twitchLinks.length > 0) {
  8893. for (const twitchLink of twitchLinks) {
  8894. const link = $(twitchLink).attr('href');
  8895. if (!(link && /^https:\/\/(www\.)?twitch\.tv\/.+/.test(link))) {
  8896. continue;
  8897. }
  8898. this.#addBtn(twitchLink, 'twitch', 'channelLinks', link);
  8899. }
  8900. }
  8901. if (vkLinks.length > 0) {
  8902. for (const vkLink of vkLinks) {
  8903. const link = $(vkLink).attr('href');
  8904. if (!(link && /^https:\/\/vk\.com\/.+/.test(link))) {
  8905. continue;
  8906. }
  8907. this.#addBtn(vkLink, 'vk', 'nameLinks', link);
  8908. }
  8909. }
  8910. if (steamStoreLinks.length > 0) {
  8911. for (const steamStoreLink of steamStoreLinks) {
  8912. const link = $(steamStoreLink).attr('href');
  8913. if (!link) {
  8914. continue;
  8915. }
  8916. if (/curator\/[\d]+/.test(link)) {
  8917. this.#addBtn(steamStoreLink, 'steam', 'curatorLinks', link);
  8918. } else if (/(publisher|developer|franchise)\/.+/.test(link)) {
  8919. this.#addBtn(steamStoreLink, 'steam', 'curatorLikeLinks', link);
  8920. } else if (/news(hub)?\/app\/[\d]+\/view\/[\d]+/.test(link)) {
  8921. this.#addBtn(steamStoreLink, 'steam', 'announcementLinks', link);
  8922. } else if (/app\/[\d]+/.test(link)) {
  8923. this.#addBtn(steamStoreLink, 'steam', 'followLinks', link);
  8924. this.#addBtn(steamStoreLink, 'steam', 'wishlistLinks', link);
  8925. }
  8926. }
  8927. }
  8928. if (steamCommunityLinks.length > 0) {
  8929. for (const steamCommunityLink of steamCommunityLinks) {
  8930. const link = $(steamCommunityLink).attr('href');
  8931. if (!link) {
  8932. continue;
  8933. }
  8934. if (/groups\/.+/.test(link)) {
  8935. this.#addBtn(steamCommunityLink, 'steam', 'groupLinks', link);
  8936. } else if (/announcements\/detail\/[\d]+/.test(link)) {
  8937. this.#addBtn(steamCommunityLink, 'steam', 'announcementLinks', link);
  8938. }
  8939. }
  8940. }
  8941. if (ytbLinks.length > 0) {
  8942. for (const ytbLink of ytbLinks) {
  8943. const link = $(ytbLink).attr('href');
  8944. if (!link) {
  8945. continue;
  8946. }
  8947. this.#addBtn(ytbLink, 'youtube', 'channelLinks', link);
  8948. this.#addBtn(ytbLink, 'youtube', 'likeLinks', link);
  8949. }
  8950. }
  8951. 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');
  8952. if (giveawayLinks.length > 0) {
  8953. for (const giveawayLink of giveawayLinks) {
  8954. const link = $(giveawayLink).attr('href');
  8955. if (!link) {
  8956. continue;
  8957. }
  8958. website_leftKeyChecker.classify(link).then(status => {
  8959. if (!status) {
  8960. return;
  8961. }
  8962. if (/^Active/.test(status)) {
  8963. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status active" title="${i18n('Active')}">${status}</font>`);
  8964. return;
  8965. }
  8966. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status not-active" title="${i18n(status)}">${status}</font>`);
  8967. }).catch(error => {
  8968. throwError(error, 'keylol.after -> leftKeyChecker');
  8969. });
  8970. }
  8971. }
  8972. if (this.name === 'Keylol') {
  8973. const asfLinks = mainPost.find('a[href^="#asf"]:visible');
  8974. if (asfLinks.length > 0) {
  8975. for (const asfLink of asfLinks) {
  8976. const link = $(asfLink).attr('href');
  8977. if (!link) {
  8978. continue;
  8979. }
  8980. this.#addBtn($(`a[href="${link}"]`).after('<span style="color: #ccc; margin: 0 -5px 0 5px"> | </span>').next()[0], 'steam', 'licenseLinks', `appid-${link.replace('#asf', '')}`);
  8981. }
  8982. }
  8983. const subLinks = mainPost.find('a[href*="steamdb.info/sub/"]:visible');
  8984. if (subLinks.length > 0) {
  8985. for (const subLink of subLinks) {
  8986. const link = $(subLink).attr('href');
  8987. if (!link) {
  8988. continue;
  8989. }
  8990. const subid = link.match(/^https:\/\/steamdb\.info\/sub\/([\d]+)/)?.[1];
  8991. if (!subid) {
  8992. continue;
  8993. }
  8994. this.#addBtn(subLink, 'steam', 'licenseLinks', `subid-${subid}`);
  8995. }
  8996. }
  8997. const asfLinks2 = mainPost.find('.blockcode:contains("addlicense"):visible');
  8998. if (asfLinks2.length > 0) {
  8999. for (const asfLink of asfLinks2) {
  9000. const appid = [ ...asfLink.innerText.matchAll(/a(pp)?\/([\d]+)/g) ].map(matched => matched?.[2]).filter(id => id) || [];
  9001. if (appid.length > 0) {
  9002. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `appid-${appid.join(',')}`);
  9003. }
  9004. const subid = asfLink.innerText.match(/[\d]+/g)?.filter(matched => !appid.includes(matched));
  9005. if (!subid || subid.length === 0) {
  9006. continue;
  9007. }
  9008. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `subid-${subid.join(',')}`);
  9009. }
  9010. }
  9011. }
  9012. if ($('#threadindex').length > 0) {
  9013. const [ targetNode ] = $('#postlist').children('div[id^="post_"]');
  9014. const config = {
  9015. childList: true
  9016. };
  9017. const observer = new MutationObserver(() => {
  9018. observer.disconnect();
  9019. this.after();
  9020. });
  9021. observer.observe(targetNode, config);
  9022. }
  9023. } catch (error) {
  9024. throwError(error, 'keylol.after');
  9025. }
  9026. }
  9027. classifyTask(action) {
  9028. try {
  9029. this.socialTasks = JSON.parse(Keylol_defaultTasks);
  9030. this.undoneTasks = JSON.parse(Keylol_defaultTasks);
  9031. const selectedBtns = $('.auto-task-keylol[selected="selected"]:visible');
  9032. for (const btn of selectedBtns) {
  9033. const button = $(btn);
  9034. const social = button.attr('data-social');
  9035. const type = button.attr('data-type');
  9036. const link = button.attr('data-link');
  9037. if (!(social && type && link)) {
  9038. continue;
  9039. }
  9040. if (action === 'do') {
  9041. this.undoneTasks[social][type].push(link);
  9042. }
  9043. if (action === 'undo') {
  9044. this.socialTasks[social][type].push(link);
  9045. }
  9046. }
  9047. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9048. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9049. if (window.DEBUG) {
  9050. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9051. }
  9052. return true;
  9053. } catch (error) {
  9054. throwError(error, 'Keylol.classifyTask');
  9055. return false;
  9056. }
  9057. }
  9058. selectAll() {
  9059. try {
  9060. $('.auto-task-keylol:visible').attr('selected', 'selected');
  9061. } catch (error) {
  9062. throwError(error, 'Keylol.selectAll');
  9063. }
  9064. }
  9065. selectNone() {
  9066. try {
  9067. $('.auto-task-keylol:visible').removeAttr('selected');
  9068. } catch (error) {
  9069. throwError(error, 'Keylol.selectNone');
  9070. }
  9071. }
  9072. invertSelect() {
  9073. try {
  9074. $('.auto-task-keylol:visible').each((index, element) => {
  9075. element.getAttribute('selected') ? element.removeAttribute('selected') : element.setAttribute('selected', 'selected');
  9076. });
  9077. } catch (error) {
  9078. throwError(error, 'Keylol.invertSelect');
  9079. }
  9080. }
  9081. #addBtn(before, social, linkType, link) {
  9082. try {
  9083. $(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>`);
  9084. } catch (error) {
  9085. throwError(error, 'keylol.addBtn');
  9086. }
  9087. }
  9088. }
  9089. const website_Keylol = Keylol;
  9090. const Opquests_defaultTasks = {
  9091. steam: {
  9092. groupLinks: [],
  9093. wishlistLinks: [],
  9094. followLinks: [],
  9095. curatorLikeLinks: []
  9096. }
  9097. };
  9098. class Opquests extends website_Website {
  9099. name = 'Opquests';
  9100. undoneTasks = {
  9101. ...Opquests_defaultTasks
  9102. };
  9103. buttons = [ 'doTask', 'verifyTask', 'getKey' ];
  9104. static test() {
  9105. return window.location.host === 'opquests.com';
  9106. }
  9107. async before() {
  9108. try {
  9109. const opquestsVerifyTasks = GM_getValue('opquestsVerifyTasks') || [];
  9110. if (opquestsVerifyTasks.length > 0) {
  9111. const taskId = opquestsVerifyTasks.pop();
  9112. GM_setValue('opquestsVerifyTasks', opquestsVerifyTasks);
  9113. const [ verifyBtn ] = $(`#task_id[value="${taskId}"]`).parent().find('button[type="button"]').has('i.fa-check');
  9114. if (verifyBtn) {
  9115. verifyBtn.click();
  9116. return;
  9117. }
  9118. this.before();
  9119. return;
  9120. }
  9121. if (GM_getValue('opquestsVerifyTasks')) {
  9122. GM_deleteValue('opquestsVerifyTasks');
  9123. }
  9124. } catch (error) {
  9125. throwError(error, 'Opquests.before');
  9126. }
  9127. }
  9128. async after() {
  9129. try {
  9130. if (!this.#checkLogin()) {
  9131. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9132. }
  9133. } catch (error) {
  9134. throwError(error, 'Opquests.after');
  9135. }
  9136. }
  9137. init() {
  9138. try {
  9139. const logStatus = scripts_echoLog({
  9140. text: i18n('initing')
  9141. });
  9142. if ($('a[href*="/auth/redirect"]').length > 0) {
  9143. window.open('/auth/redirect', '_self');
  9144. logStatus.warning(i18n('needLogin'));
  9145. return false;
  9146. }
  9147. if (!this.#getGiveawayId()) {
  9148. return false;
  9149. }
  9150. this.initialized = true;
  9151. logStatus.success();
  9152. return true;
  9153. } catch (error) {
  9154. throwError(error, 'Opquests.init');
  9155. return false;
  9156. }
  9157. }
  9158. async classifyTask(action) {
  9159. try {
  9160. if (action === 'undo') {
  9161. scripts_echoLog({
  9162. text: i18n('cannotUndo')
  9163. });
  9164. return false;
  9165. }
  9166. const logStatus = scripts_echoLog({
  9167. text: i18n('getTasksInfo')
  9168. });
  9169. const tasks = $('.w-full:contains("Validate") .items-center');
  9170. for (const task of tasks) {
  9171. const link = $(task).find('a:contains("Open")').attr('href');
  9172. const taskDes = $(task).find('div').eq(1).text().trim();
  9173. if (!link) {
  9174. continue;
  9175. }
  9176. if (/steamcommunity\.com\/groups\//.test(link)) {
  9177. this.undoneTasks.steam.groupLinks.push(link);
  9178. } else if (/store\.steampowered\.com\/app\//.test(link)) {
  9179. if (/wishlist/gim.test(taskDes)) {
  9180. this.undoneTasks.steam.wishlistLinks.push(link);
  9181. } else if (/follow/gim.test(taskDes)) {
  9182. this.undoneTasks.steam.followLinks.push(link);
  9183. }
  9184. } else if (/store\.steampowered\.com\/(publisher|developer|curator)\//.test(link) && /follow/gim.test(taskDes)) {
  9185. this.undoneTasks.steam.curatorLikeLinks.push(link);
  9186. } else {
  9187. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  9188. }
  9189. }
  9190. logStatus.success();
  9191. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9192. if (window.DEBUG) {
  9193. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9194. }
  9195. return true;
  9196. } catch (error) {
  9197. throwError(error, 'Opquests.classifyTask');
  9198. return false;
  9199. }
  9200. }
  9201. async verifyTask() {
  9202. try {
  9203. if (!this.initialized) {
  9204. this.init();
  9205. }
  9206. const tasks = $.makeArray($('.items-center').has('input[name="task_id"]')).map(ele => $(ele).find('input[name="task_id"]').val());
  9207. await this.#confirm();
  9208. const taskId = tasks.pop();
  9209. GM_setValue('opquestsVerifyTasks', tasks);
  9210. $(`#task_id[value="${taskId}"]`).parent().find('button[type="button"]').has('i.fa-check')[0]?.click();
  9211. return true;
  9212. } catch (error) {
  9213. throwError(error, 'Opquests.verifyTask');
  9214. return false;
  9215. }
  9216. }
  9217. async #confirm() {
  9218. try {
  9219. const logStatus = scripts_echoLog({
  9220. html: `<li>${i18n('confirmingTask')}...<font></font></li>`
  9221. });
  9222. const {
  9223. result,
  9224. statusText,
  9225. status,
  9226. data
  9227. } = await tools_httpRequest({
  9228. url: `https://opquests.com/quests/${this.giveawayId}?confirm=1`,
  9229. method: 'GET',
  9230. nochche: true,
  9231. headers: {
  9232. origin: 'https://opquests.com',
  9233. referer: `https://opquests.com/warning?id=${this.giveawayId}`
  9234. }
  9235. });
  9236. if (result === 'Success') {
  9237. if (data?.status === 200) {
  9238. logStatus.success();
  9239. return true;
  9240. }
  9241. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9242. return false;
  9243. }
  9244. logStatus.error(`${result}:${statusText}(${status})`);
  9245. return false;
  9246. } catch (error) {
  9247. throwError(error, 'Opquests.confirm');
  9248. return false;
  9249. }
  9250. }
  9251. async getKey(isButton) {
  9252. try {
  9253. const logStatus = scripts_echoLog({
  9254. text: i18n('gettingKey')
  9255. });
  9256. const {
  9257. result,
  9258. statusText,
  9259. status,
  9260. data
  9261. } = await tools_httpRequest({
  9262. url: 'https://opquests.com/keys',
  9263. method: 'GET'
  9264. });
  9265. if (result === 'Success') {
  9266. if (data?.responseText) {
  9267. const key = $(data?.responseText).find(`div.items-center:contains("${$('h1.font-bold').text().trim().replace(' Quest', '')}")`).find('div.font-bold').next().text();
  9268. if (!key) {
  9269. logStatus.error('Error: Key was not found');
  9270. if (isButton) {
  9271. window.open('https://opquests.com/keys', '_self');
  9272. }
  9273. return false;
  9274. }
  9275. logStatus.success();
  9276. scripts_echoLog({}).success(key);
  9277. return true;
  9278. }
  9279. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9280. return false;
  9281. }
  9282. logStatus.error(`${result}:${statusText}(${status})`);
  9283. return false;
  9284. } catch (error) {
  9285. throwError(error, 'Opquests.getGiveawayId');
  9286. return false;
  9287. }
  9288. }
  9289. #getGiveawayId() {
  9290. try {
  9291. const giveawayId = window.location.href.match(/quests\/([\d]+)/)?.[1];
  9292. if (giveawayId) {
  9293. this.giveawayId = giveawayId;
  9294. return true;
  9295. }
  9296. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  9297. return false;
  9298. } catch (error) {
  9299. throwError(error, 'Opquests.getGiveawayId');
  9300. return false;
  9301. }
  9302. }
  9303. #checkLogin() {
  9304. try {
  9305. if (!globalOptions.other.checkLogin) {
  9306. return true;
  9307. }
  9308. if ($('a[href*="/auth/redirect"]').length > 0) {
  9309. window.open('/auth/redirect', '_self');
  9310. }
  9311. return true;
  9312. } catch (error) {
  9313. throwError(error, 'Opquests.checkLogin');
  9314. return false;
  9315. }
  9316. }
  9317. }
  9318. const website_Opquests = Opquests;
  9319. const Gleam_defaultTasksTemplate = {
  9320. steam: {
  9321. groupLinks: [],
  9322. wishlistLinks: [],
  9323. followLinks: [],
  9324. curatorLinks: [],
  9325. curatorLikeLinks: []
  9326. },
  9327. twitter: {
  9328. userLinks: [],
  9329. retweetLinks: []
  9330. },
  9331. twitch: {
  9332. channelLinks: []
  9333. },
  9334. discord: {
  9335. serverLinks: []
  9336. },
  9337. youtube: {
  9338. channelLinks: []
  9339. },
  9340. extra: {
  9341. gleam: []
  9342. }
  9343. };
  9344. const Gleam_defaultTasks = JSON.stringify(Gleam_defaultTasksTemplate);
  9345. class Gleam extends website_Website {
  9346. name = 'Gleam';
  9347. undoneTasks = JSON.parse(Gleam_defaultTasks);
  9348. socialTasks = JSON.parse(Gleam_defaultTasks);
  9349. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  9350. static test() {
  9351. return window.location.host === 'gleam.io';
  9352. }
  9353. before() {
  9354. try {
  9355. unsafeWindow.confirm = () => {};
  9356. unsafeWindow.alert = () => {};
  9357. unsafeWindow.prompt = () => {};
  9358. } catch (error) {
  9359. throwError(error, 'Gleam.before');
  9360. }
  9361. }
  9362. async after() {
  9363. try {
  9364. if (window.location.search.includes('8b07d23f4bfa65f9')) {
  9365. const checkComplete = setInterval(() => {
  9366. if ($('.entry-content .entry-method i.fa-check').length > 0) {
  9367. clearInterval(checkComplete);
  9368. window.close();
  9369. }
  9370. });
  9371. for (const task of $('.entry-content .entry-method')) {
  9372. const taskInfo = $(task).find('.user-links');
  9373. const expandInfo = $(task).find('.expandable');
  9374. const aElements = expandInfo.find('a.btn,a:contains(Continue),button:contains(Continue)');
  9375. if (aElements.length > 0) {
  9376. for (const element of aElements) {
  9377. const $element = $(element);
  9378. const href = $element.attr('href');
  9379. $element.removeAttr('href')[0].click();
  9380. $element.attr('href', href);
  9381. await delay(1e3);
  9382. }
  9383. }
  9384. taskInfo[0].click();
  9385. await delay(1e3);
  9386. }
  9387. scripts_echoLog({}).warning(i18n('gleamTaskNotice'));
  9388. } else if (!await this.#checkLeftKey()) {
  9389. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  9390. }
  9391. } catch (error) {
  9392. throwError(error, 'Gleam.after');
  9393. }
  9394. }
  9395. init() {
  9396. try {
  9397. const logStatus = scripts_echoLog({
  9398. text: i18n('initing')
  9399. });
  9400. if (!this.#getGiveawayId()) {
  9401. return false;
  9402. }
  9403. this.initialized = true;
  9404. logStatus.success();
  9405. return true;
  9406. } catch (error) {
  9407. throwError(error, 'Gleam.init');
  9408. return false;
  9409. }
  9410. }
  9411. async classifyTask(action) {
  9412. try {
  9413. const logStatus = scripts_echoLog({
  9414. text: i18n('getTasksInfo')
  9415. });
  9416. if (action === 'undo') {
  9417. this.socialTasks = GM_getValue(`gleamTasks-${this.giveawayId}`)?.tasks || JSON.parse(Gleam_defaultTasks);
  9418. }
  9419. const tasks = $('.entry-content .entry-method');
  9420. for (const task of tasks) {
  9421. const $task = $(task);
  9422. if (action === 'do' && $task.find('i.fa-question').length === 0) {
  9423. continue;
  9424. }
  9425. const socialIcon = $task.find('.icon-wrapper i');
  9426. const taskInfo = $task.find('.user-links');
  9427. const taskText = taskInfo.text().trim();
  9428. const expandInfo = $task.find('.expandable');
  9429. const aElements = expandInfo.find('a.btn');
  9430. if (aElements.length > 0) {
  9431. for (const element of aElements) {
  9432. const $element = $(element);
  9433. const href = $element.attr('href');
  9434. $element.removeAttr('href')[0].click();
  9435. $element.attr('href', href);
  9436. }
  9437. }
  9438. if (socialIcon.hasClass('fa-twitter') || socialIcon.hasClass('fa-x-twitter')) {
  9439. const link = $task.find('a[href^="https://twitter.com/"],a[href^="https://x.com/"]').attr('href');
  9440. if (!link) {
  9441. continue;
  9442. }
  9443. if (/follow/gi.test(taskText)) {
  9444. if (action === 'undo') {
  9445. this.socialTasks.twitter.userLinks.push(link);
  9446. }
  9447. if (action === 'do') {
  9448. this.undoneTasks.twitter.userLinks.push(link);
  9449. }
  9450. } else if (/retweet/gim.test(taskText)) {
  9451. if (action === 'undo') {
  9452. this.socialTasks.twitter.retweetLinks.push(link);
  9453. }
  9454. if (action === 'do') {
  9455. this.undoneTasks.twitter.retweetLinks.push(link);
  9456. }
  9457. }
  9458. } else if (socialIcon.hasClass('fa-twitch')) {
  9459. if (/follow/gim.test(taskText)) {
  9460. const link = $task.find('a[href^="https://twitch.tv/"]').attr('href');
  9461. if (!link) {
  9462. continue;
  9463. }
  9464. if (action === 'undo') {
  9465. this.socialTasks.twitch.channelLinks.push(link);
  9466. }
  9467. if (action === 'do') {
  9468. this.undoneTasks.twitch.channelLinks.push(link);
  9469. }
  9470. }
  9471. } else if (socialIcon.hasClass('fa-discord')) {
  9472. if (/join/gim.test(taskText)) {
  9473. let link = $task.find('a[href^="https://discord.com/invite/"]').attr('href');
  9474. if (!link) {
  9475. const ggLink = $task.find('a[href^="https://discord.gg/"]').attr('href')?.match(/discord\.gg\/([^/]+)/)?.[1];
  9476. if (!ggLink) {
  9477. continue;
  9478. }
  9479. link = `https://discord.com/invite/${ggLink}`;
  9480. }
  9481. if (action === 'undo') {
  9482. this.socialTasks.discord.serverLinks.push(link);
  9483. }
  9484. if (action === 'do') {
  9485. this.undoneTasks.discord.serverLinks.push(link);
  9486. }
  9487. }
  9488. } else if (socialIcon.hasClass('fa-external-link-square-alt')) {
  9489. continue;
  9490. } else if (socialIcon.hasClass('fa-youtube')) {
  9491. if (/subscribe/gim.test(taskText)) {
  9492. const link = $task.find('a[href^="https://www.youtube.com/channel/"]').attr('href');
  9493. if (!link) {
  9494. continue;
  9495. }
  9496. if (action === 'undo') {
  9497. this.socialTasks.youtube.channelLinks.push(link);
  9498. }
  9499. if (action === 'do') {
  9500. this.undoneTasks.youtube.channelLinks.push(link);
  9501. }
  9502. }
  9503. } else if (socialIcon.attr('class')?.includes('steam')) {
  9504. if (/join.*group/gi.test(taskText)) {
  9505. const link = $task.find('a[href^="https://steamcommunity.com/groups/"]').attr('href');
  9506. if (!link) {
  9507. continue;
  9508. }
  9509. if (action === 'undo') {
  9510. this.socialTasks.steam.groupLinks.push(link);
  9511. }
  9512. if (action === 'do') {
  9513. this.undoneTasks.steam.groupLinks.push(link);
  9514. }
  9515. } else if (/follow.*curator/gi.test(taskText)) {
  9516. const link = $task.find('a[href^="https://store.steampowered.com/curator/"]').attr('href');
  9517. if (!link) {
  9518. continue;
  9519. }
  9520. if (action === 'undo') {
  9521. this.socialTasks.steam.curatorLinks.push(link);
  9522. }
  9523. if (action === 'do') {
  9524. this.undoneTasks.steam.curatorLinks.push(link);
  9525. }
  9526. }
  9527. } else if (socialIcon.hasClass('fa-bullhorn') && /Complete/gi.test(taskText)) {
  9528. if (action !== 'do') {
  9529. continue;
  9530. }
  9531. const gleamLink = await this.#getGleamLink(taskText);
  9532. if (!gleamLink) {
  9533. continue;
  9534. }
  9535. this.undoneTasks.extra.gleam.push(gleamLink);
  9536. } 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 {
  9537. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskText}`);
  9538. }
  9539. }
  9540. logStatus.success();
  9541. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9542. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9543. if (window.DEBUG) {
  9544. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9545. }
  9546. GM_setValue(`gleamTasks-${this.giveawayId}`, {
  9547. tasks: this.socialTasks,
  9548. time: new Date().getTime()
  9549. });
  9550. return true;
  9551. } catch (error) {
  9552. throwError(error, 'Gleam.classifyTask');
  9553. return false;
  9554. }
  9555. }
  9556. async extraDoTask({
  9557. gleam
  9558. }) {
  9559. try {
  9560. const pro = [];
  9561. for (const link of gleam) {
  9562. pro.push(this.#doGleamTask(link));
  9563. }
  9564. return Promise.all(pro).then(() => true);
  9565. } catch (error) {
  9566. throwError(error, 'Gleam.extraDoTask');
  9567. return false;
  9568. }
  9569. }
  9570. async verifyTask() {
  9571. try {
  9572. scripts_echoLog({
  9573. text: `${i18n('verifyingTask')}...`
  9574. });
  9575. const tasks = $('.entry-content .entry-method');
  9576. unsafeWindow._OxA = '_OxA';
  9577. for (const task of tasks) {
  9578. if ($('[campaign-key="campaign.key"]').length > 0) {
  9579. return scripts_echoLog({
  9580. text: i18n('campaign')
  9581. });
  9582. }
  9583. const $task = $(task);
  9584. if ($task.find('i.fa-question').length === 0) {
  9585. continue;
  9586. }
  9587. const taskInfo = $task.find('.user-links');
  9588. taskInfo[0].click();
  9589. const aElements = $task.find('.expandable').find('a.btn');
  9590. if (aElements.length > 0) {
  9591. for (const element of aElements) {
  9592. const $element = $(element);
  9593. const href = $element.attr('href');
  9594. $element.removeAttr('href')[0].click();
  9595. $element.attr('href', href);
  9596. }
  9597. }
  9598. unsafeWindow.$hookTimer?.setSpeed(1e3);
  9599. const visitBtn = $task.find('.expandable').find('span:contains(more seconds),button:contains(more seconds)').filter(':visible');
  9600. if (visitBtn.length > 0 && unsafeWindow.$hookTimer) {
  9601. const newTab = GM_openInTab('', {
  9602. active: true
  9603. });
  9604. await delay(1e3);
  9605. newTab?.close();
  9606. window.focus();
  9607. }
  9608. await delay(3e3);
  9609. unsafeWindow.$hookTimer?.setSpeed(1);
  9610. const expandInfo = $task.find('.expandable');
  9611. const [ input ] = expandInfo.find('input');
  9612. if (input) {
  9613. const evt = new Event('input', {
  9614. bubbles: true,
  9615. cancelable: true,
  9616. composed: true
  9617. });
  9618. const valuelimit = [ ...expandInfo.text().matchAll(/"(.+?)"/g) ].at(-1)?.[1];
  9619. input.value = valuelimit || 'vloot';
  9620. input.dispatchEvent(evt);
  9621. await delay(1e3);
  9622. }
  9623. await this.#checkSync();
  9624. const continueBtn = $task.find('.expandable').find('span:contains(Continue),button:contains(Continue)');
  9625. for (const button of continueBtn) {
  9626. button.click();
  9627. await delay(500);
  9628. await this.#checkSync();
  9629. }
  9630. }
  9631. scripts_echoLog({
  9632. text: i18n('verifiedGleamTasks')
  9633. });
  9634. } catch (error) {
  9635. throwError(error, 'Gleam.verifyTask');
  9636. return false;
  9637. }
  9638. }
  9639. async #checkSync() {
  9640. try {
  9641. return await new Promise(resolve => {
  9642. const checker = setInterval(() => {
  9643. if ($('.entry-content .entry-method i.fa-sync').length === 0) {
  9644. clearInterval(checker);
  9645. resolve(true);
  9646. }
  9647. }, 500);
  9648. });
  9649. } catch (error) {
  9650. throwError(error, 'Gleam.checkSync');
  9651. return false;
  9652. }
  9653. }
  9654. async #doGleamTask(link) {
  9655. try {
  9656. const logStatus = scripts_echoLog({
  9657. text: i18n('doingGleamTask')
  9658. });
  9659. return await new Promise(resolve => {
  9660. GM_openInTab(`${link}?8b07d23f4bfa65f9`, {
  9661. active: true,
  9662. insert: true,
  9663. setParent: true
  9664. }).onclose = () => {
  9665. logStatus.success();
  9666. resolve(true);
  9667. };
  9668. });
  9669. } catch (error) {
  9670. throwError(error, 'Gleam.doGleamTask');
  9671. return false;
  9672. }
  9673. }
  9674. #getGiveawayId() {
  9675. try {
  9676. const giveawayId = window.location.pathname;
  9677. if (giveawayId) {
  9678. this.giveawayId = giveawayId;
  9679. return true;
  9680. }
  9681. scripts_echoLog({
  9682. text: i18n('getFailed', 'GiveawayId')
  9683. });
  9684. return false;
  9685. } catch (error) {
  9686. throwError(error, 'Gleam.getGiveawayId');
  9687. return false;
  9688. }
  9689. }
  9690. async #getGleamLink(title) {
  9691. try {
  9692. const logStatus = scripts_echoLog({
  9693. text: i18n('gettingGleamLink')
  9694. });
  9695. const {
  9696. result,
  9697. statusText,
  9698. status,
  9699. data
  9700. } = await tools_httpRequest({
  9701. url: 'https://www.vloot.io/api/v1/giveaways',
  9702. method: 'GET',
  9703. responseType: 'json'
  9704. });
  9705. if (result === 'Success') {
  9706. if (data?.status === 200 && data?.response?.Success === true && data?.response?.Data) {
  9707. const {
  9708. link
  9709. } = data.response.Data.find(giveaway => title.replace(/[\s]/g, '').toLowerCase().includes(giveaway.title.replace(/[\s]/g, '').toLowerCase())) || {};
  9710. if (link) {
  9711. logStatus.success();
  9712. return link;
  9713. }
  9714. logStatus.error(`Error:${i18n('getLinkFailed')}`);
  9715. return false;
  9716. }
  9717. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9718. return false;
  9719. }
  9720. logStatus.error(`${result}:${statusText}(${status})`);
  9721. return false;
  9722. } catch (error) {
  9723. throwError(error, 'Gleam.getGleamLink');
  9724. return false;
  9725. }
  9726. }
  9727. async #checkLeftKey() {
  9728. try {
  9729. if (!globalOptions.other.checkLeftKey) {
  9730. return true;
  9731. }
  9732. const campaignString = $('div.popup-blocks-container').attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  9733. if (!campaignString) {
  9734. return false;
  9735. }
  9736. const {
  9737. campaign,
  9738. incentive
  9739. } = JSON.parse(campaignString);
  9740. const controllerString = $('div.campaign.reward').attr('ng-init')?.match(/initContestant\(([\w\W]+?)\);/)?.[1];
  9741. let ownedKey = false;
  9742. if (controllerString) {
  9743. if (JSON.parse(controllerString).contestant?.claims?.incentives?.[incentive.id]?.length) {
  9744. ownedKey = true;
  9745. }
  9746. }
  9747. if (campaign.banned || campaign.finished && !ownedKey || campaign.paused || new Date().getTime() < campaign.starts_at * 1e3) {
  9748. await external_Swal_default().fire({
  9749. icon: 'warning',
  9750. title: i18n('notice'),
  9751. text: i18n('giveawayNotWork'),
  9752. confirmButtonText: i18n('confirm'),
  9753. cancelButtonText: i18n('cancel'),
  9754. showCancelButton: true
  9755. }).then(({
  9756. value
  9757. }) => {
  9758. if (value) {
  9759. window.close();
  9760. }
  9761. });
  9762. }
  9763. return true;
  9764. } catch (error) {
  9765. throwError(error, 'Gleam.checkLeftKey');
  9766. return false;
  9767. }
  9768. }
  9769. }
  9770. const website_Gleam = Gleam;
  9771. const SweepWidget_defaultOptions = {
  9772. username: '',
  9773. email: ''
  9774. };
  9775. class SweepWidget extends website_Website {
  9776. name = 'SweepWidget';
  9777. options = {
  9778. ...SweepWidget_defaultOptions,
  9779. ...GM_getValue('SweepWidgetOptions')
  9780. };
  9781. buttons = [ 'doTask' ];
  9782. static test() {
  9783. return /^https?:\/\/sweepwidget\.com\/view\/[\d]+/.test(window.location.href);
  9784. }
  9785. async after() {
  9786. try {
  9787. if (!this.#checkLogin()) {
  9788. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9789. }
  9790. } catch (error) {
  9791. throwError(error, 'SweepWidget.after');
  9792. }
  9793. }
  9794. init() {
  9795. try {
  9796. const logStatus = scripts_echoLog({
  9797. text: i18n('initing')
  9798. });
  9799. if (!this.#checkLogin()) {
  9800. logStatus.warning(i18n('needLogin'));
  9801. return false;
  9802. }
  9803. if (!this.#getGiveawayId()) {
  9804. return false;
  9805. }
  9806. this.initialized = true;
  9807. logStatus.success();
  9808. return true;
  9809. } catch (error) {
  9810. throwError(error, 'SweepWidget.init');
  9811. return false;
  9812. }
  9813. }
  9814. classifyTask() {
  9815. return true;
  9816. }
  9817. async doTask() {
  9818. try {
  9819. if ($('#unlock_rewards_main_wrapper').length === 0) {
  9820. if ($('input[name="sw__login_name"]:visible').length > 0) {
  9821. $('input[name="sw__login_name"]').val(this.options.username);
  9822. }
  9823. if ($('input[name="sw__login_email"]:visible').length > 0) {
  9824. $('input[name="sw__login_email"]').val(this.options.email);
  9825. }
  9826. if ($('#sw_login_button:visible').length > 0) {
  9827. $('#sw_login_button')[0].click();
  9828. }
  9829. if (!await this.#checkEnter()) {
  9830. return false;
  9831. }
  9832. }
  9833. const logStatus = scripts_echoLog({
  9834. text: i18n('SweepWidgetNotice')
  9835. });
  9836. const tasks = $('#sw_inner_entry_methods_l2_wrapper>div.sw_entry');
  9837. for (const task of tasks) {
  9838. const $task = $(task);
  9839. if ($task.find('i.fa-check:visible').length > 0) {
  9840. continue;
  9841. }
  9842. const title = $task.find('.sw_text_inner');
  9843. title[0].click();
  9844. const aElement = $task.find('a.sw_link');
  9845. const link = aElement.attr('href');
  9846. aElement.attr('href', '#a').attr('target', '_self');
  9847. aElement[0]?.click();
  9848. await delay(300);
  9849. aElement.attr('href', link).attr('target', '_blank');
  9850. $task.find('input[type="text"]').val('test');
  9851. const verifyBtn = $task.find('input.sw_verify');
  9852. if (verifyBtn.prop('disabled') === true) {
  9853. title[0].click();
  9854. await delay(300);
  9855. title[0].click();
  9856. await delay(300);
  9857. }
  9858. $task.find('input.sw_verify').removeAttr('disabled')[0]?.click();
  9859. await this.#checkFinish($task);
  9860. await delay(parseInt(`${Math.random() * (3e3 - 1e3 + 1) + 1e3}`, 10));
  9861. }
  9862. logStatus.success();
  9863. return true;
  9864. } catch (error) {
  9865. throwError(error, 'SweepWidget.doTask');
  9866. return false;
  9867. }
  9868. }
  9869. #checkLogin() {
  9870. try {
  9871. if ($('#twitter_login_button').length > 0) {
  9872. $('#twitter_login_button')[0].click();
  9873. }
  9874. return true;
  9875. } catch (error) {
  9876. throwError(error, 'SweepWidget.checkLogin');
  9877. return false;
  9878. }
  9879. }
  9880. #getGiveawayId() {
  9881. try {
  9882. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  9883. if (giveawayId) {
  9884. this.giveawayId = giveawayId;
  9885. return true;
  9886. }
  9887. scripts_echoLog({
  9888. text: i18n('getFailed', 'GiveawayId')
  9889. });
  9890. return false;
  9891. } catch (error) {
  9892. throwError(error, 'SweepWidget.getGiveawayId');
  9893. return false;
  9894. }
  9895. }
  9896. async #checkEnter() {
  9897. try {
  9898. return new Promise(resolve => {
  9899. const checker = setInterval(() => {
  9900. if ($('#unlock_rewards_main_wrapper').length > 0) {
  9901. clearInterval(checker);
  9902. resolve(true);
  9903. }
  9904. }, 500);
  9905. });
  9906. } catch (error) {
  9907. throwError(error, 'SweepWidget.checkEnter');
  9908. return false;
  9909. }
  9910. }
  9911. async #checkFinish($task) {
  9912. try {
  9913. return new Promise(resolve => {
  9914. const checker = setInterval(() => {
  9915. if ($task.find('i.fa-check:visible').length > 0 || $task.find('.sw_entry_input:visible').length === 0) {
  9916. clearInterval(checker);
  9917. resolve(true);
  9918. }
  9919. }, 500);
  9920. });
  9921. } catch (error) {
  9922. throwError(error, 'SweepWidget.checkFinish');
  9923. return false;
  9924. }
  9925. }
  9926. }
  9927. const website_SweepWidget = SweepWidget;
  9928. const defaultWhiteList = {
  9929. discord: {
  9930. servers: []
  9931. },
  9932. instagram: {
  9933. users: []
  9934. },
  9935. twitch: {
  9936. channels: []
  9937. },
  9938. twitter: {
  9939. users: [],
  9940. retweets: [],
  9941. likes: []
  9942. },
  9943. vk: {
  9944. names: []
  9945. },
  9946. youtube: {
  9947. channels: [],
  9948. likes: []
  9949. },
  9950. reddit: {
  9951. reddits: []
  9952. },
  9953. steam: {
  9954. groups: [],
  9955. officialGroups: [],
  9956. wishlists: [],
  9957. follows: [],
  9958. forums: [],
  9959. workshops: [],
  9960. curators: [],
  9961. workshopVotes: [],
  9962. curatorLikes: [],
  9963. announcements: [],
  9964. licenses: [],
  9965. playtests: []
  9966. }
  9967. };
  9968. const link2id = async function(type) {
  9969. try {
  9970. const link = $('#socialLink').val();
  9971. let id = '';
  9972. switch (type) {
  9973. case 'discord.servers':
  9974. id = link.match(/invite\/(.+)/)?.[1] || '';
  9975. break;
  9976.  
  9977. case 'instagram.users':
  9978. id = link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1] || '';
  9979. break;
  9980.  
  9981. case 'twitch.channels':
  9982. id = link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2] || '';
  9983. break;
  9984.  
  9985. case 'twitter.users':
  9986. id = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || '';
  9987. break;
  9988.  
  9989. case 'twitter.retweets':
  9990. id = link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1] || '';
  9991. break;
  9992.  
  9993. case 'vk.names':
  9994. id = link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1] || '';
  9995. break;
  9996.  
  9997. case 'youtube.channels':
  9998. id = (await getInfo(link, 'channel'))?.params?.channelId || '';
  9999. break;
  10000.  
  10001. case 'youtube.likes':
  10002. id = (await getInfo(link, 'likeVideo'))?.params?.videoId || '';
  10003. break;
  10004.  
  10005. case 'reddit.reddits':
  10006. id = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1] || link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1] || '';
  10007. break;
  10008.  
  10009. case 'steam.groups':
  10010. id = link.match(/groups\/(.+)\/?/)?.[1] || '';
  10011. break;
  10012.  
  10013. case 'steam.wishlists':
  10014. case 'steam.follows':
  10015. case 'steam.forums':
  10016. id = link.match(/app\/([\d]+)/)?.[1] || '';
  10017. break;
  10018.  
  10019. case 'steam.workshops':
  10020. id = link.match(/\?id=([\d]+)/)?.[1] || '';
  10021. break;
  10022.  
  10023. case 'steam.curators':
  10024. {
  10025. if (link.includes('curator')) {
  10026. id = link.match(/curator\/([\d]+)/)?.[1] || '';
  10027. } else {
  10028. const param = link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3);
  10029. if (!param || param.length !== 2) {
  10030. break;
  10031. }
  10032. const steam = new social_Steam();
  10033. if (await steam.init()) {
  10034. id = await steam.getCuratorId(param[0], param[1]) || '';
  10035. }
  10036. }
  10037. }
  10038. break;
  10039. }
  10040. return id;
  10041. } catch (error) {
  10042. throwError(error, 'link2id');
  10043. return i18n('getFailed', 'id');
  10044. }
  10045. };
  10046. const disabledType = {
  10047. steam: [ 'workshopVotes', 'curatorLikes', 'announcements' ],
  10048. twitter: [ 'likes' ]
  10049. };
  10050. const assignWhiteList = whiteList => {
  10051. try {
  10052. const newWhiteList = {};
  10053. for (const [ key, value ] of Object.entries(defaultWhiteList)) {
  10054. newWhiteList[key] = {
  10055. ...value,
  10056. ...whiteList[key]
  10057. };
  10058. }
  10059. return newWhiteList;
  10060. } catch (error) {
  10061. throwError(error, 'assignWhiteList');
  10062. return defaultWhiteList;
  10063. }
  10064. };
  10065. const whiteListOptions = function(showType) {
  10066. try {
  10067. const whiteList = assignWhiteList(GM_getValue('whiteList') || {});
  10068. let whiteListOptionsForm = `<form id="whiteListForm" class="auto-task-form">
  10069. <table class="auto-task-table"><thead><tr><td>${i18n('website')}</td><td>${i18n('type')}</td><td>${i18n('edit')}</td></tr></thead><tbody>`;
  10070. for (const [ social, types ] of Object.entries(whiteList)) {
  10071. 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('');
  10072. }
  10073. whiteListOptionsForm += '</tbody></table></form>';
  10074. if (showType === 'swal') {
  10075. external_Swal_default().fire({
  10076. title: i18n('whiteListOptions'),
  10077. html: whiteListOptionsForm,
  10078. showConfirmButton: false,
  10079. showCloseButton: true
  10080. });
  10081. } else {
  10082. $('body').append(`<h2>${i18n('whiteList')}</h2>${whiteListOptionsForm}`);
  10083. }
  10084. $('.editWhiteList').on('click', function() {
  10085. const value = $(this).attr('data-value');
  10086. if (!value) {
  10087. return;
  10088. }
  10089. const [ social, type ] = value.split('.');
  10090. if (!whiteList?.[social]?.[type]) {
  10091. scripts_echoLog({}).warning(i18n('whiteListNotFound', value));
  10092. return;
  10093. }
  10094. external_Swal_default().fire({
  10095. title: i18n('changeWhiteListOption', value),
  10096. input: 'textarea',
  10097. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10098. <button id="link2id" data-type="${value}" class="swal2-confirm swal2-styled">获取id</button>
  10099. <p style="margin-bottom:0 !important;">在下方填写白名单,每行一个</p>`,
  10100. inputValue: whiteList[social][type].join('\n'),
  10101. showConfirmButton: true,
  10102. confirmButtonText: i18n('save'),
  10103. showCancelButton: true,
  10104. cancelButtonText: i18n('close'),
  10105. showDenyButton: true,
  10106. denyButtonText: i18n('return')
  10107. }).then(({
  10108. isDenied,
  10109. isConfirmed,
  10110. value
  10111. }) => {
  10112. if (isDenied) {
  10113. if (showType === 'swal') {
  10114. whiteListOptions(showType);
  10115. }
  10116. return;
  10117. } else if (isConfirmed) {
  10118. whiteList[social][type] = value.split('\n');
  10119. GM_setValue('whiteList', whiteList);
  10120. external_Swal_default().fire({
  10121. title: i18n('changeWhiteListSuccess'),
  10122. icon: 'success'
  10123. });
  10124. }
  10125. });
  10126. $('#link2id').on('click', async function() {
  10127. const type = $(this).attr('data-type');
  10128. $('#socialLink').val(await link2id(type));
  10129. });
  10130. });
  10131. } catch (error) {
  10132. throwError(error, 'whiteListOptions');
  10133. }
  10134. };
  10135. const whiteList = whiteListOptions;
  10136. const setGistData = async (token, gistId, fileName, content) => {
  10137. try {
  10138. const logStatus = scripts_echoLog({
  10139. text: i18n('settingData')
  10140. });
  10141. const contentData = JSON.stringify({
  10142. files: {
  10143. [fileName]: {
  10144. content: JSON.stringify(content)
  10145. }
  10146. }
  10147. });
  10148. const {
  10149. result,
  10150. statusText,
  10151. status,
  10152. data
  10153. } = await tools_httpRequest({
  10154. url: `https://api.github.com/gists/${gistId}`,
  10155. headers: {
  10156. Accept: 'application/vnd.github.v3+json',
  10157. Authorization: `token ${token}`
  10158. },
  10159. data: contentData,
  10160. responseType: 'json',
  10161. method: 'POST',
  10162. timeout: 3e4
  10163. });
  10164. if (result === 'Success') {
  10165. if (data?.status === 200 && data.response.files?.[fileName]?.content === JSON.stringify(content)) {
  10166. logStatus.success();
  10167. return true;
  10168. }
  10169. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10170. return false;
  10171. }
  10172. logStatus.error(`${result}:${statusText}(${status})`);
  10173. return false;
  10174. } catch (error) {
  10175. throwError(error, 'setGistData');
  10176. return false;
  10177. }
  10178. };
  10179. const getGistData = async (token, gistId, fileName, test = false) => {
  10180. try {
  10181. const logStatus = scripts_echoLog({
  10182. text: i18n('gettingData')
  10183. });
  10184. const {
  10185. result,
  10186. statusText,
  10187. status,
  10188. data
  10189. } = await tools_httpRequest({
  10190. url: `https://api.github.com/gists/${gistId}`,
  10191. headers: {
  10192. Accept: 'application/vnd.github.v3+json',
  10193. Authorization: `token ${token}`
  10194. },
  10195. responseType: 'json',
  10196. method: 'GET',
  10197. timeout: 3e4
  10198. });
  10199. if (result === 'Success') {
  10200. if (data?.status === 200) {
  10201. const content = data.response?.files?.[fileName]?.content;
  10202. let formatedContent;
  10203. if (!content) {
  10204. logStatus.error(`Error:${i18n('noRemoteData')}`);
  10205. return false;
  10206. }
  10207. if (test) {
  10208. logStatus.success();
  10209. return true;
  10210. }
  10211. try {
  10212. formatedContent = JSON.parse(content);
  10213. } catch (error) {
  10214. logStatus.error(`Error:${i18n('errorRemoteDataFormat')}`);
  10215. return false;
  10216. }
  10217. logStatus.success();
  10218. return formatedContent;
  10219. }
  10220. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10221. return false;
  10222. }
  10223. logStatus.error(`${result}:${statusText}(${status})`);
  10224. return false;
  10225. } catch (error) {
  10226. throwError(error, 'getGistData');
  10227. return false;
  10228. }
  10229. };
  10230. const syncOptions = () => {
  10231. try {
  10232. const {
  10233. TOKEN,
  10234. GIST_ID,
  10235. FILE_NAME,
  10236. SYNC_HISTORY
  10237. } = GM_getValue('gistOptions') || {
  10238. TOKEN: '',
  10239. GIST_ID: '',
  10240. FILE_NAME: '',
  10241. SYNC_HISTORY: true
  10242. };
  10243. external_Swal_default().fire({
  10244. title: i18n('gistOptions'),
  10245. 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;">
  10246. ${i18n('upload2gist')}</button>` + `<button id="download-data" type="button" class="swal2-confirm swal2-styled" style="display: inline-block;">
  10247. ${i18n('downloadFromGist')}</button></p>`,
  10248. focusConfirm: false,
  10249. showLoaderOnConfirm: true,
  10250. 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>`,
  10251. preConfirm: async () => {
  10252. const token = $('#github-token').val();
  10253. const gistId = $('#gist-id').val();
  10254. const fileName = $('#file-name').val();
  10255. const syncHistory = $('#sync-history').prop('checked');
  10256. GM_setValue('gistOptions', {
  10257. TOKEN: token,
  10258. GIST_ID: gistId,
  10259. FILE_NAME: fileName,
  10260. SYNC_HISTORY: syncHistory
  10261. });
  10262. return await getGistData(token, gistId, fileName, true);
  10263. },
  10264. allowOutsideClick: () => !external_Swal_default().isLoading(),
  10265. confirmButtonText: i18n('saveAndTest'),
  10266. showCancelButton: true,
  10267. cancelButtonText: i18n('close')
  10268. }).then(({
  10269. value
  10270. }) => {
  10271. if (value) {
  10272. external_Swal_default().fire({
  10273. icon: 'success',
  10274. title: i18n('testSuccess')
  10275. }).then(syncOptions);
  10276. } else if (value !== undefined) {
  10277. external_Swal_default().fire({
  10278. icon: 'error',
  10279. title: i18n('testFailed')
  10280. }).then(syncOptions);
  10281. }
  10282. });
  10283. $('#upload-data').on('click', async () => {
  10284. const {
  10285. TOKEN,
  10286. GIST_ID,
  10287. FILE_NAME
  10288. } = GM_getValue('gistOptions') || {};
  10289. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10290. return external_Swal_default().fire({
  10291. icon: 'error',
  10292. title: i18n('saveAndTestNotice')
  10293. }).then(syncOptions);
  10294. }
  10295. external_Swal_default().fire({
  10296. icon: 'info',
  10297. title: i18n('processingData')
  10298. });
  10299. const data = {};
  10300. const names = GM_listValues();
  10301. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10302. for (const name of names) {
  10303. if (name === 'gistOptions' || /^[\w]+?Auth$/.test(name)) {
  10304. continue;
  10305. }
  10306. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10307. continue;
  10308. }
  10309. data[name] = GM_getValue(name);
  10310. }
  10311. external_Swal_default().update({
  10312. icon: 'info',
  10313. title: i18n('updatingData')
  10314. });
  10315. if (await setGistData(TOKEN, GIST_ID, FILE_NAME, data)) {
  10316. external_Swal_default().fire({
  10317. icon: 'success',
  10318. title: i18n('syncDataSuccess')
  10319. });
  10320. } else {
  10321. external_Swal_default().fire({
  10322. icon: 'error',
  10323. title: i18n('syncDataFailed')
  10324. });
  10325. }
  10326. });
  10327. $('#download-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('downloadingData')
  10342. });
  10343. const data = await getGistData(TOKEN, GIST_ID, FILE_NAME);
  10344. if (!data) {
  10345. return external_Swal_default().fire({
  10346. icon: 'error',
  10347. title: i18n('checkedNoData')
  10348. }).then(syncOptions);
  10349. }
  10350. external_Swal_default().update({
  10351. icon: 'info',
  10352. title: i18n('savingData')
  10353. });
  10354. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10355. for (const [ name, value ] of Object.entries(data)) {
  10356. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10357. continue;
  10358. }
  10359. GM_setValue(name, value);
  10360. }
  10361. external_Swal_default().fire({
  10362. icon: 'success',
  10363. title: i18n('syncDataSuccess')
  10364. });
  10365. });
  10366. } catch (error) {
  10367. throwError(error, 'syncOptions');
  10368. }
  10369. };
  10370. const dataSync = syncOptions;
  10371. class Setting {
  10372. name = 'Setting';
  10373. buttons = [ 'saveGlobalOptions', 'syncData', 'tasksHistory' ];
  10374. syncData = dataSync;
  10375. tasksHistory() {
  10376. GM_openInTab('https://auto-task-v4.hclonely.com/history.html', {
  10377. active: true
  10378. });
  10379. }
  10380. static test() {
  10381. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/setting.html';
  10382. }
  10383. before() {
  10384. try {
  10385. $('body').html('').addClass('auto-task-options');
  10386. } catch (error) {
  10387. throwError(error, 'Setting.before');
  10388. }
  10389. }
  10390. after() {
  10391. try {
  10392. this.#environment();
  10393. changeGlobalOptions('page');
  10394. whiteList('page');
  10395. $('input[name="other.twitterVerifyId"]').after(`<button id="getTwitterUserId" type="button">${i18n('getTwitterUserId')}</button>`);
  10396. $('#getTwitterUserId').on('click', () => {
  10397. this.#getId('twitterUser');
  10398. });
  10399. $('input[name="other.youtubeVerifyChannel"]').after(`<button id="getYoutubeChannelId" type="button">${i18n('getYoutubeChannelId')}</button>`);
  10400. $('#getYoutubeChannelId').on('click', () => {
  10401. this.#getId('youtubeChannel');
  10402. });
  10403. $('input[name^="position"]').on('input', function() {
  10404. const type = $(this).attr('name').replace('position.', '');
  10405. const xLabel = 'rightleft';
  10406. const yLabel = 'topbottpm';
  10407. switch (type) {
  10408. case 'buttonSideX':
  10409. case 'buttonSideY':
  10410. case 'buttonDistance':
  10411. {
  10412. const distance = $('input[name="position.buttonDistance"]').val();
  10413. const sideX = $('input[name="position.buttonSideX"]').val();
  10414. const sideY = $('input[name="position.buttonSideY"]').val();
  10415. if (![ 'right', 'left' ].includes(sideX)) {
  10416. break;
  10417. }
  10418. if (![ 'top', 'bottom' ].includes(sideY)) {
  10419. break;
  10420. }
  10421. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10422. break;
  10423. }
  10424. const distanceArr = distance.split(',');
  10425. $('#auto-task-buttons').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10426. break;
  10427. }
  10428.  
  10429. case 'showButtonSideX':
  10430. case 'showButtonSideY':
  10431. case 'showButtonDistance':
  10432. {
  10433. const distance = $('input[name="position.showButtonDistance"]').val();
  10434. const sideX = $('input[name="position.showButtonSideX"]').val();
  10435. const sideY = $('input[name="position.showButtonSideY"]').val();
  10436. if (![ 'right', 'left' ].includes(sideX)) {
  10437. break;
  10438. }
  10439. if (![ 'top', 'bottom' ].includes(sideY)) {
  10440. break;
  10441. }
  10442. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10443. break;
  10444. }
  10445. const distanceArr = distance.split(',');
  10446. $('div.show-button-div').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10447. break;
  10448. }
  10449.  
  10450. case 'logSideX':
  10451. case 'logSideY':
  10452. case 'logDistance':
  10453. {
  10454. const distance = $('input[name="position.logDistance"]').val();
  10455. const sideX = $('input[name="position.logSideX"]').val();
  10456. const sideY = $('input[name="position.logSideY"]').val();
  10457. if (![ 'right', 'left' ].includes(sideX)) {
  10458. break;
  10459. }
  10460. if (![ 'top', 'bottom' ].includes(sideY)) {
  10461. break;
  10462. }
  10463. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10464. break;
  10465. }
  10466. const distanceArr = distance.split(',');
  10467. $('#auto-task-info').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10468. break;
  10469. }
  10470.  
  10471. default:
  10472. break;
  10473. }
  10474. });
  10475. $('input[name^="hotKey"]').attr('readonly', 'readonly').off('keydown').on('keydown', function(event) {
  10476. let functionKey = '';
  10477. if (event.altKey) {
  10478. functionKey += 'alt + ';
  10479. } else if (event.ctrlKey) {
  10480. functionKey += 'ctrl + ';
  10481. } else if (event.shiftKey) {
  10482. functionKey += 'shift + ';
  10483. }
  10484. $(this).val(functionKey + (event.key.length === 1 ? event.key.toLowerCase() : ''));
  10485. });
  10486. } catch (error) {
  10487. throwError(error, 'Setting.after');
  10488. }
  10489. }
  10490. saveGlobalOptions() {
  10491. try {
  10492. saveData();
  10493. } catch (error) {
  10494. throwError(error, 'Setting.saveGlobalOptions');
  10495. }
  10496. }
  10497. #getId(social) {
  10498. try {
  10499. external_Swal_default().fire({
  10500. title: i18n('getId', i18n(social)),
  10501. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10502. <button id="link2id" data-type="${social}" class="swal2-confirm swal2-styled">获取id</button>`,
  10503. showCancelButton: true,
  10504. cancelButtonText: i18n('close'),
  10505. showConfirmButton: false
  10506. });
  10507. $('#link2id').on('click', async function() {
  10508. const link = $('#socialLink').val();
  10509. if (!link) {
  10510. return;
  10511. }
  10512. const type = $(this).attr('data-type');
  10513. if (type === 'twitterUser') {
  10514. const name = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || link;
  10515. $('#socialLink').val(await new social_Twitter().userName2id(name) || '');
  10516. } else if (type === 'youtubeChannel') {
  10517. const name = /^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www.youtube.com\/.*/.test(link) ? link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1] : link;
  10518. $('#socialLink').val((await getInfo(name, 'channel'))?.params?.channelId || '');
  10519. }
  10520. });
  10521. } catch (error) {
  10522. throwError(error, 'Setting.getId');
  10523. }
  10524. }
  10525. #environment() {
  10526. try {
  10527. const userAgent = (0, javascript_utils_umd_min.ua)();
  10528. const environmentForm = `<form id="environmentForm" class="auto-task-form">
  10529. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('name')}</td><td>${i18n('version')}</td></tr></thead><tbody>
  10530. <tr><td>${i18n('os')}</td><td>${userAgent.os}</td><td>${userAgent.osVersion}</td></tr>
  10531. <tr><td>${i18n('browser')}</td><td>${userAgent.browserZH}</td><td>${userAgent.browserVersion}</td></tr>
  10532. <tr><td>${i18n('scriptManager')}</td><td>${GM_info.scriptHandler}</td><td>${GM_info.version}</td></tr>
  10533. <tr><td>${i18n('script')}</td><td>${GM_info.script.name}</td><td>${GM_info.script.version}</td></tr>
  10534. </tbody></table></form>`;
  10535. $('body').append(`<h2>${i18n('environment')}</h2>${environmentForm}`);
  10536. } catch (error) {
  10537. throwError(error, 'Setting.environment');
  10538. }
  10539. }
  10540. }
  10541. const website_Setting = Setting;
  10542. class History extends website_Keylol {
  10543. name = 'History';
  10544. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect', 'clearHistory' ];
  10545. static test() {
  10546. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/history.html';
  10547. }
  10548. before() {
  10549. try {
  10550. $('body').html('<div class="container"></div>').addClass('auto-task-history');
  10551. const data = GM_listValues() || [];
  10552. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  10553. for (const item of tasksHistory) {
  10554. this.#addItem(item);
  10555. }
  10556. } catch (error) {
  10557. throwError(error, 'History.before');
  10558. }
  10559. }
  10560. clearHistory() {
  10561. try {
  10562. const data = GM_listValues() || [];
  10563. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  10564. for (const item of tasksHistory) {
  10565. GM_deleteValue(item);
  10566. }
  10567. external_Swal_default().fire({
  10568. title: i18n('clearHistoryFinished'),
  10569. icon: 'success'
  10570. });
  10571. } catch (error) {
  10572. throwError(error, 'History.clearHistory');
  10573. }
  10574. }
  10575. #addItem(item) {
  10576. try {
  10577. const tasksData = GM_getValue(item);
  10578. if (!tasksData?.tasks) {
  10579. return;
  10580. }
  10581. let html = '';
  10582. let title = '';
  10583. let link = '';
  10584. const [ website, id ] = item.split('-');
  10585. switch (website) {
  10586. case 'fawTasks':
  10587. title = `Freeanywhere[${id}]`;
  10588. link = `https://freeanywhere.net/#/giveaway/${id}`;
  10589. break;
  10590.  
  10591. case 'gasTasks':
  10592. title = `Giveawaysu[${id}]`;
  10593. link = `https://giveaway.su/giveaway/view/${id}`;
  10594. break;
  10595.  
  10596. case 'gcTasks':
  10597. title = `GiveeClub[${id}]`;
  10598. link = `https://givee.club/event/${id}`;
  10599. break;
  10600.  
  10601. case 'gkTasks':
  10602. title = `Givekey[${id}]`;
  10603. link = `https://givekey.ru/giveaway/${id}`;
  10604. break;
  10605.  
  10606. case 'gleamTasks':
  10607. title = `Gleam[${id}]`;
  10608. link = `https://gleam.io${id}`;
  10609. break;
  10610.  
  10611. case 'khTasks':
  10612. title = `keyhub[${id}]`;
  10613. link = `https://key-hub.eu/giveaway/${id}`;
  10614. break;
  10615.  
  10616. case 'prysTasks':
  10617. title = `Prys[${id}]`;
  10618. link = `https://prys.revadike.com/giveaway/?id=${id}`;
  10619. break;
  10620.  
  10621. default:
  10622. return;
  10623. }
  10624. for (const [ social, types ] of Object.entries(tasksData.tasks)) {
  10625. for (const [ type, tasks ] of Object.entries(types)) {
  10626. for (const task of tasks) {
  10627. 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>`;
  10628. }
  10629. }
  10630. }
  10631. $('.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>`);
  10632. $('span.delete-task').on('click', function() {
  10633. const itemName = $(this).attr('data-name');
  10634. if (itemName) {
  10635. GM_deleteValue(itemName);
  10636. $(`div.card[data-name="${itemName}"]`).remove();
  10637. external_Swal_default().fire({
  10638. title: i18n('clearTaskFinished'),
  10639. text: itemName,
  10640. icon: 'success'
  10641. });
  10642. } else {
  10643. external_Swal_default().fire({
  10644. title: i18n('clearTaskFailed'),
  10645. icon: 'error'
  10646. });
  10647. }
  10648. });
  10649. } catch (error) {
  10650. throwError(error, 'History.addItem');
  10651. }
  10652. }
  10653. }
  10654. const website_History = History;
  10655. const GiveawayHopper_defaultTasksTemplate = {
  10656. steam: {
  10657. groupLinks: [],
  10658. wishlistLinks: [],
  10659. followLinks: [],
  10660. curatorLinks: [],
  10661. curatorLikeLinks: []
  10662. },
  10663. twitter: {
  10664. userLinks: [],
  10665. retweetLinks: []
  10666. },
  10667. twitch: {
  10668. channelLinks: []
  10669. },
  10670. discord: {
  10671. serverLinks: []
  10672. },
  10673. youtube: {
  10674. channelLinks: []
  10675. },
  10676. extra: {
  10677. giveawayHopper: []
  10678. }
  10679. };
  10680. const GiveawayHopper_defaultTasks = JSON.stringify(GiveawayHopper_defaultTasksTemplate);
  10681. class GiveawayHopper extends website_Website {
  10682. name = 'GiveawayHopper';
  10683. undoneTasks = JSON.parse(GiveawayHopper_defaultTasks);
  10684. socialTasks = JSON.parse(GiveawayHopper_defaultTasks);
  10685. tasks = [];
  10686. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  10687. static test() {
  10688. return window.location.host === 'giveawayhopper.com';
  10689. }
  10690. async after() {
  10691. try {
  10692. if (!this.#checkLogin()) {
  10693. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  10694. }
  10695. this.#getGiveawayId();
  10696. } catch (error) {
  10697. throwError(error, 'GiveawayHopper.after');
  10698. }
  10699. }
  10700. async init() {
  10701. try {
  10702. const logStatus = scripts_echoLog({
  10703. text: i18n('initing')
  10704. });
  10705. if (!await this.#checkLeftKey()) {
  10706. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  10707. }
  10708. this.initialized = true;
  10709. logStatus.success();
  10710. return true;
  10711. } catch (error) {
  10712. throwError(error, 'GiveawayHopper.init');
  10713. return false;
  10714. }
  10715. }
  10716. async classifyTask(action) {
  10717. try {
  10718. if (!this.giveawayId) {
  10719. await this.#getGiveawayId();
  10720. }
  10721. const logStatus = scripts_echoLog({
  10722. text: i18n('getTasksInfo')
  10723. });
  10724. if (action === 'undo') {
  10725. this.socialTasks = GM_getValue(`giveawayHopperTasks-${this.giveawayId}`)?.tasks || JSON.parse(GiveawayHopper_defaultTasks);
  10726. }
  10727. const {
  10728. result,
  10729. statusText,
  10730. status,
  10731. data
  10732. } = await tools_httpRequest({
  10733. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/with-auth`,
  10734. method: 'GET',
  10735. responseType: 'json',
  10736. fetch: true,
  10737. headers: {
  10738. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10739. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10740. }
  10741. });
  10742. if (result === 'Success') {
  10743. if (data?.status === 200 && data?.response?.tasks) {
  10744. this.tasks = data.response.tasks;
  10745. for (const task of data.response.tasks) {
  10746. if (task.isDone) {
  10747. continue;
  10748. }
  10749. await tools_httpRequest({
  10750. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/visited`,
  10751. method: 'GET',
  10752. responseType: 'json',
  10753. fetch: true,
  10754. headers: {
  10755. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10756. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10757. }
  10758. });
  10759. if (task.category === 'Steam' && task.type === 'JoinGroup') {
  10760. const steamGroupLink = await getRedirectLink(`https://steamcommunity.com/gid/${task.group_id}`);
  10761. if (!steamGroupLink) {
  10762. continue;
  10763. }
  10764. if (action === 'undo') {
  10765. this.socialTasks.steam.groupLinks.push(steamGroupLink);
  10766. }
  10767. if (action === 'do') {
  10768. this.undoneTasks.steam.groupLinks.push(steamGroupLink);
  10769. }
  10770. continue;
  10771. }
  10772. if (task.category === 'Discord' && task.type === 'JoinServer') {
  10773. if (action === 'undo') {
  10774. this.socialTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  10775. }
  10776. if (action === 'do') {
  10777. this.undoneTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  10778. }
  10779. continue;
  10780. }
  10781. if ([ 'TikTok', 'YouTube', 'General' ].includes(task.category)) {
  10782. continue;
  10783. }
  10784. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${task.category}-${task.type}`);
  10785. }
  10786. logStatus.success();
  10787. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  10788. this.socialTasks = this.uniqueTasks(this.socialTasks);
  10789. if (window.DEBUG) {
  10790. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  10791. }
  10792. GM_setValue(`giveawayHopperTasks-${this.giveawayId}`, {
  10793. tasks: this.socialTasks,
  10794. time: new Date().getTime()
  10795. });
  10796. return true;
  10797. }
  10798. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10799. return false;
  10800. }
  10801. logStatus.error(`${result}:${statusText}(${status})`);
  10802. return false;
  10803. } catch (error) {
  10804. throwError(error, 'GiveawayHopper.classifyTask');
  10805. return false;
  10806. }
  10807. }
  10808. async verifyTask() {
  10809. try {
  10810. for (const task of this.tasks) {
  10811. if (task.isDone) {
  10812. continue;
  10813. }
  10814. const logStatus = scripts_echoLog({
  10815. text: `${i18n('verifyingTask')}[${task.displayName?.replace(':target', task.targetName) || task.name}]...`
  10816. });
  10817. if (!task.link) {
  10818. if (task.category === 'YouTube' && task.type === 'FollowAccount') {
  10819. task.link = `https://www.youtube.com/@${task.targetName}`;
  10820. } else if (task.category === 'TikTok' && task.type === 'FollowAccount') {
  10821. task.link = `https://www.tiktok.com/@${task.targetName}`;
  10822. } else if (task.category === 'Steam' && task.type === 'JoinGroup') {
  10823. task.link = '';
  10824. } else if (task.category === 'Discord' && task.type === 'JoinServer') {
  10825. task.link = '';
  10826. }
  10827. }
  10828. if (task.link) {
  10829. await tools_httpRequest({
  10830. 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}`,
  10831. method: 'GET',
  10832. fetch: true,
  10833. headers: {
  10834. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10835. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10836. }
  10837. });
  10838. }
  10839. await delay(1e3);
  10840. const postData = {
  10841. taskcategory: task.category,
  10842. taskname: task.type
  10843. };
  10844. if ([ 'YouTube', 'TikTok' ].includes(task.category)) {
  10845. postData.username = '1';
  10846. }
  10847. const {
  10848. result,
  10849. statusText,
  10850. status,
  10851. data
  10852. } = await tools_httpRequest({
  10853. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/complete`,
  10854. method: 'POST',
  10855. fetch: true,
  10856. headers: {
  10857. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10858. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1]),
  10859. 'content-type': 'application/json'
  10860. },
  10861. dataType: 'json',
  10862. data: JSON.stringify(postData)
  10863. });
  10864. if (result === 'Success') {
  10865. if (data?.status === 200 && data?.response?.completed) {
  10866. logStatus.success();
  10867. continue;
  10868. }
  10869. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10870. continue;
  10871. }
  10872. logStatus.error(`${result}:${statusText}(${status})`);
  10873. continue;
  10874. }
  10875. } catch (error) {
  10876. throwError(error, 'GiveawayHopper.verifyTask');
  10877. return false;
  10878. }
  10879. }
  10880. #getGiveawayId() {
  10881. try {
  10882. const giveawayId = window.location.pathname.split('/').at(-1);
  10883. if (giveawayId) {
  10884. this.giveawayId = giveawayId;
  10885. return true;
  10886. }
  10887. scripts_echoLog({
  10888. text: i18n('getFailed', 'GiveawayId')
  10889. });
  10890. return false;
  10891. } catch (error) {
  10892. throwError(error, 'GiveawayHopper.getGiveawayId');
  10893. return false;
  10894. }
  10895. }
  10896. #checkLogin() {
  10897. try {
  10898. if (!globalOptions.other.checkLogin) {
  10899. return true;
  10900. }
  10901. if ($('div.widget-connections-edit:contains("Log in")').length > 0) {
  10902. $('div.widget-connections-edit:contains("Log in") a')[0].click();
  10903. }
  10904. return true;
  10905. } catch (error) {
  10906. throwError(error, 'GiveawayHopper.checkLogin');
  10907. return false;
  10908. }
  10909. }
  10910. async #checkLeftKey() {
  10911. try {
  10912. if (!globalOptions.other.checkLeftKey) {
  10913. return true;
  10914. }
  10915. if ($('p.widget-single-prize span').length > 0 && parseInt($('p.widget-single-prize span').text()?.match(/\d+/)?.[0] || '0', 10) > 0) {
  10916. return true;
  10917. }
  10918. await external_Swal_default().fire({
  10919. icon: 'warning',
  10920. title: i18n('notice'),
  10921. text: i18n('noKeysLeft'),
  10922. confirmButtonText: i18n('confirm'),
  10923. cancelButtonText: i18n('cancel'),
  10924. showCancelButton: true
  10925. }).then(({
  10926. value
  10927. }) => {
  10928. if (value) {
  10929. window.close();
  10930. }
  10931. });
  10932. return true;
  10933. } catch (error) {
  10934. throwError(error, 'GiveawayHopper.checkLeftKey');
  10935. return false;
  10936. }
  10937. }
  10938. }
  10939. const website_GiveawayHopper = GiveawayHopper;
  10940. 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 ];
  10941. const websiteOptions = function(website, options) {
  10942. try {
  10943. let websiteOptionsForm = `<form id="websiteOptionsForm" class="auto-task-form">
  10944. <table class="auto-task-table"><thead><tr><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  10945. for (const [ option, value ] of Object.entries(options)) {
  10946. websiteOptionsForm += `<tr><td>${option}</td><td><input class="editOption" type="text" name="${option}" value="${value}"/></td></tr>`;
  10947. }
  10948. websiteOptionsForm += '</tbody></table></form>';
  10949. external_Swal_default().fire({
  10950. title: i18n('websiteOptions'),
  10951. html: websiteOptionsForm,
  10952. showConfirmButton: true,
  10953. confirmButtonText: i18n('save'),
  10954. showCancelButton: true,
  10955. cancelButtonText: i18n('close')
  10956. }).then(({
  10957. isConfirmed
  10958. }) => {
  10959. if (isConfirmed) {
  10960. $('#websiteOptionsForm').serializeArray().map(value => {
  10961. options[value.name] = value.value;
  10962. return value;
  10963. });
  10964. GM_setValue(`${website}Options`, options);
  10965. external_Swal_default().fire({
  10966. title: i18n('changeWebsiteOptionsSuccess'),
  10967. icon: 'success'
  10968. });
  10969. }
  10970. });
  10971. } catch (error) {
  10972. throwError(error, 'websiteOptions');
  10973. }
  10974. };
  10975. const options = websiteOptions;
  10976. const external_keyboardJS_namespaceObject = keyboardJS;
  10977. var external_keyboardJS_default = __webpack_require__.n(external_keyboardJS_namespaceObject);
  10978. const checkUpdate = async (updateLink, auto) => {
  10979. try {
  10980. const checkUrl = `${updateLink}package.json?time=${new Date().getTime()}`;
  10981. const {
  10982. result,
  10983. statusText,
  10984. status,
  10985. data
  10986. } = await tools_httpRequest({
  10987. url: checkUrl,
  10988. responseType: 'json',
  10989. method: 'GET',
  10990. timeout: 3e4
  10991. });
  10992. if (result === 'Success') {
  10993. if (data?.response?.version) {
  10994. return data.response;
  10995. }
  10996. if (!auto) {
  10997. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${data?.statusText}(${data?.status})]`);
  10998. }
  10999. return false;
  11000. }
  11001. if (!auto) {
  11002. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${result}:${statusText}(${status})]`);
  11003. }
  11004. return false;
  11005. } catch (error) {
  11006. throwError(error, 'checkUpdate');
  11007. return false;
  11008. }
  11009. };
  11010. const hasNewVersion = (currentVersion, remoteVersion) => {
  11011. try {
  11012. const [ currentRealVersion ] = currentVersion.split('-');
  11013. const [ remoteRealVersion, isPreview ] = remoteVersion.split('-');
  11014. if (isPreview && !globalOptions.other.receivePreview) {
  11015. return false;
  11016. }
  11017. const [ currentVersion1, currentVersion2, currentVersion3 ] = currentRealVersion.split('.').map(value => parseInt(value, 10));
  11018. const [ remoteVersion1, remoteVersion2, remoteVersion3 ] = remoteRealVersion.split('.').map(value => parseInt(value, 10));
  11019. if (remoteVersion1 > currentVersion1) {
  11020. return true;
  11021. }
  11022. if (remoteVersion1 < currentVersion1) {
  11023. return false;
  11024. }
  11025. if (remoteVersion2 > currentVersion2) {
  11026. return true;
  11027. }
  11028. if (remoteVersion2 < currentVersion2) {
  11029. return false;
  11030. }
  11031. if (remoteVersion3 > currentVersion3) {
  11032. return true;
  11033. }
  11034. return false;
  11035. } catch (error) {
  11036. throwError(error, 'compareVersion');
  11037. return false;
  11038. }
  11039. };
  11040. const updateChecker = async () => {
  11041. try {
  11042. const currentVersion = GM_info.script.version;
  11043. const updateSource = globalOptions.other.autoUpdateSource.toLowerCase();
  11044. const updateLinks = {
  11045. github: 'https://github.com/HCLonely/auto-task-new/raw/main/',
  11046. jsdelivr: 'https://cdn.jsdelivr.net/gh/HCLonely/auto-task-v4@main/',
  11047. standby: 'https://auto-task-v4.hclonely.com/'
  11048. };
  11049. let version;
  11050. let updateLink = '';
  11051. let packageData;
  11052. if ([ 'github', 'jsdelivr', 'standby' ].includes(updateSource)) {
  11053. updateLink = updateLinks[updateSource];
  11054. packageData = await checkUpdate(updateLink, false);
  11055. } else {
  11056. updateLink = updateLinks.github;
  11057. packageData = await checkUpdate(updateLink, true);
  11058. if (!packageData) {
  11059. updateLink = updateLinks.jsdelivr;
  11060. packageData = await checkUpdate(updateLink, true);
  11061. if (!packageData) {
  11062. updateLink = updateLinks.standby;
  11063. packageData = await checkUpdate(updateLink, true);
  11064. }
  11065. }
  11066. }
  11067. if (packageData) {
  11068. version = packageData.version || currentVersion;
  11069. } else {
  11070. version = currentVersion;
  11071. scripts_echoLog({}).error(i18n('checkUpdateFailed'));
  11072. }
  11073. if (packageData && hasNewVersion(currentVersion, version)) {
  11074. scripts_echoLog({
  11075. html: `<li><font>${i18n('newVersionNotice', version, `${updateLink}dist/${GM_info.script.name}.user.js`)}</font></li>`
  11076. });
  11077. scripts_echoLog({
  11078. html: `<li>${i18n('updateText', version)}</li><ol class="update-text">${packageData.change?.map(change => `<li>${change}</li>`).join('')}<li>${i18n('updateHistory')}</li></ol>`
  11079. });
  11080. }
  11081. } catch (error) {
  11082. throwError(error, 'updateChecker');
  11083. }
  11084. };
  11085. const scripts_updateChecker = updateChecker;
  11086. window.STYLE = GM_addStyle(auto_task.A + GM_getResourceText('style'));
  11087. window.DEBUG = !!globalOptions.other?.debug;
  11088. window.TRACE = !!globalOptions.other?.debug && typeof console.trace === 'function';
  11089. const loadScript = async () => {
  11090. if (window.name === 'ATv4_twitchAuth' && window.location.hostname === 'www.twitch.tv') {
  11091. const authToken = external_Cookies_default().get('auth-token');
  11092. const isLogin = !!external_Cookies_default().get('login');
  11093. if (isLogin) {
  11094. GM_setValue('twitchAuth', {
  11095. authToken: authToken,
  11096. clientVersion: __twilightBuildID,
  11097. clientId: commonOptions?.headers?.['Client-ID'],
  11098. deviceId: commonOptions?.headers?.['Device-ID'],
  11099. clientSessionId: window.localStorage.local_storage_app_session_id.replace(/"/g, '')
  11100. });
  11101. window.close();
  11102. external_Swal_default().fire('', i18n('closePageNotice'));
  11103. } else {
  11104. external_Swal_default().fire('', i18n('needLogin'));
  11105. }
  11106. return;
  11107. }
  11108. if (window.name === 'ATv4_redditAuth' && window.location.hostname === 'www.reddit.com') {
  11109. const betaButton = $('#redesign-beta-optin-btn');
  11110. if (betaButton.length > 0) {
  11111. return betaButton[0].click();
  11112. }
  11113. window.close();
  11114. external_Swal_default().fire('', i18n('closePageNotice'));
  11115. return;
  11116. }
  11117. let website;
  11118. for (const Website of Websites) {
  11119. if (Website.test()) {
  11120. website = new Website();
  11121. break;
  11122. }
  11123. }
  11124. if (!website) {
  11125. console.log('%c%s', 'color:#ff0000', 'Auto-Task[Warning]: 脚本停止加载,当前网站不支持!');
  11126. return;
  11127. }
  11128. if (website?.before) {
  11129. await website?.before();
  11130. }
  11131. $('body').append(`
  11132. <div id="auto-task-info"
  11133. style="display:${globalOptions.other.defaultShowLog ? 'block' : 'none'};
  11134. ${globalOptions.position.logSideX}:${globalOptions.position.logDistance.split(',')[0]}px;
  11135. ${globalOptions.position.logSideY}:${globalOptions.position.logDistance.split(',')[1]}px;">
  11136. </div>
  11137. <div id="auto-task-buttons"
  11138. style="display:${globalOptions.other.defaultShowButton ? 'block' : 'none'};
  11139. ${globalOptions.position.buttonSideX}:${globalOptions.position.buttonDistance.split(',')[0]}px;
  11140. ${globalOptions.position.buttonSideY}:${globalOptions.position.buttonDistance.split(',')[1]}px;">
  11141. </div>
  11142. <div class="show-button-div"
  11143. style="display:${globalOptions.other.defaultShowButton ? 'none' : 'block'};
  11144. ${globalOptions.position.showButtonSideX}:${globalOptions.position.showButtonDistance.split(',')[0]}px;
  11145. ${globalOptions.position.showButtonSideY}:${globalOptions.position.showButtonDistance.split(',')[1]}px;">
  11146. <a class="auto-task-website-btn"
  11147. href="javascript:void(0);"
  11148. target="_self"
  11149. title="${i18n('showButton')}"> </a>
  11150. </div>
  11151. `);
  11152. $('div.show-button-div').on('click', () => {
  11153. $('#auto-task-buttons').show();
  11154. $('div.show-button-div').hide();
  11155. });
  11156. const toggleLog = () => {
  11157. const $this = $('#toggle-log');
  11158. const status = $this.attr('data-status');
  11159. if (status === 'show') {
  11160. $('#auto-task-info').hide();
  11161. $this.attr('data-status', 'hide').text(i18n('showLog'));
  11162. } else {
  11163. $('#auto-task-info').show();
  11164. $this.attr('data-status', 'show').text(i18n('hideLog'));
  11165. }
  11166. };
  11167. external_keyboardJS_default().bind(globalOptions.hotKey.doTaskKey, () => {
  11168. if (website.doTask) {
  11169. website.doTask();
  11170. }
  11171. });
  11172. external_keyboardJS_default().bind(globalOptions.hotKey.undoTaskKey, () => {
  11173. if (website.undoTask) {
  11174. website.undoTask();
  11175. }
  11176. });
  11177. external_keyboardJS_default().bind(globalOptions.hotKey.toggleLogKey, toggleLog);
  11178. if (website?.after) {
  11179. await website?.after();
  11180. }
  11181. if (website?.buttons && $('#auto-task-buttons').children().length === 0) {
  11182. $('#auto-task-buttons').addClass(`${website.name}-buttons`);
  11183. for (const button of website.buttons) {
  11184. if (website[button]) {
  11185. const btnElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">${i18n(button)}</a></p>`);
  11186. btnElement.find('a.auto-task-website-btn').on('click', () => {
  11187. website[button]();
  11188. });
  11189. $('#auto-task-buttons').append(btnElement);
  11190. }
  11191. }
  11192. }
  11193. const hideButtonElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">
  11194. ${i18n('hideButton')}</a></p>`);
  11195. hideButtonElement.find('a.auto-task-website-btn').on('click', () => {
  11196. $('#auto-task-buttons').hide();
  11197. $('div.show-button-div').show();
  11198. });
  11199. 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'}">
  11200. ${globalOptions.other.defaultShowLog ? i18n('hideLog') : i18n('showLog')}</a></p>`);
  11201. toggleLogElement.find('a.auto-task-website-btn').on('click', toggleLog);
  11202. $('#auto-task-buttons').append(hideButtonElement).append(toggleLogElement);
  11203. if (website?.options) {
  11204. GM_registerMenuCommand(i18n('changeWebsiteOptions'), () => {
  11205. options(website.name, website.options);
  11206. });
  11207. }
  11208. if (website.name !== 'Setting') {
  11209. GM_registerMenuCommand(i18n('changeGlobalOptions'), () => {
  11210. changeGlobalOptions('swal');
  11211. });
  11212. GM_registerMenuCommand(i18n('settingPage'), () => {
  11213. GM_openInTab('https://auto-task-v4.hclonely.com/setting.html', {
  11214. active: true
  11215. });
  11216. });
  11217. }
  11218. console.log('%c%s', 'color:#1bbe1a', 'Auto-Task[Load]: 脚本加载完成');
  11219. const [ v1, v2 ] = GM_info.version.split('.');
  11220. if (!(parseInt(v1, 10) >= 5 && parseInt(v2, 10) >= 2)) {
  11221. scripts_echoLog({}).error(i18n('versionNotMatched'));
  11222. }
  11223. if (!GM_getValue('notice')) {
  11224. external_Swal_default().fire({
  11225. title: i18n('swalNotice'),
  11226. icon: 'warning'
  11227. }).then(() => {
  11228. GM_openInTab(i18n('noticeLink'), {
  11229. active: true
  11230. });
  11231. GM_setValue('notice', new Date().getTime());
  11232. });
  11233. scripts_echoLog({
  11234. html: `<li><font class="warning">${i18n('echoNotice', i18n('noticeLink'))}</font></li>`
  11235. }).font?.find('a').on('click', () => {
  11236. GM_setValue('notice', new Date().getTime());
  11237. });
  11238. }
  11239. scripts_updateChecker();
  11240. };
  11241. if (window.location.hostname === 'discord.com') {
  11242. const LocalStorage = window.localStorage;
  11243. if (window.name === 'ATv4_discordAuth') {
  11244. window.localStorage.removeItem = () => true;
  11245. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11246. if (discordAuth && discordAuth.length > 0) {
  11247. GM_setValue('discordAuth', {
  11248. auth: discordAuth
  11249. });
  11250. window.close();
  11251. external_Swal_default().fire('', i18n('closePageNotice'));
  11252. } else {
  11253. external_Swal_default().fire({
  11254. text: i18n('getDiscordAuthFailed'),
  11255. icon: 'error'
  11256. });
  11257. }
  11258. } else {
  11259. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11260. if (discordAuth && discordAuth.length > 0) {
  11261. GM_setValue('discordAuth', {
  11262. auth: discordAuth
  11263. });
  11264. }
  11265. }
  11266. } else if (window.location.hostname === 'opquests.com') {
  11267. loadScript();
  11268. } else if ((window.name === 'ATv4_updateStoreAuth' || GM_getValue('ATv4_updateStoreAuth')) && window.location.host === 'store.steampowered.com') {
  11269. $(() => {
  11270. if ($('[data-miniprofile]').length === 0) {
  11271. return;
  11272. }
  11273. const storeSessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11274. if (storeSessionID) {
  11275. GM_deleteValue('ATv4_updateStoreAuth');
  11276. GM_setValue('steamStoreAuth', {
  11277. storeSessionID: storeSessionID
  11278. });
  11279. window.close();
  11280. external_Swal_default().fire('', i18n('closePageNotice'));
  11281. } else {
  11282. external_Swal_default().fire({
  11283. title: 'Error: Get "sessionID" failed',
  11284. icon: 'error'
  11285. });
  11286. }
  11287. });
  11288. } else if ((window.name === 'ATv4_updateCommunityAuth' || GM_getValue('ATv4_updateCommunityAuth')) && window.location.host === 'steamcommunity.com') {
  11289. $(() => {
  11290. const steam64Id = document.body.innerHTML.match(/g_steamID = "(.+?)";/)?.[1];
  11291. const communitySessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11292. if (steam64Id && communitySessionID) {
  11293. GM_deleteValue('ATv4_updateCommunityAuth');
  11294. GM_setValue('steamCommunityAuth', {
  11295. steam64Id: steam64Id,
  11296. communitySessionID: communitySessionID
  11297. });
  11298. window.close();
  11299. external_Swal_default().fire('', i18n('closePageNotice'));
  11300. } else {
  11301. setTimeout(() => {
  11302. external_Swal_default().fire({
  11303. title: 'Error: Get "sessionID" failed',
  11304. icon: 'error'
  11305. });
  11306. }, 3e3);
  11307. }
  11308. });
  11309. } else {
  11310. if (window.location.hostname === 'key-hub.eu') {
  11311. unsafeWindow.keyhubtracker = 1;
  11312. unsafeWindow.gaData = {};
  11313. }
  11314. $(loadScript);
  11315. }
  11316. }();
  11317. })();