auto-task-v4

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

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

  1. // ==UserScript==
  2. // @name auto-task-v4
  3. // @namespace auto-task-v4
  4. // @version 4.6.1
  5. // @description 自动完成 Freeanywhere,Giveawaysu,GiveeClub,Givekey,Gleam,Indiedb,keyhub,OpiumPulses,Opquests,SweepWidget 等网站的任务。
  6. // @description:en Automatically complete the tasks of FreeAnyWhere, GiveawaySu, GiveeClub, Givekey, Gleam, Indiedb, keyhub, OpiumPulses, Opquests, SweepWidget websites.
  7. // @author HCLonely
  8. // @license MIT
  9. // @run-at document-start
  10. // @homepage https://auto-task-doc.js.org/
  11. // @supportURL https://github.com/HCLonely/auto-task-v4/issues
  12. // @icon https://auto-task-v4.hclonely.com/favicon.ico
  13.  
  14. // @include *://freeanywhere.net/*
  15. // @include *://giveaway.su/giveaway/view/*
  16. // @include *://givee.club/*/event/*
  17. // @include *://givekey.ru/giveaway/*
  18. // @include *://www.indiedb.com/giveaways*
  19. // @include *://key-hub.eu/giveaway/*
  20. // @include *://keylol.com/*
  21. // @include *://www.opiumpulses.com/giveaways
  22. // @include *://prys.revadike.com/giveaway/?id=*
  23. // @include *://opquests.com/quests/*
  24. // @include *://gleam.io/*
  25. // @include *://sweepwidget.com/view/*
  26. // @include *://giveawayhopper.com/c/*
  27.  
  28. // @include *://discord.com/*
  29. // @include *://www.twitch.tv/*
  30. // @include *://www.youtube.com/*
  31. // @include *://*.reddit.com/*
  32. // @include *://twitter.com/settings/account?k*
  33. // @include *://x.com/settings/account*
  34. // @include *://steamcommunity.com/*
  35. // @include *://store.steampowered.com/*
  36. // @include https://auto-task-v4.hclonely.com/setting.html
  37. // @include https://auto-task-v4.hclonely.com/history.html
  38.  
  39. // @grant GM_setValue
  40. // @grant GM_getValue
  41. // @grant GM_listValues
  42. // @grant GM_deleteValue
  43. // @grant GM_addStyle
  44. // @grant GM_xmlhttpRequest
  45. // @grant GM_registerMenuCommand
  46. // @grant GM_info
  47. // @grant GM_openInTab
  48. // @grant GM_setClipboard
  49. // @grant GM_getResourceText
  50. // @grant GM_cookie
  51. // @grant GM_addValueChangeListener
  52. // @grant GM_removeValueChangeListener
  53. // @grant unsafeWindow
  54. // @grant window.close
  55. // @grant window.localStorage
  56. // @grant window.sessionStorage
  57. // @grant window.focus
  58.  
  59. // @connect cdn.jsdelivr.net
  60. // @connect store.steampowered.com
  61. // @connect steamcommunity.com
  62. // @connect login.steampowered.com
  63. // @connect twitter.com
  64. // @connect x.com
  65. // @connect api.twitter.com
  66. // @connect youtube.com
  67. // @connect www.youtube.com
  68. // @connect facebook.com
  69. // @connect instagram.com
  70. // @connect vk.com
  71. // @connect twitch.tv
  72. // @connect www.twitch.tv
  73. // @connect gql.twitch.tv
  74. // @connect github.com
  75. // @connect discordapp.com
  76. // @connect discord.gg
  77. // @connect discord.com
  78. // @connect www.reddit.com
  79. // @connect oauth.reddit.com
  80. // @connect raw.githubusercontent.com
  81. // @connect t.me
  82. // @connect bit.ly
  83. // @connect giveaway.su
  84. // @connect google.com
  85. // @connect www.vloot.io
  86. // @connect givee.club
  87. // @connect gleam.io
  88. // @connect www.indiedb.com
  89. // @connect key-hub.eu
  90. // @connect opquests.com
  91. // @connect itch.io
  92. // @connect auto-task-v4.hclonely.com
  93. // @connect giveawayhopper.com
  94. // @connect *
  95. // @require https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
  96. // @require https://cdn.jsdelivr.net/npm/js-cookie@3.0.1/dist/js.cookie.min.js
  97. // @require https://cdn.jsdelivr.net/npm/regenerator-runtime@0.13.5/runtime.min.js
  98. // @require https://cdn.jsdelivr.net/npm/js-sha1@0.6.0/src/sha1.min.js
  99. // @require https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js
  100. // @resource style https://cdn.jsdelivr.net/npm/sweetalert2@11.3.5/dist/sweetalert2.min.css
  101. // @require https://cdn.jsdelivr.net/npm/keyboardjs@2.6.4/dist/keyboard.min.js
  102. // @require https://cdn.jsdelivr.net/npm/dayjs@1.10.7/dayjs.min.js
  103.  
  104. // @noframes
  105. // ==/UserScript==
  106.  
  107. console.log('%c%s', 'color:blue', 'Auto-Task[Load]: 脚本开始加载');
  108. (function() {
  109. var __webpack_modules__ = {
  110. 991: function(__unused_webpack_module, exports) {
  111. !function(e, n) {
  112. true ? n(exports) : 0;
  113. }(this, function(e) {
  114. 'use strict';
  115. var t = function() {
  116. return (t = Object.assign || function(e) {
  117. for (var n, o = 1, t = arguments.length; o < t; o++) {
  118. for (var r in n = arguments[o]) {
  119. Object.prototype.hasOwnProperty.call(n, r) && (e[r] = n[r]);
  120. }
  121. }
  122. return e;
  123. }).apply(this, arguments);
  124. };
  125. function r(e, n, o) {
  126. if (o || 2 === arguments.length) {
  127. for (var t, r = 0, i = n.length; r < i; r++) {
  128. !t && r in n || ((t = t || Array.prototype.slice.call(n, 0, r))[r] = n[r]);
  129. }
  130. }
  131. return e.concat(t || Array.prototype.slice.call(n));
  132. }
  133. function d(e) {
  134. return '[object Object]' === n(e);
  135. }
  136. function l(e, n) {
  137. var o = r(r([], n || [], !0), [ '_' ], !1).join('|');
  138. return e.replace(new RegExp('(('.concat(o, ')[a-z])+'), 'g'), function(e, n) {
  139. return n.replace(new RegExp(o), '').toLocaleUpperCase();
  140. });
  141. }
  142. var n = function(e) {
  143. return Object.prototype.toString.call(e);
  144. };
  145. var o = (i.prototype.init = function() {
  146. try {
  147. this.getSystemName(), this.getBrowserName();
  148. } catch (e) {
  149. console.warn('[UA formatter error] '.concat(e));
  150. }
  151. }, i.prototype.getEngine = function() {
  152. var e = this.agent;
  153. return -1 !== e.indexOf('Trident') ? 'Trident' : -1 !== e.indexOf('Firefox') ? 'Gecko' : -1 !== e.indexOf('Presto') ? 'Presto' : 'WebKit';
  154. }, i.prototype.getSystemName = function() {
  155. var e, n = (this.agent.match(/^[a-z]+\/\d+\.\d+\s?\(([a-z\d\s:;./_-]+)\)/i) || [])[1];
  156. try {
  157. var o = '';
  158. if (/Windows/i.test(n)) {
  159. var t = (n.match(/NT\s(\d+\.\d+)/) || [])[1];
  160. switch (this.info.os = 'Windows', t) {
  161. case '6.3':
  162. o = '8.1';
  163. break;
  164.  
  165. case '6.2':
  166. o = '8';
  167. break;
  168.  
  169. case '6.1':
  170. o = '7';
  171. break;
  172.  
  173. case '5.2':
  174. case '5.1':
  175. o = 'XP';
  176. break;
  177.  
  178. default:
  179. o = t;
  180. }
  181. return this.info.device = 'PC', void (this.info.osVersion = o);
  182. }
  183. if (/^Macintosh/i.test(n)) {
  184. return o = (n.match(/X\s((\d+(_|\.))+\d+)/) || [])[1], this.info.os = 'Macintosh',
  185. this.info.device = 'PC', void (this.info.osVersion = null !== (e = null == o ? void 0 : o.replace(/_/g, '.')) && void 0 !== e ? e : 'Unknown');
  186. }
  187. if (/^iPad/i.test(n)) {
  188. return o = (n.match(/((\d+_)+\d+)/) || [])[1], this.info.os = 'iPad',
  189. this.info.device = 'Tablet', void (this.info.osVersion = o.replace(/_/g, '.'));
  190. }
  191. if (/^iPhone/i.test(n)) {
  192. return o = (n.match(/((\d+_)+\d+)/) || [])[1], this.info.os = 'iPhone',
  193. this.info.device = 'Mobile', void (this.info.osVersion = o.replace(/_/g, '.'));
  194. }
  195. if (-1 !== n.indexOf('Android')) {
  196. var r = (n.match(/Android\s((\d+\.?)+\d?)/) || [])[1];
  197. return this.info.device = 'Mobile', this.info.os = 'Android', void (this.info.osVersion = r);
  198. }
  199. if (/Linux\s[a-z\d_]+/.test(n)) {
  200. return this.info.os = 'Linux', void (this.info.osVersion = 'Unknown');
  201. }
  202. this.info.os = 'Unknown', this.info.osVersion = 'Unknown';
  203. } catch (e) {
  204. this.info.os = 'Unknown', this.info.osVersion = 'Unknown';
  205. }
  206. }, i.prototype.getBrowserName = function() {
  207. var e = Object.keys(this.browserNameMap).map(function(e) {
  208. return new RegExp(''.concat(e, '(\\/|\\s)(\\d+\\.)+\\d+'));
  209. }), n = 1 < (n = (this.agent.match(/[a-z\d]+(\/|\s)(\d+\.)+\d+/gi) || []).filter(function(n) {
  210. return -1 !== e.findIndex(function(e) {
  211. return e.test(n);
  212. });
  213. })).length && !/^Safari/.test(n[n.length - 1]) ? n.reverse() : n;
  214. this.info = t(t({}, this.info), this._formatBrowserVersion(n[0]));
  215. }, i.prototype._formatBrowserVersion = function(e) {
  216. var n, o, t, r;
  217. try {
  218. for (var i = null !== (o = null === (n = e.match(/(?<name>[a-z\d]+)(\/|\s)(?<version>(\d+\.)+\d+)/i)) || void 0 === n ? void 0 : n.groups) && void 0 !== o ? o : {}, s = i.name, a = i.version, c = {}, f = 0, u = Object.entries(this.browserNameMap); f < u.length; f++) {
  219. var d = u[f], l = d[0], h = d[1];
  220. if (new RegExp(l).test(s)) {
  221. c = h;
  222. break;
  223. }
  224. }
  225. var p = {
  226. browserVersion: null != a ? a : 'Unknown',
  227. browser: null !== (t = c.en) && void 0 !== t ? t : 'Unknown',
  228. browserZH: null !== (r = (null == c ? void 0 : c.zh) || c.en) && void 0 !== r ? r : 'Unknown'
  229. };
  230. return 'Trident' === s && (p.browserVersion = {
  231. '4.0': 8,
  232. '5.0': 9,
  233. '6.0': 10,
  234. '7.0': 11
  235. }[a]), p;
  236. } catch (e) {
  237. return console.warn('[UA formatter error] '.concat(e)), {
  238. browser: 'Unknown',
  239. browserVersion: 'Unknown'
  240. };
  241. }
  242. }, i);
  243. function i(e) {
  244. this.agent = '', this.info = {
  245. browser: '',
  246. browserZH: '',
  247. browserVersion: '',
  248. os: '',
  249. osVersion: '',
  250. device: 'Unknown',
  251. engine: 'WebKit'
  252. }, this.browserNameMap = {
  253. MicroMessenger: {
  254. en: 'MicroMessenger',
  255. zh: '微信'
  256. },
  257. MetaSr: {
  258. en: 'MetaSr',
  259. zh: '搜狗浏览器'
  260. },
  261. 'QQ(Browser)?': {
  262. en: 'QQBrowser',
  263. zh: 'QQ浏览器'
  264. },
  265. UCBrowser: {
  266. en: 'UCBrowser',
  267. zh: 'UC浏览器'
  268. },
  269. '2345Explorer': {
  270. en: '2345Explorer',
  271. zh: '2345极速浏览器'
  272. },
  273. Mb2345Browser: {
  274. en: 'Mb2345Browser',
  275. zh: '2345手机浏览器'
  276. },
  277. Trident: {
  278. en: 'Internet Explorer'
  279. },
  280. 'Edge?': {
  281. en: 'Edge'
  282. },
  283. OPR: {
  284. en: 'Opera'
  285. },
  286. Vivaldi: {
  287. en: 'Vivaldi'
  288. },
  289. Firefox: {
  290. en: 'Firefox'
  291. },
  292. Chrome: {
  293. en: 'Chrome'
  294. },
  295. Safari: {
  296. en: 'Safari'
  297. }
  298. }, this.agent = e, this.init();
  299. var n = this.info, o = n.browser, e = n.browserVersion, n = n.osVersion;
  300. this.info = t(t({}, this.info), {
  301. engine: this.getEngine(),
  302. browserVersion: 'Safari' === o ? n : e
  303. });
  304. }
  305. function s() {
  306. this.cookies = {}, this.init();
  307. }
  308. var a = new (s.prototype.init = function() {
  309. var o = {};
  310. document.cookie.split(/;\s/).forEach(function(e) {
  311. var n = e.split(/=/), e = n[0], n = n[1];
  312. o[e] = n;
  313. }), this.cookies = o;
  314. }, s.prototype.getItem = function(e) {
  315. return this.cookies[e];
  316. }, s.prototype.getAllItems = function() {
  317. return this.cookies;
  318. }, s.prototype.setItem = function(e, n, o, t, r, i) {
  319. document.cookie = ''.concat(e, '=').concat(n).concat(o ? '; expires='.concat(o) : '').concat(t ? '; path='.concat(t) : '').concat(r ? '; domain='.concat(r) : '').concat(i ? '; secure' : '');
  320. }, s)();
  321. e.countDown = function e(n, o, t, r) {
  322. if (!window) {
  323. throw new Error('window is not defind.');
  324. }
  325. if (0 < n) {
  326. return r && r(), n--, window[o] = window.setTimeout(function() {
  327. e(n, o, t, r);
  328. }, 1e3), function() {
  329. return clearTimeout(window[o]);
  330. };
  331. }
  332. clearTimeout(window[o]), t && t();
  333. }, e.createRandomID = function(e) {
  334. void 0 === e && (e = 12);
  335. for (var n = [], o = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''), t = o.length, r = 0; r < e; r++) {
  336. n.push(o[Math.round(Math.random() * t)]);
  337. }
  338. return n.join('');
  339. }, e.dCookie = a, e.debounce = function(o, t, r) {
  340. var i;
  341. void 0 === t && (t = 0);
  342. var s = r = void 0 === r ? !1 : r;
  343. return function() {
  344. var e = this, n = arguments;
  345. s && (o.apply(this, arguments), s = !1), clearTimeout(i), i = setTimeout(function() {
  346. r ? s = !0 : o.apply(e, n);
  347. }, t);
  348. };
  349. }, e.deepCopy = function e(n) {
  350. if (d(n) || Array.isArray(n)) {
  351. var o, t = Array.isArray(n) ? [] : {};
  352. for (o in n) {
  353. t[o] = e(n[o]);
  354. }
  355. return t;
  356. }
  357. return n;
  358. }, e.formatQueryParams = function(e) {
  359. e = null === (e = /\?(?<params>(.*)=.+)/.exec(decodeURIComponent(e))) || void 0 === e ? void 0 : e.groups;
  360. if (!e) {
  361. return {};
  362. }
  363. for (var n = e.params.split('&'), t = {}, o = 0; o < n.length; o++) {
  364. n[o].replace(/([^?&]*)=([^?&]*)/, function(e, n, o) {
  365. return t[n] = o, e;
  366. });
  367. }
  368. return t;
  369. }, e.formatThousandth = function(e) {
  370. var n = ''.concat(e).split('.'), e = n[0], n = n[1], n = void 0 === n ? '' : n, e = e.replace(/\d{1,3}(?=(\d{3})+$)/g, '$&,');
  371. return ''.concat(e).concat(n ? '.'.concat(n) : '');
  372. }, e.generateTree = function e(n, o, t, r) {
  373. for (var i = [], s = 0; s < n.length; s++) {
  374. var a = n[s];
  375. a[t] === o && (i.push(a), a.children = e(n, a[null != r ? r : 'id'], t, r));
  376. }
  377. return i;
  378. }, e.isEmpty = function(e) {
  379. return Array.isArray(e) ? 0 === e.length : d(e) ? 0 === Object.keys(e).length : [ '[object Set]', '[object Map]' ].includes(n(e)) ? 0 === e.size : [ null, void 0, '' ].includes(e);
  380. }, e.isFunction = function(e) {
  381. return '[object Function]' === n(e);
  382. }, e.isImageUrl = function(e) {
  383. return /\.((png)|(jpe?g)|(gif)|(svg)|(webp))$/gi.test(e);
  384. }, e.isObject = d, e.isRegexp = function(e) {
  385. return '[object RegExp]' === n(e);
  386. }, e.objectKeyToCamelCase = function e(n, o, t) {
  387. if (Array.isArray(n)) {
  388. for (var r = [], i = 0; i < n.length; i++) {
  389. r[i] = e(o && n[i][o] ? n[i][o] : n[i], o, t);
  390. }
  391. } else if (d(n)) {
  392. r = {};
  393. for (var s = o && n[o] ? n[o] : n, a = 0, c = Object.entries(s); a < c.length; a++) {
  394. var f = (u = c[a])[0], u = u[1];
  395. Array.isArray(u) || d(s) ? r[l(f, t)] = e(u, o, t) : r[l(f, t)] = u;
  396. }
  397. } else {
  398. r = n;
  399. }
  400. return r;
  401. }, e.realType = n, e.searchParams = function(e, n) {
  402. return void 0 === e && (e = null === location || void 0 === location ? void 0 : location.search),
  403. new URLSearchParams(e).get(n);
  404. }, e.toLowerCamelCase = l, e.toUnderline = function(e) {
  405. return e.replace(/([A-Z])/g, function(e) {
  406. return '_'.concat(e.toLocaleLowerCase());
  407. });
  408. }, e.ua = function(e) {
  409. return void 0 === e && (e = navigator.userAgent), new o(e).info;
  410. }, Object.defineProperty(e, '__esModule', {
  411. value: !0
  412. });
  413. });
  414. },
  415. 675: function(module, __webpack_exports__, __webpack_require__) {
  416. 'use strict';
  417. __webpack_require__.d(__webpack_exports__, {
  418. A: function() {
  419. return __WEBPACK_DEFAULT_EXPORT__;
  420. }
  421. });
  422. var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(601);
  423. var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = __webpack_require__.n(_node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
  424. var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(314);
  425. var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = __webpack_require__.n(_node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
  426. var ___CSS_LOADER_EXPORT___ = _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()(_node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default());
  427. ___CSS_LOADER_EXPORT___.push([ module.id, `.colorful-button,#auto-task-buttons a.auto-task-website-btn,.show-button-div a.auto-task-website-btn,body.auto-task-options .auto-task-form table button{position:relative;padding:5px 10px;text-align:center;color:#fff;text-decoration:none;background:linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);border-radius:30px;background-size:400%;text-transform:capitalize}.colorful-button:hover,#auto-task-buttons a.auto-task-website-btn:hover,.show-button-div a.auto-task-website-btn:hover,body.auto-task-options .auto-task-form table button:hover{transform:scale(1.05);box-shadow:0 6px 20px rgba(0,0,0,.3);cursor:pointer}.colorful-button:hover::before,#auto-task-buttons a.auto-task-website-btn:hover::before,.show-button-div a.auto-task-website-btn:hover::before,body.auto-task-options .auto-task-form table button:hover::before{filter:blur(10px);opacity:1}.colorful-button::before,#auto-task-buttons a.auto-task-website-btn::before,.show-button-div a.auto-task-website-btn::before,body.auto-task-options .auto-task-form table button::before{content:"";position:absolute;top:-5px;left:-5px;right:-5px;bottom:-5px;z-index:-1;background:linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);border-radius:40px;background-size:400%;opacity:-1}#auto-task-info{z-index:999999999 !important}#auto-task-info{position:fixed;bottom:10px;right:10px;width:60%;max-width:500px;max-height:60%;overflow-y:auto;color:#000;background-color:#fff;padding-left:5px;border:solid 2px #add8e6;border-radius:10px}#auto-task-info li{text-align:left}#auto-task-info li a.high-light{color:#00aeff;font-weight:bold}#auto-task-info .success{color:green}#auto-task-info .error{color:red}#auto-task-info .warning{color:blue}#auto-task-info .info{color:#ff0}#auto-task-info .update-text{color:green;border:solid 2px #8dcb69;margin:5px 10px 5px 20px;border-radius:10px;padding:5px 20px}.auto-task-keylol{text-decoration:none !important}.auto-task-keylol{display:inline-block;text-transform:capitalize;margin-left:10px;border:solid 1px;border-radius:5px;padding:0 2px}.auto-task-keylol[selected=selected]{background-color:blue !important;color:#fff !important}.auto-task-form table{font-family:verdana,arial,sans-serif;font-size:11px;color:#333;border-width:1px;border-color:#999;border-collapse:collapse;width:100%}.auto-task-form table thead td{border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9;font-weight:bold;background-color:#fff}.auto-task-form table tbody tr{background-color:#d4e3e5}.auto-task-form table tbody tr:hover{background-color:#ff6 !important}.auto-task-form table tbody tr th{background-color:#c3dde0;border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9;text-transform:capitalize}.auto-task-form table tbody tr td{border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9}.swal2-modal{width:70% !important;max-width:1000px !important}body.auto-task-options{padding-top:10px;text-align:center}body.auto-task-options .auto-task-form{width:80%;max-width:1000px;margin:0 auto;padding-bottom:20px}body.auto-task-options .auto-task-form table input.editOption{width:80%}body.auto-task-options .auto-task-form table #getTwitterUserId,body.auto-task-options .auto-task-form table #getYoutubeChannelId{margin-top:5px}body.auto-task-options .auto-task-form table button{z-index:1}body.auto-task-options .auto-task-form table input[type=text]{outline-style:none;border:1px solid #ccc;border-radius:3px;padding:5px 10px;font-size:14px}body.auto-task-options .auto-task-form table input[type=text]:focus{border-color:#66afe9;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}body.auto-task-options .auto-task-form table label{position:relative;width:160px;height:80px;cursor:pointer;transform:scale(0.25);margin:-25% 0;top:-30px;display:inline-block}body.auto-task-options .auto-task-form table label input{position:relative;z-index:1;appearance:none}body.auto-task-options .auto-task-form table label input:checked~span{background:#05be05;box-shadow:0 15px 25px rgba(5,190,5,.4)}body.auto-task-options .auto-task-form table label input:checked~span i{left:84px}body.auto-task-options .auto-task-form table label input:checked~span i::before{background:#05be05;box-shadow:35px 0 0 #05be05}body.auto-task-options .auto-task-form table label input:checked~span i::after{bottom:12px;height:15px;border-bottom-left-radius:15px;border-bottom-right-radius:15px;background:#05be05}body.auto-task-options .auto-task-form table label span{position:absolute;top:0;left:0;width:100%;height:100%;background:#fe0000;border-radius:80px;transition:.5s;box-shadow:0 15px 25px rgba(254,0,0,.4)}body.auto-task-options .auto-task-form table label span i{position:absolute;top:4px;left:4px;width:72px;height:72px;background:#fff;border-radius:50%}body.auto-task-options .auto-task-form table label span i::before{content:"";position:absolute;top:22px;left:12px;width:12px;height:12px;border-radius:50%;background:#fe0000;box-shadow:35px 0 0 #fe0000;transition:.5s}body.auto-task-options .auto-task-form table label span i::after{content:"";position:absolute;bottom:15px;left:calc(50% - 15px);width:30px;height:6px;border-radius:6px;background:#fe0000;transition:.5s}body.auto-task-history{font-size:15px;font-weight:400;line-height:1.5}body.auto-task-history .container a{color:#007bff;text-decoration:none;background-color:rgba(0,0,0,0)}body.auto-task-history .container .card{width:80%;max-width:800px;border-radius:10px;background:rgba(118,118,118,.1019607843);border-top:1px solid rgba(255,255,255,.5019607843);-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);box-shadow:0 15px 25px rgba(0,0,0,.1019607843);margin:20px auto;position:relative;display:flex;flex-direction:column;word-wrap:break-word;-webkit-background-clip:border-box;background-clip:border-box;border:1px solid rgba(0,0,0,.125);border-radius:.25rem}body.auto-task-history .container .card .title{text-align:center;font-size:30px;font-weight:bold;margin:5px 0}body.auto-task-history .container .card .title a:hover{text-decoration:none;background:#93e1ff;border-radius:10px;padding:3px}body.auto-task-history .container .card ul{margin-bottom:25px}body.auto-task-history .container .card ul li{margin-bottom:5px;line-height:20px}body.auto-task-history .container .card ul a:hover{text-decoration:underline}body.auto-task-history .container .card .delete-task{right:10px;width:38px;height:35px;position:absolute;font-size:24px;cursor:pointer;border-radius:10px}body.auto-task-history .container .card .delete-task:hover{background:#fff}body.auto-task-history .container .card .time{right:5px;position:absolute;bottom:0;color:#e83e8c;font-family:'SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace';font-size:15px}#auto-task-buttons,.show-button-div{z-index:999999999 !important}#auto-task-buttons,.show-button-div{position:fixed;top:30px;right:15px;width:124px;transform:scale(0.85)}#auto-task-buttons p,.show-button-div p{margin:5px !important}#auto-task-buttons p,.show-button-div p{line-height:30px;height:40px;text-align:center}#auto-task-buttons a.auto-task-website-btn,.show-button-div a.auto-task-website-btn{width:105px;line-height:27px;font-size:20px;display:block}.show-button-div{width:20px}.auto-task-capitalize{text-transform:capitalize !important}.swal2-file:focus,.swal2-input:focus,.swal2-textarea:focus{box-shadow:inset 0px 0px 4px 1px rgba(100,150,200,.5) !important}.swal2-checkbox-custom{align-items:center;justify-content:center;background:#fff;color:inherit;margin:1em auto}.swal2-checkbox-custom input{flex-shrink:0;margin:0 .4em}.giveaway-actions #getKey{display:none !important}.auto-task-giveaway-status{color:#fff;border-radius:10px;padding:0 5px;margin-left:5px}.auto-task-giveaway-status.active{background-color:#5cb85c}.auto-task-giveaway-status.not-active{background-color:#d9534f}`, '' ]);
  428. const __WEBPACK_DEFAULT_EXPORT__ = ___CSS_LOADER_EXPORT___.toString();
  429. },
  430. 314: function(module) {
  431. 'use strict';
  432. module.exports = function(cssWithMappingToString) {
  433. var list = [];
  434. list.toString = function toString() {
  435. return this.map(function(item) {
  436. var content = '';
  437. var needLayer = typeof item[5] !== 'undefined';
  438. if (item[4]) {
  439. content += '@supports ('.concat(item[4], ') {');
  440. }
  441. if (item[2]) {
  442. content += '@media '.concat(item[2], ' {');
  443. }
  444. if (needLayer) {
  445. content += '@layer'.concat(item[5].length > 0 ? ' '.concat(item[5]) : '', ' {');
  446. }
  447. content += cssWithMappingToString(item);
  448. if (needLayer) {
  449. content += '}';
  450. }
  451. if (item[2]) {
  452. content += '}';
  453. }
  454. if (item[4]) {
  455. content += '}';
  456. }
  457. return content;
  458. }).join('');
  459. };
  460. list.i = function i(modules, media, dedupe, supports, layer) {
  461. if (typeof modules === 'string') {
  462. modules = [ [ null, modules, undefined ] ];
  463. }
  464. var alreadyImportedModules = {};
  465. if (dedupe) {
  466. for (var k = 0; k < this.length; k++) {
  467. var id = this[k][0];
  468. if (id != null) {
  469. alreadyImportedModules[id] = true;
  470. }
  471. }
  472. }
  473. for (var _k = 0; _k < modules.length; _k++) {
  474. var item = [].concat(modules[_k]);
  475. if (dedupe && alreadyImportedModules[item[0]]) {
  476. continue;
  477. }
  478. if (typeof layer !== 'undefined') {
  479. if (typeof item[5] === 'undefined') {
  480. item[5] = layer;
  481. } else {
  482. item[1] = '@layer'.concat(item[5].length > 0 ? ' '.concat(item[5]) : '', ' {').concat(item[1], '}');
  483. item[5] = layer;
  484. }
  485. }
  486. if (media) {
  487. if (!item[2]) {
  488. item[2] = media;
  489. } else {
  490. item[1] = '@media '.concat(item[2], ' {').concat(item[1], '}');
  491. item[2] = media;
  492. }
  493. }
  494. if (supports) {
  495. if (!item[4]) {
  496. item[4] = ''.concat(supports);
  497. } else {
  498. item[1] = '@supports ('.concat(item[4], ') {').concat(item[1], '}');
  499. item[4] = supports;
  500. }
  501. }
  502. list.push(item);
  503. }
  504. };
  505. return list;
  506. };
  507. },
  508. 601: function(module) {
  509. 'use strict';
  510. module.exports = function(i) {
  511. return i[1];
  512. };
  513. }
  514. };
  515. var __webpack_module_cache__ = {};
  516. function __webpack_require__(moduleId) {
  517. var cachedModule = __webpack_module_cache__[moduleId];
  518. if (cachedModule !== undefined) {
  519. return cachedModule.exports;
  520. }
  521. var module = __webpack_module_cache__[moduleId] = {
  522. id: moduleId,
  523. exports: {}
  524. };
  525. __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  526. return module.exports;
  527. }
  528. !function() {
  529. __webpack_require__.n = function(module) {
  530. var getter = module && module.__esModule ? function() {
  531. return module['default'];
  532. } : function() {
  533. return module;
  534. };
  535. __webpack_require__.d(getter, {
  536. a: getter
  537. });
  538. return getter;
  539. };
  540. }();
  541. !function() {
  542. __webpack_require__.d = function(exports, definition) {
  543. for (var key in definition) {
  544. if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  545. Object.defineProperty(exports, key, {
  546. enumerable: true,
  547. get: definition[key]
  548. });
  549. }
  550. }
  551. };
  552. }();
  553. !function() {
  554. __webpack_require__.o = function(obj, prop) {
  555. return Object.prototype.hasOwnProperty.call(obj, prop);
  556. };
  557. }();
  558. var __webpack_exports__ = {};
  559. !function() {
  560. 'use strict';
  561. const external_Swal_namespaceObject = Swal;
  562. var external_Swal_default = __webpack_require__.n(external_Swal_namespaceObject);
  563. const external_Cookies_namespaceObject = Cookies;
  564. var external_Cookies_default = __webpack_require__.n(external_Cookies_namespaceObject);
  565. var auto_task = __webpack_require__(675);
  566. var javascript_utils_umd_min = __webpack_require__(991);
  567. const httpRequest = async (options, times = 0) => {
  568. if (window.TRACE) {
  569. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  570. }
  571. try {
  572. const result = await new Promise(resolve => {
  573. if (options.dataType) {
  574. options.responseType = options.dataType;
  575. }
  576. const requestObj = {
  577. ...{
  578. timeout: 3e4,
  579. ontimeout(data) {
  580. resolve({
  581. result: 'Error',
  582. statusText: 'Timeout',
  583. status: 601,
  584. data: data,
  585. options: options
  586. });
  587. },
  588. onabort(data) {
  589. resolve({
  590. result: 'Error',
  591. statusText: 'Aborted',
  592. status: 602,
  593. data: data,
  594. options: options
  595. });
  596. },
  597. onerror(data) {
  598. resolve({
  599. result: 'Error',
  600. statusText: 'Error',
  601. status: 603,
  602. data: data,
  603. options: options
  604. });
  605. },
  606. onload(data) {
  607. const headers = {};
  608. data.responseHeaders?.split('\n').forEach(header => {
  609. const headerArr = header.trim().split(':');
  610. const name = headerArr.shift()?.trim() || '';
  611. const value = headerArr.join(':').trim();
  612. if (name && value) {
  613. if (headers[name]) {
  614. if (Array.isArray(headers[name])) {
  615. headers[name].push(value);
  616. } else {
  617. headers[name] = [ headers[name], value ];
  618. }
  619. } else {
  620. headers[name] = value;
  621. }
  622. }
  623. });
  624. if (headers['set-cookie'] && !Array.isArray(headers['set-cookie'])) {
  625. headers['set-cookie'] = [ headers['set-cookie'] ];
  626. }
  627. data.responseHeadersText = data.responseHeaders;
  628. data.responseHeaders = headers;
  629. data.finalUrl = data.responseHeaders?.location || data.finalUrl;
  630. if (options.responseType === 'json' && data?.response && typeof data.response !== 'object') {
  631. try {
  632. data.response = JSON.parse(data.responseText);
  633. } catch (error) {}
  634. }
  635. resolve({
  636. result: 'Success',
  637. statusText: 'Load',
  638. status: 600,
  639. data: data,
  640. options: options
  641. });
  642. }
  643. },
  644. ...options
  645. };
  646. GM_xmlhttpRequest(requestObj);
  647. });
  648. if (window.DEBUG) {
  649. console.log('%cAuto-Task[httpRequest]:', 'color:blue', JSON.stringify(result));
  650. }
  651. if (result.status !== 600 && times < 2) {
  652. return await httpRequest(options, times + 1);
  653. }
  654. return result;
  655. } catch (error) {
  656. console.log('%cAuto-Task[httpRequest]:', 'color:red', JSON.stringify({
  657. errorMsg: error,
  658. options: options
  659. }));
  660. throwError(error, 'httpRequest');
  661. return {
  662. result: 'JsError',
  663. statusText: 'Error',
  664. status: 604,
  665. error: error,
  666. options: options
  667. };
  668. }
  669. };
  670. const tools_httpRequest = httpRequest;
  671. const echoLog = ({
  672. type,
  673. text,
  674. html,
  675. id
  676. }) => {
  677. const emptyStatus = {
  678. success: () => emptyStatus,
  679. error: () => emptyStatus,
  680. warning: () => emptyStatus,
  681. info: () => emptyStatus,
  682. view: () => emptyStatus
  683. };
  684. try {
  685. let ele;
  686. if (type) {
  687. switch (type) {
  688. case 'joiningSteamGroup':
  689. case 'leavingSteamGroup':
  690. case 'gettingSteamGroupId':
  691. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/groups/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  692. break;
  693.  
  694. case 'joiningSteamOfficialGroup':
  695. case 'leavingSteamOfficialGroup':
  696. case 'gettingSteamOfficialGroupId':
  697. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/games/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  698. break;
  699.  
  700. case 'subscribingForum':
  701. case 'unsubscribingForum':
  702. case 'gettingForumId':
  703. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/app/${text}/discussions/" target="_blank">${text}</a>]...<font></font></li>`);
  704. break;
  705.  
  706. case 'followingCurator':
  707. case 'unfollowingCurator':
  708. case 'gettingCuratorId':
  709. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/${text?.includes('/') ? text : `curator/${text}`}" target="_blank">${text}</a>]...<font></font></li>`);
  710. break;
  711.  
  712. case 'addingToWishlist':
  713. case 'removingFromWishlist':
  714. case 'followingGame':
  715. case 'unfollowingGame':
  716. case 'gettingSubid':
  717. case 'addingFreeLicense':
  718. case 'requestingPlayTestAccess':
  719. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/app/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  720. break;
  721.  
  722. case 'addingFreeLicenseSubid':
  723. ele = $(`<li>${i18n('addingFreeLicense')}[<a href="https://steamdb.info/sub/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  724. break;
  725.  
  726. case 'favoritingWorkshop':
  727. case 'unfavoritingWorkshop':
  728. case 'gettingWorkshopAppId':
  729. case 'votingUpWorkshop':
  730. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/sharedfiles/filedetails/?id=${text}" target="_blank">
  731. ${text}</a>]...<font></font></li>`);
  732. break;
  733.  
  734. case 'gettingAnnouncementParams':
  735. case 'likingAnnouncement':
  736. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/news/app/${text}/view/${id}" target="_blank">
  737. ${id}</a>]...<font></font></li>`);
  738. break;
  739.  
  740. case 'joiningDiscordServer':
  741. case 'gettingDiscordGuild':
  742. ele = $(`<li>${i18n(type)}[<a href="https://discord.com/invite/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  743. break;
  744.  
  745. case 'leavingDiscordServer':
  746. ele = $(`<li>${i18n(type)}[<a href="https://discord.com/channels/@me/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  747. break;
  748.  
  749. case 'updateDiscordAuth':
  750. ele = $(`<li style="color:red;">${i18n('updateDiscordAuth')}</li>`);
  751. break;
  752.  
  753. case 'followingTwitchChannel':
  754. case 'unfollowingTwitchChannel':
  755. case 'gettingTwitchChannelId':
  756. ele = $(`<li>${i18n(type)}[<a href="https://www.twitch.tv/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  757. break;
  758.  
  759. case 'gettingInsUserId':
  760. case 'followingIns':
  761. case 'unfollowingIns':
  762. ele = $(`<li>${i18n(type)}[<a href="https://www.instagram.com/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  763. break;
  764.  
  765. case 'gettingTwitterUserId':
  766. case 'followingTwitterUser':
  767. case 'unfollowingTwitterUser':
  768. ele = $(`<li>${i18n(type)}[<a href="https://x.com/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  769. break;
  770.  
  771. case 'retweetting':
  772. case 'unretweetting':
  773. ele = $(`<li>${i18n(type)}${text}...<font></font></li>`);
  774. break;
  775.  
  776. case 'joiningReddit':
  777. case 'leavingReddit':
  778. ele = $(`<li>${i18n(type)}[<a href="https://www.reddit.com/r/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  779. break;
  780.  
  781. case 'followingRedditUser':
  782. case 'unfollowingRedditUser':
  783. ele = $(`<li>${i18n(type)}[<a href="https://www.reddit.com/user/${text?.replace('u_', '')}" target="_blank">
  784. ${text?.replace('u_', '')}</a>]...<font></font></li>`);
  785. break;
  786.  
  787. case 'followingYtbChannel':
  788. case 'unfollowingYtbChannel':
  789. ele = $(`<li>${i18n(type)}[<a href="https://www.youtube.com/channel/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  790. break;
  791.  
  792. case 'likingYtbVideo':
  793. case 'unlikingYtbVideo':
  794. ele = $(`<li>${i18n(type)}[<a href="https://www.youtube.com/watch?v=${text}" target="_blank">${text}</a>]...<font></font></li>`);
  795. break;
  796.  
  797. case 'gettingVkId':
  798. case 'joiningVkGroup':
  799. case 'leavingVkGroup':
  800. case 'joiningVkPublic':
  801. case 'leavingVkPublic':
  802. case 'sendingVkWall':
  803. case 'deletingVkWall':
  804. ele = $(`<li>${i18n(type)}[<a href="https://vk.com/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  805. break;
  806.  
  807. case 'visitingLink':
  808. ele = $(`<li>${i18n('visitingLink')}[<a href="${text}" target="_blank">${text}</a>]...<font></font></li>`);
  809. break;
  810.  
  811. case 'verifyingInsAuth':
  812. case 'text':
  813. ele = $(`<li>${i18n(text)}<font></font></li>`);
  814. break;
  815.  
  816. case 'html':
  817. ele = $(text || html);
  818. break;
  819.  
  820. case 'whiteList':
  821. ele = $(`<li><font class="warning">${i18n('skipTask')}[${text}(${id})](${i18n('whiteList')})</font></li>`);
  822. break;
  823.  
  824. case 'globalOptionsSkip':
  825. ele = $(`<li>${i18n('skipTaskOption')}<font class="warning">${text}</font></li>`);
  826. break;
  827.  
  828. default:
  829. ele = $(`<li>${i18n('unKnown')}:${type}(${text})...<font></font></li>`);
  830. break;
  831. }
  832. } else if (text) {
  833. ele = $(`<li>${i18n(text)}<font></font></li>`);
  834. } else if (html) {
  835. ele = $(html);
  836. } else {
  837. ele = $('<li><font></font></li>');
  838. }
  839. ele.addClass('card-text');
  840. $('#auto-task-info').append(ele);
  841. ele[0]?.scrollIntoView();
  842. const font = ele.find('font');
  843. const status = {
  844. font: font,
  845. success(text = 'Success', html = false) {
  846. this.font?.attr('class', '').addClass('success');
  847. html ? this.font?.html(text) : this.font?.text(text);
  848. return this;
  849. },
  850. error(text = 'Error', html = false) {
  851. this.font?.attr('class', '').addClass('error');
  852. html ? this.font?.html(text) : this.font?.text(text);
  853. return this;
  854. },
  855. warning(text = 'Warning', html = false) {
  856. this.font?.attr('class', '').addClass('warning');
  857. html ? this.font?.html(text) : this.font?.text(text);
  858. return this;
  859. },
  860. info(text = 'Info', html = false) {
  861. this.font?.attr('class', '').addClass('info');
  862. html ? this.font?.html(text) : this.font?.text(text);
  863. return this;
  864. },
  865. view() {
  866. this.font?.[0].scrollIntoView();
  867. return this;
  868. }
  869. };
  870. return status;
  871. } catch (error) {
  872. throwError(error, 'echoLog');
  873. return emptyStatus;
  874. }
  875. };
  876. const scripts_echoLog = echoLog;
  877. const unique = array => {
  878. try {
  879. return [ ...new Set(array) ];
  880. } catch (error) {
  881. throwError(error, 'unique');
  882. return [];
  883. }
  884. };
  885. const delay = (time = 1e3) => new Promise(resolve => {
  886. setTimeout(() => {
  887. resolve(true);
  888. }, time);
  889. });
  890. const getRedirectLink = async link => {
  891. try {
  892. if (!link) {
  893. return null;
  894. }
  895. const redirectLinksCache = GM_getValue('redirectLinks') || {};
  896. if (redirectLinksCache[link]) {
  897. redirectLinksCache[link];
  898. }
  899. return await tools_httpRequest({
  900. url: link,
  901. method: 'GET'
  902. }).then(({
  903. data
  904. }) => {
  905. if (data?.finalUrl) {
  906. redirectLinksCache[link] = data.finalUrl;
  907. GM_setValue('redirectLinks', redirectLinksCache);
  908. return data.finalUrl;
  909. }
  910. return null;
  911. });
  912. } catch (error) {
  913. throwError(error, 'getRedirectLink');
  914. return null;
  915. }
  916. };
  917. const visitLink = async (link, options) => {
  918. try {
  919. const logStatus = scripts_echoLog({
  920. type: 'visitLink',
  921. text: link
  922. });
  923. return await tools_httpRequest({
  924. url: link,
  925. method: 'GET',
  926. ...options
  927. }).then(({
  928. result,
  929. statusText,
  930. status
  931. }) => {
  932. if (result === 'Success') {
  933. logStatus.success();
  934. return true;
  935. }
  936. logStatus.error(`${result}:${statusText}(${status})`);
  937. return false;
  938. });
  939. } catch (error) {
  940. throwError(error, 'visitLink');
  941. return false;
  942. }
  943. };
  944. const getUrlQuery = url => {
  945. try {
  946. const query = {};
  947. if (url) {
  948. if (url.includes('?')) {
  949. url.split('?')[1].replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  950. query[key] = value;
  951. return str;
  952. });
  953. }
  954. } else {
  955. window.location.search.replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  956. query[key] = value;
  957. return str;
  958. });
  959. }
  960. return query;
  961. } catch (error) {
  962. throwError(error, 'getUrlQuery');
  963. return {};
  964. }
  965. };
  966. const getUuid = () => {
  967. const uuidUrl = URL.createObjectURL(new Blob()).toString();
  968. return uuidUrl.slice(uuidUrl.lastIndexOf('/') + 1);
  969. };
  970. const stringToColour = str => {
  971. try {
  972. let hash = 0;
  973. for (let i = 0; i < str.length; i++) {
  974. hash = str.charCodeAt(i) + ((hash << 5) - hash);
  975. }
  976. let colour = '#';
  977. for (let i = 0; i < 3; i++) {
  978. const value = hash >> i * 8 & 255;
  979. colour += `00${value.toString(16)}`.slice(-2);
  980. }
  981. return colour;
  982. } catch (error) {
  983. throwError(error, 'stringToColour');
  984. return '#fff';
  985. }
  986. };
  987. const defaultGlobalOptions = {
  988. doTask: {
  989. discord: {
  990. servers: true
  991. },
  992. instagram: {
  993. users: true
  994. },
  995. twitch: {
  996. channels: true
  997. },
  998. twitter: {
  999. users: true,
  1000. retweets: true
  1001. },
  1002. vk: {
  1003. names: true
  1004. },
  1005. youtube: {
  1006. channels: true,
  1007. likes: true
  1008. },
  1009. reddit: {
  1010. reddits: true
  1011. },
  1012. steam: {
  1013. groups: true,
  1014. officialGroups: true,
  1015. wishlists: true,
  1016. follows: true,
  1017. forums: true,
  1018. workshops: true,
  1019. curators: true,
  1020. workshopVotes: true,
  1021. announcements: true,
  1022. licenses: true,
  1023. playtests: true
  1024. }
  1025. },
  1026. undoTask: {
  1027. discord: {
  1028. servers: true
  1029. },
  1030. instagram: {
  1031. users: true
  1032. },
  1033. twitch: {
  1034. channels: true
  1035. },
  1036. twitter: {
  1037. users: true,
  1038. retweets: true
  1039. },
  1040. vk: {
  1041. names: true
  1042. },
  1043. youtube: {
  1044. channels: true,
  1045. likes: true
  1046. },
  1047. reddit: {
  1048. reddits: true
  1049. },
  1050. steam: {
  1051. groups: true,
  1052. officialGroups: true,
  1053. wishlists: true,
  1054. follows: true,
  1055. forums: true,
  1056. workshops: true,
  1057. curators: true
  1058. }
  1059. },
  1060. ASF: {
  1061. AsfEnabled: false,
  1062. AsfIpcUrl: '',
  1063. AsfIpcPassword: '',
  1064. AsfBotname: 'asf'
  1065. },
  1066. position: {
  1067. buttonSideX: 'right',
  1068. buttonSideY: 'top',
  1069. buttonDistance: '15,30',
  1070. showButtonSideX: 'right',
  1071. showButtonSideY: 'top',
  1072. showButtonDistance: '15,30',
  1073. logSideX: 'right',
  1074. logSideY: 'bottom',
  1075. logDistance: '10,10'
  1076. },
  1077. hotKey: {
  1078. doTaskKey: 'alt + d',
  1079. undoTaskKey: 'alt + u',
  1080. toggleLogKey: 'alt + l'
  1081. },
  1082. other: {
  1083. twitterVerifyId: '783214',
  1084. youtubeVerifyChannel: 'UCrXUsMBcfTVqwAS7DKg9C0Q',
  1085. autoUpdateSource: 'jsdelivr',
  1086. language: 'zh',
  1087. checkLogin: true,
  1088. checkLeftKey: true,
  1089. defaultShowButton: true,
  1090. defaultShowLog: true,
  1091. debug: false,
  1092. receivePreview: true
  1093. }
  1094. };
  1095. const userDefinedGlobalOptions = GM_getValue('globalOptions') || {};
  1096. const assignObject = (obj1, obj2) => {
  1097. try {
  1098. const newObj = {};
  1099. for (const [ key, value ] of Object.entries(obj1)) {
  1100. if (Object.prototype.toString.call(value) === '[object Object]' && Object.prototype.toString.call(obj2[key]) === '[object Object]') {
  1101. newObj[key] = assignObject(value, obj2[key]);
  1102. } else {
  1103. newObj[key] = obj2[key] ?? value;
  1104. }
  1105. }
  1106. return newObj;
  1107. } catch (error) {
  1108. throwError(error, 'assignObject');
  1109. return defaultGlobalOptions;
  1110. }
  1111. };
  1112. const globalOptions = assignObject(defaultGlobalOptions, userDefinedGlobalOptions);
  1113. const saveData = () => {
  1114. try {
  1115. const data = {};
  1116. $('#globalOptionsForm').serializeArray().map(value => {
  1117. data[value.name] = value.value;
  1118. return value;
  1119. });
  1120. $.makeArray($('#globalOptionsForm input')).map(element => {
  1121. const name = $(element).attr('name');
  1122. const keys = name.split('.');
  1123. if (keys.length === 3) {
  1124. globalOptions[keys[0]][keys[1]][keys[2]] = data[name] ? data[name] === 'on' ? true : data[name] : false;
  1125. } else if (keys.length === 2) {
  1126. globalOptions[keys[0]][keys[1]] = data[name] ? data[name] === 'on' ? true : data[name] : false;
  1127. }
  1128. return element;
  1129. });
  1130. GM_setValue('globalOptions', globalOptions);
  1131. external_Swal_default().fire({
  1132. title: i18n('changeGlobalOptionsSuccess'),
  1133. icon: 'success'
  1134. });
  1135. } catch (error) {
  1136. throwError(error, 'saveData');
  1137. }
  1138. };
  1139. const changeGlobalOptions = showType => {
  1140. try {
  1141. let globalOptionsForm = `<form id="globalOptionsForm" class="auto-task-form">
  1142. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  1143. for (const [ type, data1 ] of Object.entries(globalOptions)) {
  1144. for (const [ option, data2 ] of Object.entries(data1)) {
  1145. if ([ 'other', 'position', 'hotKey', 'ASF' ].includes(type)) {
  1146. if (typeof data2 === 'boolean') {
  1147. globalOptionsForm += `<tr style="background-color: ${stringToColour(type)}44">${Object.keys(data1).indexOf(option) === 0 ? `<th rowspan="${Object.keys(data1).length}">${i18n(type)}</th>` : ''}<td>${i18n(option)}</td><td><label><input type="checkbox" name="${type}.${option}"${data2 ? ' checked="checked"' : ''}/><span><i></i></span></label></td></tr>`;
  1148. } else {
  1149. globalOptionsForm += `<tr style="background-color: ${stringToColour(type)}44">${Object.keys(data1).indexOf(option) === 0 ? `<th rowspan="${Object.keys(data1).length}" style="background-color: ${stringToColour(type)}66">${i18n(type)}</th>` : ''}<td>${i18n(option)}</td><td><input class="editOption" type="text" name="${type}.${option}" value="${data2}"/></td></tr>`;
  1150. }
  1151. } else {
  1152. for (const [ socialType, data3 ] of Object.entries(data2)) {
  1153. globalOptionsForm += `<tr style="background-color: ${stringToColour(option)}66">${Object.keys(data1).indexOf(option) === 0 ? `<th rowspan="${Object.keys(data1).map(key => Object.keys(data1[key]).length).reduce((acr, cur) => acr + cur)}" style="background-color: ${stringToColour(type)}66">${i18n(type)}</th>` : ''}<td>${option}.${i18n(socialType)}</td><td><label><input type="checkbox" name="${type}.${option}.${socialType}"${data3 ? ' checked="checked"' : ''}/><span><i></i></span></label></td></tr>`;
  1154. }
  1155. }
  1156. }
  1157. }
  1158. globalOptionsForm += '</tbody></table></form>';
  1159. if (showType === 'swal') {
  1160. external_Swal_default().fire({
  1161. title: i18n('globalOptions'),
  1162. html: globalOptionsForm,
  1163. showConfirmButton: true,
  1164. confirmButtonText: i18n('save'),
  1165. showCancelButton: true,
  1166. cancelButtonText: i18n('close')
  1167. }).then(({
  1168. isConfirmed
  1169. }) => {
  1170. if (isConfirmed) {
  1171. saveData();
  1172. }
  1173. });
  1174. } else {
  1175. $('body').append(`<h2>${i18n('globalOptions')}</h2>${globalOptionsForm}`);
  1176. }
  1177. } catch (error) {
  1178. throwError(error, 'changeGlobalOptions');
  1179. }
  1180. };
  1181. const data = {
  1182. website: '网站',
  1183. type: '类型',
  1184. edit: '编辑',
  1185. whiteList: '白名单',
  1186. skipTask: '跳过撤销任务',
  1187. whiteListOptions: '白名单设置',
  1188. changeWhiteListOption: '设置白名单(%0)',
  1189. whiteListNotFound: '找不到此项白名单: %0',
  1190. changeWhiteListSuccess: '白名单修改成功,刷新生效!',
  1191. changeWebsiteOptions: '网站设置',
  1192. changeGlobalOptions: '全局设置',
  1193. ok: '是',
  1194. save: '保存',
  1195. close: '关闭',
  1196. return: '返回',
  1197. option: '选项',
  1198. value: '值',
  1199. websiteOptions: '当前网站设置',
  1200. changeWebsiteOptionsSuccess: '更改当前网站设置成功,刷新生效!',
  1201. changeGlobalOptionsSuccess: '更改全局设置成功,刷新生效!',
  1202. needLogin: '请先登录!',
  1203. getTasksInfo: '正在获取并处理任务信息...',
  1204. gettingKey: '正在获取Key...',
  1205. verifyingTask: '正在验证任务',
  1206. notice: '自动任务脚本提醒',
  1207. noKeysLeft: '此页面已经没有剩余key了,是否关闭?',
  1208. giveawayEnded: '此活动已结束,是否关闭?',
  1209. giveawayNotWork: '此活动因某些原因(已结束/暂停/未开始...)不可用(如果是脚本误判请及时反馈),是否关闭?',
  1210. confirm: '确定',
  1211. cancel: '取消',
  1212. unKnown: '未知',
  1213. unKnownTaskType: '未识别的任务',
  1214. doing: '正在做任务',
  1215. allTasksComplete: '所有任务已完成!',
  1216. getTaskIdFailed: '获取任务Id失败!',
  1217. initSuccess: '%0 初始化成功!',
  1218. initFailed: '%0 初始化失败!',
  1219. errorLink: '链接错误: %0',
  1220. needInit: '请先初始化',
  1221. verifyingAuth: '正在验证%0凭证...',
  1222. updatingAuth: '正在更新%0凭证...',
  1223. refreshingToken: '正在刷新%0凭证...',
  1224. settingToken: '正在设置%0凭证...',
  1225. steamStoreTab: 'Steam商店(弹窗)',
  1226. steamCommunityTab: 'Steam社区(弹窗)',
  1227. initing: '正在初始化...',
  1228. getFailed: '获取%0失败!',
  1229. checkLoginFailed: '检测登录状态失败!',
  1230. checkLeftKeyFailed: '检测剩余Key失败!',
  1231. userId: '用户Id',
  1232. joiningGiveaway: '正在加入赠Key',
  1233. needJoinGiveaway: '需要先加入赠Key',
  1234. cannotUndo: '此网站不支持取消任务',
  1235. verifyAuth: '正在验证 %0 凭证...',
  1236. closePageNotice: '如果此页面没有自动关闭,请自行关闭本页面。',
  1237. errorReport: '检测到脚本报错,是否前往反馈BUG?',
  1238. visitingLink: '正在访问链接: ',
  1239. doTask: '做任务',
  1240. undoTask: '撤销任务',
  1241. verifyTask: '验证任务',
  1242. getKey: '获取Key',
  1243. selectAll: '全选',
  1244. selectNone: '全不选',
  1245. invertSelect: '反选',
  1246. doFreeTask: '加入免费赠品',
  1247. doPointTask: '加入点数赠品',
  1248. skipTaskOption: '设置中已配置跳过任务',
  1249. other: '其他',
  1250. globalOptions: '全局设置',
  1251. checkLogin: '登录检测</br>需要登录的网站自动登录,部分网站支持',
  1252. checkLeftKey: '剩余Key检测</br>赠Key活动结束提示是否关闭,部分网站支持',
  1253. twitterVerifyId: '通过尝试关注该账号验证Twitter凭证</br>默认为Twitter官方帐号 783214</br>不想关注官方账号可以改为自己的帐号',
  1254. youtubeVerifyChannel: '通过尝试订阅该频道验证YouTube凭证</br>默认为YouTube官方频道 UCrXUsMBcfTVqwAS7DKg9C0Q</br>不想关注官方频道可以改为自己的频道',
  1255. autoUpdateSource: '更新源</br>github: 需代理,实时更新</br>jsdelivr: 可不用代理,更新有延迟</br>standby: 备用</br>auto: 依次使用github, jsdelivr, standby源进行尝试更新',
  1256. saveGlobalOptions: '保存设置',
  1257. settingPage: '设置页面',
  1258. name: '名称',
  1259. version: '版本',
  1260. scriptManager: '脚本管理器',
  1261. script: '脚本',
  1262. environment: '环境',
  1263. os: '系统',
  1264. browser: '浏览器',
  1265. getId: '获取 %0 id',
  1266. getTwitterUserId: '获取Twitter用户id(获取id功能仅在设置页面可用)',
  1267. getYoutubeChannelId: '获取Youtube频道id(获取id功能仅在设置页面可用)',
  1268. showButton: '显示按钮',
  1269. hideButton: '隐藏按钮',
  1270. showLog: '显示日志',
  1271. hideLog: '隐藏日志',
  1272. defaultShowButton: '默认显示按钮',
  1273. defaultShowLog: '默认显示日志',
  1274. debug: '输出调试日志,不要开启此选项!',
  1275. receivePreview: '接收预览版更新',
  1276. position: '组件位置',
  1277. buttonSideX: '按钮区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1278. buttonSideY: '按钮区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1279. buttonDistance: '按钮区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1280. showButtonSideX: '显示按钮水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1281. showButtonSideY: '显示按钮垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1282. showButtonDistance: '显示按钮距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1283. logSideX: '日志区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1284. logSideY: '日志区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1285. logDistance: '日志区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1286. hotKey: '快捷键',
  1287. doTaskKey: '做任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1288. undoTaskKey: '撤销任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1289. toggleLogKey: '显示/隐藏日志快捷键</br>(实时预览功能仅在设置页面可用)',
  1290. tasksHistory: '任务历史',
  1291. clearHistory: '清空历史',
  1292. clearHistoryFinished: '已清空任务历史!',
  1293. deleteTask: '删除任务',
  1294. lastChangeTime: '最后一次修改时间',
  1295. clearTaskFinished: '删除以下任务完成!',
  1296. clearTaskFailed: '删除任务失败,没有找到任务名!',
  1297. syncData: '数据同步',
  1298. settingData: '正在上传数据...',
  1299. gettingData: '正在获取数据...',
  1300. help: '帮助',
  1301. fileName: '文件名',
  1302. upload2gist: '同步到Gist',
  1303. downloadFromGist: '从Gist同步',
  1304. saveAndTest: '保存配置并测试',
  1305. testSuccess: '测试成功!',
  1306. testFailed: '测试失败!',
  1307. saveAndTestNotice: '请先保存配置并测试!',
  1308. processingData: '正在处理数据...',
  1309. updatingData: '正在上传数据...',
  1310. syncDataSuccess: '同步数据成功!',
  1311. syncDataFailed: '同步数据失败,请在控制台查看错误信息!',
  1312. downloadingData: '正在下载数据...',
  1313. checkedNoData: '没有检测到远程数据,请确认配置是否正确!',
  1314. savingData: '正在保存数据...',
  1315. syncHistory: '同步任务历史',
  1316. checkUpdateFailed: '检测更新失败',
  1317. newVersionNotice: '检测到新版本V%0, <a class="high-light" href="%1" target="_blank">点此更新</a>',
  1318. language: '语言</br>目前仅支持zh: 中文, en: 英文',
  1319. gistOptions: 'Gist 设置',
  1320. swalNotice: '检测到您第一次安装V4版本脚本,请前往阅读用前必读内容!',
  1321. echoNotice: '检测到您第一次安装V4版本脚本,请<a class="high-light" href="%0" target="_blank">点此前往</a>阅读用前必读内容!',
  1322. noticeLink: 'https://auto-task-doc.js.org/guide/#用前必读',
  1323. toGithub: '前往Github反馈',
  1324. toKeylol: '前往其乐论坛反馈',
  1325. copySuccess: '错误信息已复制到剪切板,是否前往其乐论坛反馈?',
  1326. copyFailed: '请复制下方错误信息后前往Keylol论坛反馈!',
  1327. updateText: '%0 版本更新内容:',
  1328. Active: '进行中',
  1329. Ended: '已结束',
  1330. Banned: '已封禁',
  1331. Paused: '已暂停',
  1332. notStart: '未开始',
  1333. noRemoteData: '检测到远程无数据',
  1334. errorRemoteDataFormat: '远程数据格式错误',
  1335. updateHistory: '历史更新记录<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">点此查看</a>',
  1336. AsfEnabled: '使用ASF做Steam相关任务(需<a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a>插件)',
  1337. AsfIpcUrl: 'ASF IPC 地址',
  1338. AsfIpcPassword: 'ASF IPC 密码',
  1339. versionNotMatched: '脚本管理器版本过低,需TamperMonkey >= 5.2.0或TamperMonkey Beta >= 5.2.6196',
  1340. groups: '组',
  1341. officialGroups: '官方组',
  1342. wishlists: '愿望单',
  1343. follows: '游戏关注',
  1344. forums: '论坛',
  1345. workshops: '创意工坊收藏',
  1346. curators: '鉴赏家',
  1347. workshopVotes: '创意工坊点赞',
  1348. announcements: '社区通知',
  1349. steamCommunity: 'Steam社区',
  1350. steamStore: 'Steam商店',
  1351. licenses: '入库免费游戏',
  1352. playtests: '请求访问权限',
  1353. needLoginSteamStore: '请先<a href="https://store.steampowered.com/login/" target="_blank">登录Steam商店</a>',
  1354. needLoginSteamCommunity: '请先<a href="https://steamcommunity.com/login/home/" target="_blank">登录Steam社区</a>',
  1355. joiningSteamGroup: '正在加入Steam组',
  1356. leavingSteamGroup: '正在退出Steam组',
  1357. gettingSteamGroupId: '正在获取Steam组Id',
  1358. joiningSteamOfficialGroup: '正在加入Steam官方组',
  1359. leavingSteamOfficialGroup: '正在退出Steam官方组',
  1360. gettingSteamOfficialGroupId: '正在获取Steam官方组Id',
  1361. subscribingForum: '正在订阅Steam论坛',
  1362. unsubscribingForum: '正在取消订阅Steam论坛',
  1363. gettingForumId: '正在获取Steam论坛Id',
  1364. followingCurator: '正在关注Steam鉴赏家',
  1365. unfollowingCurator: '正在取关Steam鉴赏家',
  1366. gettingCuratorId: '正在获取Steam鉴赏家Id',
  1367. addingToWishlist: '正在添加游戏到Steam愿望单',
  1368. removingFromWishlist: '正在从Steam愿望单移除游戏',
  1369. followingGame: '正在关注Steam游戏',
  1370. unfollowingGame: '正在取关Steam游戏',
  1371. favoritingWorkshop: '正在收藏Steam创意工坊物品',
  1372. unfavoritingWorkshop: '正在取消收藏Steam创意工坊物品',
  1373. gettingWorkshopAppId: '正在获取Steam创意工坊物品Id',
  1374. votingUpWorkshop: '正在点赞Steam创意工坊物品',
  1375. gettingAnnouncementParams: '正在获取Steam通知信息',
  1376. likingAnnouncement: '正在点赞Steam通知',
  1377. changingArea: '正在更换Steam地区: %0...',
  1378. notNeededChangeArea: '当前地区不需要更换',
  1379. noAnotherArea: '请检测是否开启正确开启代理',
  1380. gettingAreaInfo: '正在获取Steam地区信息...',
  1381. changeAreaNotice: '疑似锁区游戏,尝试换区执行',
  1382. steamFinishNotice: 'Steam任务完成,尝试将购物车地区换回',
  1383. gettingSubid: '正在获取游戏subid',
  1384. addingFreeLicense: '正在入库',
  1385. missParams: '缺少参数',
  1386. gettingLicenses: '正在获取Licenses...',
  1387. requestingPlayTestAccess: '正在请求访问权限',
  1388. tryChangeAreaNotice: '此功能无法检测游戏是否限区,因此会尝试换区后再入库,换区失败也不影响后续入库',
  1389. gettingUserLink: '正在获取Steam用户社区链接...',
  1390. retry: '重试',
  1391. owned: '已拥有',
  1392. redirect: '重定向',
  1393. noSubid: '无法获取,跳过',
  1394. initingASF: '正在初始化ASF...',
  1395. servers: '服务器',
  1396. joiningDiscordServer: '正在加入Discord服务器',
  1397. leavingDiscordServer: '正在退出Discord服务器',
  1398. gettingDiscordGuild: '正在获取Discord服务器Id',
  1399. getDiscordAuthFailed: '获取Discord凭证失败,请检测Discord帐号是否已登录',
  1400. discordImportantNotice: '重要提醒!!!',
  1401. discordImportantNoticeText: '由于Discord网站后台更新,目前使用此脚本加组后可能会导致Discord帐号被强制退出,且需要两步验证才能正常登录,请谨慎使用!!!',
  1402. continue: '继续',
  1403. skipDiscordTask: '跳过Discord任务',
  1404. continueAndDontRemindAgain: '继续且不再提醒',
  1405. users: '用户',
  1406. loginIns: '请先<a href="https://www.instagram.com/accounts/login/" target="_blank">登录Instagram</a>',
  1407. insBanned: '您的Instagram账户已被封禁',
  1408. verifyingInsAuth: '正在验证Instagram凭证...',
  1409. gettingInsUserId: '正在获取Instagram用户Id',
  1410. followingIns: '正在关注Instagram用户',
  1411. unfollowingIns: '正在取关Instagram用户',
  1412. reddits: '社区/用户',
  1413. loginReddit: '请先<a href="https://www.reddit.com/login/" target="_blank">登录Reddit</a>',
  1414. changingRedditVersion: '正在切换Reddit为新版页面...',
  1415. joiningReddit: '正在加入Reddit社区',
  1416. leavingReddit: '正在退出Reddit社区',
  1417. followingRedditUser: '正在关注Reddit用户',
  1418. unfollowingRedditUser: '正在取关Reddit用户',
  1419. channels: '频道',
  1420. followingTwitchChannel: '正在关注Twitch频道',
  1421. unfollowingTwitchChannel: '正在取关Twitch频道',
  1422. gettingTwitchChannelId: '正在获取Twitch频道Id',
  1423. checkingTwitchIntegrity: '正在检查Twitch完整性...',
  1424. twitterUser: '推特用户',
  1425. retweets: '转推',
  1426. gettingTwitterUserId: '正在获取推特用户Id',
  1427. followingTwitterUser: '正在关注推特用户',
  1428. unfollowingTwitterUser: '正在取关推特用户',
  1429. retweetting: '正在转推',
  1430. unretweetting: '正在撤销转推',
  1431. names: '组/社区/动态',
  1432. loginVk: '请先<a href="https://vk.com/login/" target="_blank">登录Vk</a>',
  1433. gettingVkId: '正在获取Vk任务Id',
  1434. joiningVkGroup: '正在加入Vk组',
  1435. leavingVkGroup: '正在退出Vk组',
  1436. joiningVkPublic: '正在加入Vk社区',
  1437. leavingVkPublic: '正在退出Vk社区',
  1438. sendingVkWall: '正在转发Vk动态',
  1439. deletingVkWall: '正在撤销转发Vk动态',
  1440. youtubeChannel: 'YouTube频道',
  1441. likes: '点赞',
  1442. loginYtb: '请先<a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">登录YouTube</a>',
  1443. tryUpdateYtbAuth: '请尝试<a href="https://www.youtube.com/#auth" target="_blank">更新YouTube凭证</a>',
  1444. gettingYtbToken: '正在获取YouTube Token...',
  1445. followingYtbChannel: '正在订阅YouTube频道',
  1446. unfollowingYtbChannel: '正在退订YouTube频道',
  1447. likingYtbVideo: '正在点赞YouTube视频',
  1448. unlikingYtbVideo: '正在取消点赞YouTube视频',
  1449. giveKeyNoticeBefore: '每次验证间隔15s',
  1450. giveKeyNoticeAfter: '如果没有key, 请在<a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>查看',
  1451. noPoints: '点数不够,跳过抽奖',
  1452. getNeedPointsFailed: '获取所需点数失败,跳过抽奖',
  1453. joiningLottery: '正在加入抽奖',
  1454. doingGleamTask: '正在做Gleam任务...',
  1455. gettingGleamLink: '正在获取Gleam任务链接...',
  1456. gleamTaskNotice: '如果此页面长时间未关闭,请完成任一任务后自行关闭!',
  1457. verifiedGleamTasks: '已尝试验证所有任务,验证失败的任务请尝试手动验证或完成!',
  1458. campaign: '检测到人机验证,请完成验证后重新验证任务!',
  1459. gsNotice: '为避免得到"0000-0000-0000"key, 已自动屏蔽"Grab Key"按钮,获取key时请关闭脚本!',
  1460. giveeClubVerifyNotice: '正在验证任务...',
  1461. giveeClubVerifyFinished: '请等待验证完成后自行加入赠Key',
  1462. doingKeyhubTask: '正在做Keyhub任务...',
  1463. SweepWidgetNotice: '正在处理并验证任务,每次验证任务有1~3s间隔防止触发验证过快警告...',
  1464. tasksNotCompleted: '任务未完成',
  1465. confirmingTask: '正在跳过警告页面...'
  1466. };
  1467. const zh_CN = data;
  1468. const en_US_data = {
  1469. website: 'Website',
  1470. type: 'Type',
  1471. edit: 'Edit',
  1472. whiteList: 'Whitelist',
  1473. skipTask: 'Skip undo task',
  1474. whiteListOptions: 'Whitelist options',
  1475. changeWhiteListOption: 'Whitelist option(%0)',
  1476. whiteListNotFound: 'Cannot find this whitelist: %0',
  1477. changeWhiteListSuccess: 'The whitelist is successfully modified, and the page refresh will take effect!',
  1478. changeWebsiteOptions: 'Website options',
  1479. changeGlobalOptions: 'Global options',
  1480. ok: 'OK',
  1481. save: 'Save',
  1482. close: 'Close',
  1483. return: 'Return',
  1484. option: 'Option',
  1485. value: 'Value',
  1486. websiteOptions: 'Current website settings',
  1487. changeWebsiteOptionsSuccess: 'The current website setting is changed successfully, and the page refresh will take effect!',
  1488. changeGlobalOptionsSuccess: 'The global setting is changed successfully, and the refresh will take effect!',
  1489. needLogin: 'Please log in first!',
  1490. getTasksInfo: 'Obtaining and processing task information...',
  1491. gettingKey: 'Getting Key...',
  1492. verifyingTask: 'Verifying task',
  1493. notice: 'Automatic task script notice',
  1494. noKeysLeft: 'There are no more keys left on this page. Do you want to close it?',
  1495. giveawayEnded: 'This event has ended, do you want to close it?',
  1496. giveawayNotWork: 'This activity is unavailable for some reasons (banned/ended/paused/not started...)' + ' (if it is a script misjudgment, please give us feedback in time), is it closed?',
  1497. confirm: 'Confirm',
  1498. cancel: 'Cancel',
  1499. unKnown: 'Unknown',
  1500. unKnownTaskType: 'Unrecognized task',
  1501. doing: 'Doing a task',
  1502. allTasksComplete: 'All tasks have been completed!',
  1503. getTaskIdFailed: 'Failed to obtain task Id!',
  1504. initSuccess: '%0 was initialized successfully!',
  1505. initFailed: '%0 initialization failed!',
  1506. errorLink: 'Link error: %0',
  1507. needInit: 'Please initialize first',
  1508. verifyingAuth: 'Verifying %0 token...',
  1509. updatingAuth: 'Update %0 token...',
  1510. refreshingToken: 'Refreshing %0 token...',
  1511. settingToken: 'Setting %0 token...',
  1512. steamStoreTab: 'Steam store (new tab)',
  1513. steamCommunityTab: 'Steam community(new tab)',
  1514. initing: 'Initializing...',
  1515. getFailed: 'Failed to get %0!',
  1516. checkLoginFailed: 'Failed to detect login status!',
  1517. checkLeftKeyFailed: 'Failed to detect the remaining keys!',
  1518. userId: 'User Id',
  1519. joiningGiveaway: 'Joining giveaway',
  1520. needJoinGiveaway: 'Need to join the giveaway first',
  1521. cannotUndo: 'This website does not support canceling tasks',
  1522. verifyAuth: 'Verifying %0 token...',
  1523. closePageNotice: 'f this page does not close automatically, please close this page yourself.',
  1524. errorReport: 'A script error is detected, do you want to report the BUG?',
  1525. visitingLink: 'Visiting link: ',
  1526. doTask: 'DoTask',
  1527. undoTask: 'UndoTask',
  1528. verifyTask: 'Verify',
  1529. getKey: 'GetKey',
  1530. selectAll: 'SelectAll',
  1531. selectNone: 'SelectNone',
  1532. invertSelect: 'InvertSelect',
  1533. doFreeTask: 'FreeTask',
  1534. doPointTask: 'PointTask',
  1535. skipTaskOption: 'Skip task has been configured in the settings',
  1536. other: 'Other',
  1537. globalOptions: 'Global Options',
  1538. checkLogin: 'Login detection</br>Need to log in to the website automatically log in, part of this website supports.',
  1539. checkLeftKey: 'Key remaining detection</br>The end of the giveaway event prompts whether to close or not, part of this website supports.',
  1540. twitterVerifyId: 'Verify Twitter token by trying to follow the account.</br>The default is the official Twitter account 783214.</br>' + 'If you don\'t want to follow the official account, you can change it to your own account.',
  1541. youtubeVerifyChannel: 'Verify YouTube token by trying to subscribe to the channel.</br>' + 'The default is the official YouTube channel UCrXUsMBcfTVqwAS7DKg9C0Q.</br>' + 'If you don\'t want to follow the official channel, you can change it to your own channel.',
  1542. autoUpdateSource: 'The source to update</br>github: Fast update.</br>jsdelivr: Update is delayed.</br>' + 'standby: Standby source.</br>auto: Try to update using github, jsdelivr, standby sources in turn.',
  1543. saveGlobalOptions: 'SaveSettings',
  1544. settingPage: 'Setting Page',
  1545. name: 'Name',
  1546. version: 'Version',
  1547. scriptManager: 'Script Manager',
  1548. script: 'Script',
  1549. environment: 'Environment',
  1550. os: 'OS',
  1551. browser: 'Browser',
  1552. getId: 'Get %0 id',
  1553. getTwitterUserId: 'Get Twitter user id (Get id function is only available on the settings page).',
  1554. getYoutubeChannelId: 'Get Youtube channel id (Get id function is only available on the settings page).',
  1555. showButton: 'ShowButton',
  1556. hideButton: 'HideButton',
  1557. showLog: 'ShowLog',
  1558. hideLog: 'HideLog',
  1559. defaultShowButton: 'Default display button',
  1560. defaultShowLog: 'Display log by default',
  1561. debug: 'Output debug log, do not enable this option!',
  1562. receivePreview: 'Receive preview updates',
  1563. position: 'Component position',
  1564. buttonSideX: 'Horizontal positioning of the button area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1565. buttonSideY: 'The button area is positioned in the vertical direction (real-time preview function is only available on the settings page).' + '</br>top: top | bottom: bottom',
  1566. buttonDistance: 'The distance between the button area and the edge (the real-time preview function is only available on the setting page).' + '</br> Format: X distance, Y distance',
  1567. showButtonSideX: 'ShowButton horizontal positioning (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1568. showButtonSideY: 'ShowButton vertical positioning (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  1569. showButtonDistance: 'The distance between the ShowButton and the edge (real-time preview function is only available on the setting page).' + '</br> Format: X distance, Y distance',
  1570. logSideX: 'Horizontal positioning of the log area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  1571. logSideY: 'Vertical positioning of the log area (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  1572. logDistance: 'The distance between the log area and the edge (the real-time preview function is only available on the setting page).' + '</br> Format: X distance, Y distance',
  1573. hotKey: 'Shortcut key',
  1574. doTaskKey: 'DoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  1575. undoTaskKey: 'UndoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  1576. toggleLogKey: 'ShowLog/HideLog shortcut keys</br> (real-time preview function is only available on the settings page).',
  1577. tasksHistory: 'TasksHistory',
  1578. clearHistory: 'Clear history',
  1579. clearHistoryFinished: 'The mission history has been cleared!',
  1580. deleteTask: 'Delete task',
  1581. lastChangeTime: 'Last Change Time',
  1582. clearTaskFinished: 'Delete the following tasks completed!',
  1583. clearTaskFailed: 'Failed to delete the task, the task name was not found!',
  1584. syncData: 'DataSync',
  1585. settingData: 'Uploading data...',
  1586. gettingData: 'Getting data...',
  1587. help: 'Help',
  1588. fileName: 'Filename',
  1589. upload2gist: 'Sync to Gist',
  1590. downloadFromGist: 'Sync from Gist',
  1591. saveAndTest: 'Save configuration and test',
  1592. testSuccess: 'Test success!',
  1593. testFailed: 'Test failed!',
  1594. saveAndTestNotice: 'Please save the configuration and test first!',
  1595. processingData: 'Processing data...',
  1596. updatingData: 'Uploading data...',
  1597. syncDataSuccess: 'Synchronized data successfully!',
  1598. syncDataFailed: 'Failed to synchronize data, please check the error message on the console!',
  1599. downloadingData: 'Downloading data...',
  1600. checkedNoData: 'No remote data is detected, please confirm whether the configuration is correct!',
  1601. savingData: 'Saving data...',
  1602. syncHistory: 'Synchronize tasks history',
  1603. checkUpdateFailed: 'Check update failed',
  1604. newVersionNotice: 'Checked a new version V%0, <a class="high-light" href="%1" target="_blank">click to update</a>',
  1605. language: 'Language</br> Currently only supports zh: Chinese, en: English',
  1606. gistOptions: 'Gist Settings',
  1607. swalNotice: 'It is detected that you are installing the V4 version script for the first time' + ', please go to read the READ ME FIRST content before use!',
  1608. echoNotice: 'It is detected that you are installing the V4 version script for the first time' + ', please <a class="high-light" href="%0" target="_blank">click here</a> to read the READ ME FIRST content before use!',
  1609. noticeLink: 'https://auto-task-doc.js.org/en/guide/#read-me-first',
  1610. toGithub: 'Feedback(Github)',
  1611. toKeylol: 'Feedback(Keylol)',
  1612. copySuccess: 'The error message has been copied to the clipboard. Do you want to go to the Keylol forum to give feedback?',
  1613. copyFailed: 'Please copy the error information below and report back to the Keylol forum!',
  1614. updateText: 'Updates in version %0:',
  1615. Active: 'Active',
  1616. Ended: 'Ended',
  1617. Banned: 'Banned',
  1618. Paused: 'Paused',
  1619. notStart: 'notStart',
  1620. noRemoteData: 'No data remotely',
  1621. errorRemoteDataFormat: 'Remote data has wrong format',
  1622. updateHistory: '<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">Click here</a>' + ' to view the historical update record.',
  1623. AsfEnabled: 'Use ASF to do Steam related tasks (requires <a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a> plugin)',
  1624. AsfIpcUrl: 'ASF IPC URL',
  1625. AsfIpcPassword: 'ASF IPC Password',
  1626. groups: 'Group',
  1627. officialGroups: 'Official Group',
  1628. wishlists: 'Wishlist',
  1629. follows: 'Follow Game',
  1630. forums: 'Forum',
  1631. workshops: 'Favorite Workshop',
  1632. curators: 'Curator',
  1633. workshopVotes: 'Voteup Workshop',
  1634. announcements: 'Announcement',
  1635. steamCommunity: 'Steam Community',
  1636. steamStore: 'Steam Store',
  1637. licenses: 'Add License',
  1638. playtests: 'Playtest Access',
  1639. needLoginSteamStore: 'Please <a href="https://store.steampowered.com/login/" target="_blank">log in to the Steam Store</a>',
  1640. needLoginSteamCommunity: 'Please <a href="https://steamcommunity.com/login/home/" target="_blank">log in to the Steam Community</a>',
  1641. joiningSteamGroup: 'Joining Steam Group',
  1642. leavingSteamGroup: 'Leaving Steam Group',
  1643. gettingSteamGroupId: 'Getting Steam Group Id',
  1644. joiningSteamOfficialGroup: 'Joining Steam Official Group',
  1645. leavingSteamOfficialGroup: 'Leaving Steam Official Group',
  1646. gettingSteamOfficialGroupId: 'Getting Steam Official Group Id',
  1647. subscribingForum: 'Subscribing the Steam Forum',
  1648. unsubscribingForum: 'Unsubscribing the Steam Forum',
  1649. gettingForumId: 'Getting Steam Forum Id',
  1650. followingCurator: 'Following Steam Curator',
  1651. unfollowingCurator: 'Unfollowing Steam Curator',
  1652. gettingCuratorId: 'Getting Steam Curator Id',
  1653. addingToWishlist: 'Adding the game to the Steam wishlist',
  1654. removingFromWishlist: 'Removing the game from the Steam wishlist',
  1655. followingGame: 'Following Steam games',
  1656. unfollowingGame: 'Unfollowing Steam games',
  1657. favoritingWorkshop: 'Favouring Steam Workshop Items',
  1658. unfavoritingWorkshop: 'Unfavoriting Steam Workshop Items',
  1659. gettingWorkshopAppId: 'Getting Steam Workshop Item Id',
  1660. votingUpWorkshop: 'Liking Steam workshop items',
  1661. gettingAnnouncementParams: 'Getting Steam announcement information',
  1662. likingAnnouncement: 'Liking Steam announcement',
  1663. changingArea: 'Changing Steam area: %0...',
  1664. notNeededChangeArea: 'The current area does not need to be changed',
  1665. noAnotherArea: 'Please check whether the proxy is turned on correctly',
  1666. gettingAreaInfo: 'Getting Steam area information...',
  1667. changeAreaNotice: 'Suspected of a locked zone game, try to change the zone to execute',
  1668. steamFinishNotice: 'Steam task completed, try to change the shopping cart area back to ',
  1669. gettingSubid: 'Getting subid',
  1670. addingFreeLicense: 'Adding free license',
  1671. missParams: 'Missing parameters',
  1672. gettingLicenses: 'Getting licenses...',
  1673. requestingPlayTestAccess: 'Requesting play test access',
  1674. tryChangeAreaNotice: 'This function cannot detect whether the game is limited, so it will try to change the area before entering the library' + '. Failure to change the area will not affect the subsequent storage.',
  1675. versionNotMatched: 'The script manager version is too low, requiring TamperMonkey >= 5.2.0 or TamperMonkey Beta >= 5.2.6196',
  1676. gettingUserLink: 'Getting steam user community link...',
  1677. retry: 'Retry',
  1678. owned: 'Owned',
  1679. redirect: 'Redirect',
  1680. noSubid: 'skip due to unrecognized',
  1681. initingASF: 'Initing ASF...',
  1682. servers: 'Server',
  1683. joiningDiscordServer: 'Joining Discord Server',
  1684. leavingDiscordServer: 'Leaving Discord Server',
  1685. gettingDiscordGuild: 'Getting Discord server Id',
  1686. getDiscordAuthFailed: 'Failed to get Discord token, please check whether the Discord account is logged in',
  1687. discordImportantNotice: 'Important Reminder! ! !',
  1688. discordImportantNoticeText: 'Due to the background update of the Discord website, currently using this script to join a group may cause the Discord account to be forcibly logged out, and two-step verification is required to log in normally, please use it with caution! ! !',
  1689. continue: 'Continue',
  1690. skipDiscordTask: 'Skip',
  1691. continueAndDontRemindAgain: 'Continue without Reminders',
  1692. users: 'User',
  1693. loginIns: 'Please <a href="https://www.instagram.com/accounts/login/" target="_blank">log in to Instagram</a>',
  1694. insBanned: 'Your Instagram account has been banned',
  1695. verifyingInsAuth: 'Verifying Instagram token...',
  1696. gettingInsUserId: 'Getting Instagram user Id',
  1697. followingIns: 'Following Instagram user',
  1698. unfollowingIns: 'Unfollowing Instagram user',
  1699. reddits: 'Reddit/User',
  1700. loginReddit: 'Please <a href="https://www.reddit.com/login/" target="_blank">log in to Reddit</a>',
  1701. changingRedditVersion: 'Switching Reddit to a new version page...',
  1702. joiningReddit: 'Joining the Reddit',
  1703. leavingReddit: 'Leaving the Reddit',
  1704. followingRedditUser: 'Following Reddit User',
  1705. unfollowingRedditUser: 'Unfollowing Reddit User',
  1706. channels: 'Channel',
  1707. followingTwitchChannel: 'Following Twitch Channel',
  1708. unfollowingTwitchChannel: 'Unfollowing Twitch Channel',
  1709. gettingTwitchChannelId: 'Getting Twitch Channel Id',
  1710. checkingTwitchIntegrity: 'Checking Twitch integrity...',
  1711. twitterUser: 'Twitter User',
  1712. retweets: 'Retweet',
  1713. gettingTwitterUserId: 'Getting Twitter User Id',
  1714. followingTwitterUser: 'Following Twitter User',
  1715. unfollowingTwitterUser: 'Unfollowing Twitter User',
  1716. retweetting: 'Retweetting',
  1717. unretweetting: 'Unretweetting',
  1718. names: 'Group/Public/Wall',
  1719. loginVk: 'Please <a href="https://vk.com/login/" target="_blank">log in to Vk</a>',
  1720. gettingVkId: 'Getting Vk task Id',
  1721. joiningVkGroup: 'Joining Vk Group',
  1722. leavingVkGroup: 'Leaving Vk Group',
  1723. joiningVkPublic: 'Joining Vk Public',
  1724. leavingVkPublic: 'Leaving Vk Public',
  1725. sendingVkWall: 'Sending Vk Wall',
  1726. deletingVkWall: 'Deleting Vk Wall',
  1727. youtubeChannel: 'YouTube Channel',
  1728. likes: 'Like',
  1729. loginYtb: 'Please <a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">log in to YouTube</a>',
  1730. tryUpdateYtbAuth: 'Please try to <a href="https://www.youtube.com/#auth" target="_blank">update YouTube token</a>',
  1731. gettingYtbToken: 'Getting YouTube Token...',
  1732. followingYtbChannel: 'Subscribing to YouTube channel',
  1733. unfollowingYtbChannel: 'Unsubscribing to YouTube channel',
  1734. likingYtbVideo: 'Liking YouTube video',
  1735. unlikingYtbVideo: 'Unliking YouTube video',
  1736. giveKeyNoticeBefore: 'Each verification interval is 15s',
  1737. giveKeyNoticeAfter: 'If there is no key, please check at <a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>',
  1738. noPoints: 'Not enough points, skip the lottery',
  1739. getNeedPointsFailed: 'ailed to obtain the required points, skip the lottery',
  1740. joiningLottery: 'Joining the lottery',
  1741. doingGleamTask: 'Doing Gleam Task...',
  1742. gettingGleamLink: 'Getting Gleam task link...',
  1743. gleamTaskNotice: 'If this page has not been closed for a long time, please close it yourself after completing any task!',
  1744. verifiedGleamTasks: 'Attempted to verify all tasks. If the verification fails, please try to verify manually or complete it!',
  1745. campaign: 'ReCAPTCHA detected, please complete it and re-verify the tasks!',
  1746. gsNotice: 'In order to avoid getting the "0000-0000-0000" key, the "Grab Key" button has been hidden,' + ' please close the script when obtaining the key!',
  1747. giveeClubVerifyNotice: 'Verifying task...',
  1748. giveeClubVerifyFinished: 'Wait for the verification to complete and join it by yourself',
  1749. doingKeyhubTask: 'Doing Keyhub Task...',
  1750. SweepWidgetNotice: 'The task is being processed and verified. ' + 'There is an interval of 1~3s for each verification task to prevent the triggering of too fast verification warning...',
  1751. tasksNotCompleted: 'Tasks Not Completed',
  1752. confirmingTask: 'Confirming task...'
  1753. };
  1754. const en_US = en_US_data;
  1755. const languages = {
  1756. zh: zh_CN,
  1757. en: en_US
  1758. };
  1759. const language = [ 'zh', 'en' ].includes(globalOptions.other.language) ? globalOptions.other.language : 'en';
  1760. const I18n = (key, ...argvs) => {
  1761. if (!languages[language]?.[key]) {
  1762. return key;
  1763. }
  1764. return languages[language][key].replace(/%([\d]+)/g, (match, index) => argvs[parseInt(index, 10)]);
  1765. };
  1766. const i18n = I18n;
  1767. function throwError(error, name) {
  1768. if (window.TRACE) {
  1769. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  1770. }
  1771. external_Swal_default().fire({
  1772. title: i18n('errorReport'),
  1773. icon: 'error',
  1774. showCancelButton: true,
  1775. confirmButtonText: i18n('toGithub'),
  1776. showDenyButton: true,
  1777. denyButtonText: i18n('toKeylol'),
  1778. cancelButtonText: i18n('close')
  1779. }).then(({
  1780. isDenied,
  1781. isConfirmed
  1782. }) => {
  1783. if (isConfirmed) {
  1784. GM_openInTab(`https://github.com/HCLonely/auto-task-v4/issues/new?title=${encodeURIComponent(`[BUG] 脚本报错: ${name}`)}&labels=bug&template=bug_report.yml&website=${encodeURIComponent(window.location.href)}&browser=${encodeURIComponent(JSON.stringify((0,
  1785. javascript_utils_umd_min.ua)(), null, 4))}&manager=${encodeURIComponent(`${GM_info.scriptHandler} ${GM_info.version}`)}&user-script=${encodeURIComponent(GM_info.script.version)}&logs=${encodeURIComponent(error.stack || 'null')}&run-logs=${encodeURIComponent($.makeArray($('#auto-task-info>li')).map(element => element.innerText).join('\n'))}`, {
  1786. active: true
  1787. });
  1788. } else if (isDenied) {
  1789. const text = `错误链接: [url=${window.location.href}]${window.location.href}[/url]
  1790.  
  1791. 环境:
  1792.  
  1793. [code]${JSON.stringify((0, javascript_utils_umd_min.ua)(), null, 4)}[/code]
  1794.  
  1795. 脚本管理器: ${GM_info.scriptHandler} ${GM_info.version}
  1796. 脚本版本: ${GM_info.script.version}
  1797.  
  1798. 报错信息:
  1799. [code]${error.stack}[/code]
  1800.  
  1801. 执行日志:
  1802. [code]${$.makeArray($('#auto-task-info>li')).map(element => element.innerText).join('\n')}[/code]`;
  1803. GM_setClipboard(text);
  1804. external_Swal_default().fire({
  1805. title: i18n('copySuccess'),
  1806. icon: 'success',
  1807. confirmButtonText: i18n('ok')
  1808. }).then(() => {
  1809. GM_openInTab('https://keylol.com/forum.php?mod=post&action=reply&fid=319&tid=777450', {
  1810. active: true
  1811. });
  1812. });
  1813. }
  1814. });
  1815. console.log('%c%s', 'color:white;background:red', `Auto-Task[Error]: ${name}\n${error.stack}`);
  1816. }
  1817. class Social {
  1818. tasks;
  1819. getRealParams(name, links, doTask, link2param) {
  1820. try {
  1821. let realParams = [];
  1822. if (links.length > 0) {
  1823. realParams = [ ...realParams, ...links.map(link => link2param(link)).filter(link => link) ];
  1824. }
  1825. if (!doTask && this.tasks[name].length > 0) {
  1826. realParams = [ ...realParams, ...this.tasks[name] ];
  1827. }
  1828. return unique(realParams);
  1829. } catch (error) {
  1830. throwError(error, 'Social.getRealParams');
  1831. return [];
  1832. }
  1833. }
  1834. }
  1835. const social_Social = Social;
  1836. class Discord extends social_Social {
  1837. tasks;
  1838. whiteList;
  1839. #auth = GM_getValue('discordAuth') || {};
  1840. #cache = GM_getValue('discordCache') || {};
  1841. #initialized = false;
  1842. constructor() {
  1843. super();
  1844. const defaultTasksTemplate = {
  1845. servers: []
  1846. };
  1847. this.tasks = defaultTasksTemplate;
  1848. this.whiteList = {
  1849. ...defaultTasksTemplate,
  1850. ...GM_getValue('whiteList')?.discord || {}
  1851. };
  1852. }
  1853. async init(action) {
  1854. try {
  1855. if (!GM_getValue('dontRemindDiscordAgain')) {
  1856. const result = await external_Swal_default().fire({
  1857. title: i18n('discordImportantNotice'),
  1858. text: i18n('discordImportantNoticeText'),
  1859. showCancelButton: true,
  1860. showDenyButton: true,
  1861. confirmButtonText: i18n('continue'),
  1862. cancelButtonText: i18n('skipDiscordTask'),
  1863. denyButtonText: i18n('continueAndDontRemindAgain')
  1864. }).then(({
  1865. isConfirmed,
  1866. isDenied
  1867. }) => {
  1868. if (isConfirmed) {
  1869. return true;
  1870. }
  1871. if (isDenied) {
  1872. GM_setValue('dontRemindDiscordAgain', true);
  1873. return true;
  1874. }
  1875. return false;
  1876. });
  1877. if (!result) {
  1878. this.#initialized = false;
  1879. return 'skip';
  1880. }
  1881. }
  1882. if (GM_getValue('dontRemindDiscordAgain') || action === 'do' && !globalOptions.doTask.discord.servers || action === 'undo' && !globalOptions.undoTask.discord.servers) {
  1883. this.#initialized = false;
  1884. return 'skip';
  1885. }
  1886. if (this.#initialized) {
  1887. return true;
  1888. }
  1889. if (!this.#auth.auth) {
  1890. if (await this.#updateAuth()) {
  1891. this.#initialized = true;
  1892. return true;
  1893. }
  1894. return false;
  1895. }
  1896. const isVerified = await this.#verifyAuth();
  1897. if (isVerified) {
  1898. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  1899. this.#initialized = true;
  1900. return true;
  1901. }
  1902. GM_setValue('discordAuth', {
  1903. auth: null
  1904. });
  1905. if (await this.#updateAuth()) {
  1906. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  1907. this.#initialized = true;
  1908. return true;
  1909. }
  1910. scripts_echoLog({}).error(i18n('initFailed', 'Discord'));
  1911. return false;
  1912. } catch (error) {
  1913. throwError(error, 'Discord.init');
  1914. return false;
  1915. }
  1916. }
  1917. async #verifyAuth() {
  1918. try {
  1919. const logStatus = scripts_echoLog({
  1920. text: i18n('verifyingAuth', 'Discord')
  1921. });
  1922. const {
  1923. result,
  1924. statusText,
  1925. status,
  1926. data
  1927. } = await tools_httpRequest({
  1928. url: 'https://discord.com/api/v6/users/@me',
  1929. method: 'HEAD',
  1930. headers: {
  1931. authorization: this.#auth.auth
  1932. }
  1933. });
  1934. if (result === 'Success') {
  1935. if (data?.status === 200) {
  1936. logStatus.success();
  1937. return true;
  1938. }
  1939. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  1940. return false;
  1941. }
  1942. logStatus.error(`${result}:${statusText}(${status})`);
  1943. return false;
  1944. } catch (error) {
  1945. throwError(error, 'Discord.verifyAuth');
  1946. return false;
  1947. }
  1948. }
  1949. async #updateAuth() {
  1950. try {
  1951. const logStatus = scripts_echoLog({
  1952. text: i18n('updatingAuth', 'Discord')
  1953. });
  1954. return await new Promise(resolve => {
  1955. const newTab = GM_openInTab('https://discord.com/channels/@me', {
  1956. active: true,
  1957. insert: true,
  1958. setParent: true
  1959. });
  1960. newTab.name = 'ATv4_discordAuth';
  1961. newTab.onclose = async () => {
  1962. const auth = GM_getValue('discordAuth')?.auth;
  1963. if (auth) {
  1964. this.#auth = {
  1965. auth: auth
  1966. };
  1967. logStatus.success();
  1968. resolve(await this.#verifyAuth());
  1969. } else {
  1970. logStatus.error('Error: Update discord auth failed!');
  1971. resolve(false);
  1972. }
  1973. };
  1974. });
  1975. } catch (error) {
  1976. throwError(error, 'Discord.updateAuth');
  1977. return false;
  1978. }
  1979. }
  1980. async #joinServer(inviteId) {
  1981. try {
  1982. const logStatus = scripts_echoLog({
  1983. type: 'joiningDiscordServer',
  1984. text: inviteId
  1985. });
  1986. const {
  1987. result,
  1988. statusText,
  1989. status,
  1990. data
  1991. } = await tools_httpRequest({
  1992. url: `https://discord.com/api/v9/invites/${inviteId}`,
  1993. method: 'POST',
  1994. dataType: 'json',
  1995. headers: {
  1996. authorization: this.#auth.auth,
  1997. origin: 'https://discord.com',
  1998. referer: `https://discord.com/invite/${inviteId}`
  1999. }
  2000. });
  2001. if (result === 'Success' && data?.status === 200) {
  2002. logStatus.success();
  2003. const guild = String(data.response?.guild?.id);
  2004. if (guild) {
  2005. this.#setCache(inviteId, guild);
  2006. this.tasks.servers = unique([ ...this.tasks.servers, inviteId ]);
  2007. }
  2008. return true;
  2009. }
  2010. logStatus.error(`${result}:${statusText}(${status})`);
  2011. return false;
  2012. } catch (error) {
  2013. throwError(error, 'Discord.joinServer');
  2014. return false;
  2015. }
  2016. }
  2017. async #leaveServer(inviteId) {
  2018. try {
  2019. if (this.whiteList.servers.includes(inviteId)) {
  2020. scripts_echoLog({
  2021. type: 'whiteList',
  2022. text: 'Discord.leaveServer',
  2023. id: inviteId
  2024. });
  2025. return true;
  2026. }
  2027. const guild = await this.#getGuild(inviteId);
  2028. if (!guild) {
  2029. return false;
  2030. }
  2031. const logStatus = scripts_echoLog({
  2032. type: 'leavingDiscordServer',
  2033. text: guild
  2034. });
  2035. const {
  2036. result,
  2037. statusText,
  2038. status,
  2039. data
  2040. } = await tools_httpRequest({
  2041. url: `https://discord.com/api/v9/users/@me/guilds/${guild}`,
  2042. method: 'DELETE',
  2043. headers: {
  2044. authorization: this.#auth.auth
  2045. }
  2046. });
  2047. if (result === 'Success' && data?.status === 204) {
  2048. logStatus.success();
  2049. return true;
  2050. }
  2051. logStatus.error(`${result}:${statusText}(${status})`);
  2052. return false;
  2053. } catch (error) {
  2054. throwError(error, 'Discord.leaveServer');
  2055. return false;
  2056. }
  2057. }
  2058. async #getGuild(inviteId) {
  2059. try {
  2060. const logStatus = scripts_echoLog({
  2061. type: 'gettingDiscordGuild',
  2062. text: inviteId
  2063. });
  2064. const guild = this.#cache[inviteId];
  2065. if (guild) {
  2066. logStatus.success();
  2067. return guild;
  2068. }
  2069. const {
  2070. result,
  2071. statusText,
  2072. status,
  2073. data
  2074. } = await tools_httpRequest({
  2075. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2076. responseType: 'json',
  2077. method: 'GET'
  2078. });
  2079. if (result === 'Success' && data?.status === 200) {
  2080. const guild = data.response?.guild?.id;
  2081. if (guild) {
  2082. logStatus.success();
  2083. this.#setCache(inviteId, guild);
  2084. return guild;
  2085. }
  2086. logStatus.error(`${result}:${statusText}(${status})`);
  2087. return false;
  2088. }
  2089. logStatus.error(`${result}:${statusText}(${status})`);
  2090. return false;
  2091. } catch (error) {
  2092. throwError(error, 'Discord.getGuild');
  2093. return false;
  2094. }
  2095. }
  2096. async toggle({
  2097. doTask = true,
  2098. serverLinks = []
  2099. }) {
  2100. try {
  2101. if (!this.#initialized) {
  2102. scripts_echoLog({
  2103. text: i18n('needInit')
  2104. });
  2105. return false;
  2106. }
  2107. const prom = [];
  2108. if (doTask && !globalOptions.doTask.discord.servers || !doTask && !globalOptions.undoTask.discord.servers) {
  2109. scripts_echoLog({
  2110. type: 'globalOptionsSkip',
  2111. text: 'discord.servers'
  2112. });
  2113. } else {
  2114. const realServers = this.getRealParams('servers', serverLinks, doTask, link => link.match(/invite\/(.+)/)?.[1]);
  2115. if (realServers.length > 0) {
  2116. for (const server of realServers) {
  2117. if (doTask) {
  2118. prom.push(this.#joinServer(server));
  2119. } else {
  2120. prom.push(this.#leaveServer(server));
  2121. }
  2122. await delay(1e3);
  2123. }
  2124. }
  2125. }
  2126. return await Promise.all(prom).then(() => true);
  2127. } catch (error) {
  2128. throwError(error, 'Discord.toggleServers');
  2129. return false;
  2130. }
  2131. }
  2132. #setCache(inviteId, guild) {
  2133. try {
  2134. this.#cache[inviteId] = guild;
  2135. GM_setValue('discordCache', this.#cache);
  2136. } catch (error) {
  2137. throwError(error, 'Discord.setCache');
  2138. }
  2139. }
  2140. }
  2141. const social_Discord = Discord;
  2142. class Instagram extends social_Social {
  2143. tasks;
  2144. whiteList;
  2145. #cache = GM_getValue('instagramCache') || {};
  2146. #auth = {};
  2147. #initialized = false;
  2148. constructor() {
  2149. super();
  2150. const defaultTasksTemplate = {
  2151. users: []
  2152. };
  2153. this.tasks = defaultTasksTemplate;
  2154. this.whiteList = {
  2155. ...defaultTasksTemplate,
  2156. ...GM_getValue('whiteList')?.instagram || {}
  2157. };
  2158. }
  2159. async init() {
  2160. try {
  2161. if (this.#initialized) {
  2162. return true;
  2163. }
  2164. const isVerified = await this.#getUserInfo();
  2165. if (isVerified) {
  2166. scripts_echoLog({}).success(i18n('initSuccess', 'Instagram'));
  2167. this.#initialized = true;
  2168. return true;
  2169. }
  2170. scripts_echoLog({}).error(i18n('initFailed', 'Instagram'));
  2171. return false;
  2172. } catch (error) {
  2173. throwError(error, 'Instagram.init');
  2174. return false;
  2175. }
  2176. }
  2177. async #getUserInfo(name = 'instagram') {
  2178. try {
  2179. const logStatus = scripts_echoLog({
  2180. type: name === 'instagram' ? 'verifyingInsAuth' : 'gettingInsUserId',
  2181. text: name
  2182. });
  2183. const userId = this.#cache[name];
  2184. if (userId && name !== 'instagram') {
  2185. logStatus.success();
  2186. return userId;
  2187. }
  2188. const {
  2189. result,
  2190. statusText,
  2191. status,
  2192. data
  2193. } = await tools_httpRequest({
  2194. url: `https://www.instagram.com/${name}/`,
  2195. method: 'GET'
  2196. });
  2197. if (result === 'Success') {
  2198. if (data?.finalUrl.includes('accounts/login')) {
  2199. logStatus.error(`Error:${i18n('loginIns')}`, true);
  2200. return false;
  2201. } else if (data?.finalUrl.includes('www.instagram.com/challenge')) {
  2202. logStatus.error(`Error:${i18n('insBanned')}`);
  2203. return false;
  2204. }
  2205. if (data?.status === 200) {
  2206. const csrftoken = data.responseText.match(/"csrf_token":"(.+?)"/)?.[1];
  2207. const hash = data.responseText.match(/"rollout_hash":"(.+?)"/)?.[1];
  2208. if (name === 'instagram') {
  2209. if (csrftoken && hash) {
  2210. this.#auth = {
  2211. csrftoken: csrftoken,
  2212. hash: hash
  2213. };
  2214. return true;
  2215. }
  2216. return false;
  2217. }
  2218. const id = data.responseText.match(/"profilePage_([\d]+?)"/)?.[1];
  2219. if (id) {
  2220. this.#setCache(name, id);
  2221. logStatus.success();
  2222. return id;
  2223. }
  2224. logStatus.error('Error: Get ins data error!');
  2225. return false;
  2226. }
  2227. logStatus.error(`${result}:${statusText}(${status})`);
  2228. return false;
  2229. }
  2230. return false;
  2231. } catch (error) {
  2232. throwError(error, 'Instagram.getUserInfo');
  2233. return false;
  2234. }
  2235. }
  2236. async #followUser(name) {
  2237. try {
  2238. const id = await this.#getUserInfo(name);
  2239. if (!id) {
  2240. return false;
  2241. }
  2242. const logStatus = scripts_echoLog({
  2243. type: 'followingIns',
  2244. text: name
  2245. });
  2246. const {
  2247. result,
  2248. statusText,
  2249. status,
  2250. data
  2251. } = await tools_httpRequest({
  2252. url: `https://www.instagram.com/web/friendships/${id}/follow/`,
  2253. method: 'POST',
  2254. dataType: 'json',
  2255. headers: {
  2256. 'x-csrftoken': this.#auth.csrftoken,
  2257. origin: 'https://www.instagram.com',
  2258. referer: `https://www.instagram.com/${name}/`,
  2259. 'content-type': 'application/x-www-form-urlencoded',
  2260. 'sec-fetch-site': 'same-origin',
  2261. 'x-instagram-ajax': this.#auth.hash
  2262. }
  2263. });
  2264. if (result === 'Success') {
  2265. if (data?.status === 200 && data.response?.result === 'following') {
  2266. logStatus.success();
  2267. this.tasks.users = unique([ ...this.tasks.users, name ]);
  2268. return true;
  2269. }
  2270. logStatus.error(`Error:${data?.response?.feedback_message || `${data?.statusText}(${data?.status})`}`);
  2271. return false;
  2272. }
  2273. logStatus.error(`${result}:${statusText}(${status})`);
  2274. return false;
  2275. } catch (error) {
  2276. throwError(error, 'Instagram.followUser');
  2277. return false;
  2278. }
  2279. }
  2280. async #unfollowUser(name) {
  2281. try {
  2282. if (this.whiteList.users.includes(name)) {
  2283. scripts_echoLog({
  2284. type: 'whiteList',
  2285. text: 'Instagram.unfollowUser',
  2286. id: name
  2287. });
  2288. return true;
  2289. }
  2290. const id = await this.#getUserInfo(name);
  2291. if (!id) {
  2292. return false;
  2293. }
  2294. const logStatus = scripts_echoLog({
  2295. type: 'unfollowingIns',
  2296. text: name
  2297. });
  2298. const {
  2299. result,
  2300. statusText,
  2301. status,
  2302. data
  2303. } = await tools_httpRequest({
  2304. url: `https://www.instagram.com/web/friendships/${id}/unfollow/`,
  2305. method: 'POST',
  2306. dataType: 'json',
  2307. headers: {
  2308. 'x-csrftoken': this.#auth.csrftoken,
  2309. origin: 'https://www.instagram.com',
  2310. referer: `https://www.instagram.com/${name}/`,
  2311. 'content-type': 'application/x-www-form-urlencoded',
  2312. 'sec-fetch-site': 'same-origin',
  2313. 'x-instagram-ajax': this.#auth.hash
  2314. }
  2315. });
  2316. if (result === 'Success') {
  2317. if (data?.status === 200 && data.response?.status === 'ok') {
  2318. logStatus.success();
  2319. return true;
  2320. }
  2321. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2322. return false;
  2323. }
  2324. logStatus.error(`${result}:${statusText}(${status})`);
  2325. return false;
  2326. } catch (error) {
  2327. throwError(error, 'Instagram.unfollowUser');
  2328. return false;
  2329. }
  2330. }
  2331. async toggle({
  2332. doTask = true,
  2333. userLinks = []
  2334. }) {
  2335. try {
  2336. if (!this.#initialized) {
  2337. scripts_echoLog({
  2338. text: i18n('needInit')
  2339. });
  2340. return false;
  2341. }
  2342. const prom = [];
  2343. if (doTask && !globalOptions.doTask.instagram.users || !doTask && !globalOptions.undoTask.instagram.users) {
  2344. scripts_echoLog({
  2345. type: 'globalOptionsSkip',
  2346. text: 'instagram.users'
  2347. });
  2348. } else {
  2349. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1]);
  2350. if (realUsers.length > 0) {
  2351. for (const username of realUsers) {
  2352. if (doTask) {
  2353. prom.push(this.#followUser(username));
  2354. } else {
  2355. prom.push(this.#unfollowUser(username));
  2356. }
  2357. await delay(1e3);
  2358. }
  2359. }
  2360. }
  2361. return await Promise.all(prom).then(() => true);
  2362. } catch (error) {
  2363. throwError(error, 'Instagram.toggleUsers');
  2364. return false;
  2365. }
  2366. }
  2367. #setCache(name, id) {
  2368. try {
  2369. this.#cache[name] = id;
  2370. GM_setValue('instagramCache', this.#cache);
  2371. } catch (error) {
  2372. throwError(error, 'Instagram.setCache');
  2373. }
  2374. }
  2375. }
  2376. const social_Instagram = Instagram;
  2377. class Reddit extends social_Social {
  2378. tasks;
  2379. whiteList;
  2380. #auth;
  2381. #initialized = false;
  2382. constructor() {
  2383. super();
  2384. const defaultTasksTemplate = {
  2385. reddits: []
  2386. };
  2387. this.tasks = defaultTasksTemplate;
  2388. this.whiteList = {
  2389. ...defaultTasksTemplate,
  2390. ...GM_getValue('whiteList')?.reddit || {}
  2391. };
  2392. }
  2393. async init() {
  2394. try {
  2395. if (this.#initialized) {
  2396. return true;
  2397. }
  2398. const isVerified = await this.#updateAuth();
  2399. if (isVerified) {
  2400. scripts_echoLog({}).success(i18n('initSuccess', 'Reddit'));
  2401. this.#initialized = true;
  2402. return true;
  2403. }
  2404. scripts_echoLog({}).error(i18n('initFailed', 'Reddit'));
  2405. return false;
  2406. } catch (error) {
  2407. throwError(error, 'Reddit.init');
  2408. return false;
  2409. }
  2410. }
  2411. async #useBeta() {
  2412. try {
  2413. const logStatus = scripts_echoLog({
  2414. text: i18n('changingRedditVersion')
  2415. });
  2416. return await new Promise(resolve => {
  2417. const newTab = GM_openInTab('https://www.reddit.com/', {
  2418. active: true,
  2419. insert: true,
  2420. setParent: true
  2421. });
  2422. newTab.name = 'ATv4_redditAuth';
  2423. newTab.onclose = async () => {
  2424. logStatus.success();
  2425. resolve(await this.#updateAuth(true));
  2426. };
  2427. });
  2428. } catch (error) {
  2429. throwError(error, 'Reddit.useBeta');
  2430. return false;
  2431. }
  2432. }
  2433. async #updateAuth(beta = false) {
  2434. try {
  2435. const logStatus = scripts_echoLog({
  2436. text: i18n('updatingAuth', 'Reddit')
  2437. });
  2438. const {
  2439. result,
  2440. statusText,
  2441. status,
  2442. data
  2443. } = await tools_httpRequest({
  2444. url: 'https://www.reddit.com/',
  2445. method: 'GET',
  2446. nochche: true,
  2447. headers: {
  2448. 'Cache-Control': 'no-cache'
  2449. }
  2450. });
  2451. if (result === 'Success') {
  2452. if (data?.responseText.includes('www.reddit.com/login/')) {
  2453. logStatus.error(`Error:${i18n('loginReddit')}`, true);
  2454. return false;
  2455. }
  2456. if (data?.status === 200) {
  2457. if (data.responseText.includes('redesign-beta-optin-btn') && !beta) {
  2458. return await this.#useBeta();
  2459. }
  2460. const accessToken = data.responseText.match(/"accessToken":"(.*?)","expires":"(.*?)"/)?.[1];
  2461. if (accessToken) {
  2462. this.#auth = {
  2463. token: accessToken
  2464. };
  2465. logStatus.success();
  2466. return true;
  2467. }
  2468. logStatus.error('Error: Parameter "accessToken" not found!');
  2469. return false;
  2470. }
  2471. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2472. return false;
  2473. }
  2474. logStatus.error(`${result}:${statusText}(${status})`);
  2475. return false;
  2476. } catch (error) {
  2477. throwError(error, 'Reddit.updateAuth');
  2478. return false;
  2479. }
  2480. }
  2481. async #toggleTask({
  2482. name,
  2483. doTask = true
  2484. }) {
  2485. try {
  2486. if (!doTask && this.whiteList.reddits.includes(name)) {
  2487. scripts_echoLog({
  2488. type: 'whiteList',
  2489. text: 'Reddit.undoTask',
  2490. id: name
  2491. });
  2492. return true;
  2493. }
  2494. let type = doTask ? 'joiningReddit' : 'leavingReddit';
  2495. if (/^u_/.test(name)) {
  2496. type = doTask ? 'followingRedditUser' : 'unfollowingRedditUser';
  2497. }
  2498. const logStatus = scripts_echoLog({
  2499. type: type,
  2500. text: name
  2501. });
  2502. const {
  2503. result,
  2504. statusText,
  2505. status,
  2506. data
  2507. } = await tools_httpRequest({
  2508. url: 'https://oauth.reddit.com/api/subscribe?redditWebClient=desktop2x&app=desktop2x-client-production&raw_json=1&gilding_detail=1',
  2509. method: 'POST',
  2510. headers: {
  2511. authorization: `Bearer ${this.#auth.token}`,
  2512. 'content-type': 'application/x-www-form-urlencoded'
  2513. },
  2514. data: $.param({
  2515. action: doTask ? 'sub' : 'unsub',
  2516. sr_name: name,
  2517. api_type: 'json'
  2518. })
  2519. });
  2520. if (result === 'Success') {
  2521. if (data?.status === 200) {
  2522. logStatus.success();
  2523. if (doTask) {
  2524. this.tasks.reddits = unique([ ...this.tasks.reddits, name ]);
  2525. }
  2526. return true;
  2527. }
  2528. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2529. return false;
  2530. }
  2531. logStatus.error(`${result}:${statusText}(${status})`);
  2532. return false;
  2533. } catch (error) {
  2534. throwError(error, 'Reddit.toggleTask');
  2535. return false;
  2536. }
  2537. }
  2538. async toggle({
  2539. doTask = true,
  2540. redditLinks = []
  2541. }) {
  2542. try {
  2543. if (!this.#initialized) {
  2544. scripts_echoLog({
  2545. text: i18n('needInit')
  2546. });
  2547. return false;
  2548. }
  2549. const prom = [];
  2550. if (doTask && !globalOptions.doTask.reddit.reddits || !doTask && !globalOptions.undoTask.reddit.reddits) {
  2551. scripts_echoLog({
  2552. type: 'globalOptionsSkip',
  2553. text: 'reddit.reddits'
  2554. });
  2555. } else {
  2556. const realReddits = this.getRealParams('reddits', redditLinks, doTask, link => {
  2557. const name = link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1];
  2558. const userName = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1];
  2559. if (userName) {
  2560. return name || userName;
  2561. }
  2562. return name;
  2563. });
  2564. if (realReddits.length > 0) {
  2565. for (const name of realReddits) {
  2566. prom.push(this.#toggleTask({
  2567. name: name,
  2568. doTask: doTask
  2569. }));
  2570. await delay(1e3);
  2571. }
  2572. }
  2573. }
  2574. return await Promise.all(prom).then(() => true);
  2575. } catch (error) {
  2576. throwError(error, 'Reddit.toggle');
  2577. return false;
  2578. }
  2579. }
  2580. }
  2581. const social_Reddit = Reddit;
  2582. class Twitch extends social_Social {
  2583. tasks;
  2584. whiteList;
  2585. #auth = GM_getValue('twitchAuth') || {};
  2586. #cache = GM_getValue('twitchCache') || {};
  2587. #initialized = false;
  2588. #integrityToken;
  2589. constructor() {
  2590. super();
  2591. const defaultTasksTemplate = {
  2592. channels: []
  2593. };
  2594. this.tasks = defaultTasksTemplate;
  2595. this.whiteList = {
  2596. ...defaultTasksTemplate,
  2597. ...GM_getValue('whiteList')?.twitch || {}
  2598. };
  2599. }
  2600. async init() {
  2601. try {
  2602. if (this.#initialized) {
  2603. return true;
  2604. }
  2605. if (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId) {
  2606. if (await this.#updateAuth()) {
  2607. this.#initialized = true;
  2608. return true;
  2609. }
  2610. return false;
  2611. }
  2612. const isVerified = await this.#verifyAuth(true);
  2613. if (isVerified) {
  2614. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  2615. this.#initialized = true;
  2616. return true;
  2617. }
  2618. GM_setValue('twitchAuth', null);
  2619. if (await this.#updateAuth()) {
  2620. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  2621. this.#initialized = true;
  2622. return true;
  2623. }
  2624. scripts_echoLog({}).error(i18n('initFailed', 'Twitch'));
  2625. return false;
  2626. } catch (error) {
  2627. throwError(error, 'Twitch.init');
  2628. return false;
  2629. }
  2630. }
  2631. async #verifyAuth(isFirst) {
  2632. try {
  2633. const logStatus = scripts_echoLog({
  2634. text: i18n('verifyingAuth', 'Twitch')
  2635. });
  2636. const {
  2637. result,
  2638. statusText,
  2639. status,
  2640. data
  2641. } = await tools_httpRequest({
  2642. url: 'https://gql.twitch.tv/gql',
  2643. method: 'POST',
  2644. dataType: 'json',
  2645. headers: {
  2646. Authorization: `OAuth ${this.#auth.authToken}`,
  2647. 'Client-Id': this.#auth.clientId
  2648. },
  2649. data: '[{"operationName":"FrontPageNew_User","variables":{"limit":1},"extensions":{"persistedQuery":{"version":1,' + '"sha256Hash":"64bd07a2cbaca80699d62636d966cf6395a5d14a1f0a14282067dcb28b13eb11"}}}]'
  2650. });
  2651. if (result === 'Success') {
  2652. if (data?.status === 200 && data.response?.[0]?.data?.currentUser) {
  2653. await this.#integrity(isFirst);
  2654. logStatus.success();
  2655. return true;
  2656. }
  2657. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2658. return false;
  2659. }
  2660. logStatus.error(`${result}:${statusText}(${status})`);
  2661. return false;
  2662. } catch (error) {
  2663. throwError(error, 'Twitch.verifyAuth');
  2664. return false;
  2665. }
  2666. }
  2667. async #integrity(isFirst = true, ct = '') {
  2668. try {
  2669. const logStatus = scripts_echoLog({
  2670. text: i18n('checkingTwitchIntegrity')
  2671. });
  2672. if (isFirst && (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId)) {
  2673. return await this.#updateAuth(false);
  2674. }
  2675. const {
  2676. result,
  2677. statusText,
  2678. status,
  2679. data
  2680. } = await tools_httpRequest({
  2681. url: 'https://gql.twitch.tv/integrity',
  2682. method: 'POST',
  2683. dataType: 'json',
  2684. anonymous: true,
  2685. headers: {
  2686. Origin: 'https://www.twitch.tv',
  2687. Referer: 'https://www.twitch.tv/',
  2688. Authorization: `OAuth ${this.#auth.authToken}`,
  2689. 'Client-Id': this.#auth.clientId,
  2690. 'Client-Version': this.#auth.clientVersion,
  2691. 'X-Device-Id': this.#auth.deviceId,
  2692. 'Client-Session-Id': this.#auth.clientSessionId,
  2693. 'x-kpsdk-ct': ct
  2694. }
  2695. });
  2696. if (result === 'Success') {
  2697. if (!ct && data?.responseHeaders?.['x-kpsdk-ct']) {
  2698. return await this.#integrity(isFirst, data.responseHeaders['x-kpsdk-ct']);
  2699. }
  2700. if (data?.status === 200 && data.response?.token) {
  2701. this.#integrityToken = data.response.token;
  2702. logStatus.success();
  2703. return true;
  2704. }
  2705. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2706. return false;
  2707. }
  2708. logStatus.error(`${result}:${statusText}(${status})`);
  2709. return false;
  2710. } catch (error) {
  2711. throwError(error, 'Twitch.integrity');
  2712. return false;
  2713. }
  2714. }
  2715. async #updateAuth(isFirst = true) {
  2716. try {
  2717. const logStatus = scripts_echoLog({
  2718. text: i18n('updatingAuth', 'Twitch')
  2719. });
  2720. return await new Promise(resolve => {
  2721. const newTab = GM_openInTab('https://www.twitch.tv/', {
  2722. active: true,
  2723. insert: true,
  2724. setParent: true
  2725. });
  2726. newTab.name = 'ATv4_twitchAuth';
  2727. newTab.onclose = async () => {
  2728. const auth = GM_getValue('twitchAuth');
  2729. if (auth) {
  2730. this.#auth = auth;
  2731. logStatus.success();
  2732. resolve(await this.#verifyAuth(isFirst));
  2733. } else {
  2734. logStatus.error('Error: Update twitch auth failed!');
  2735. resolve(false);
  2736. }
  2737. };
  2738. });
  2739. } catch (error) {
  2740. throwError(error, 'Twitch.updateAuth');
  2741. return false;
  2742. }
  2743. }
  2744. async #toggleChannel({
  2745. name,
  2746. doTask = true
  2747. }) {
  2748. try {
  2749. if (!doTask && this.whiteList.channels.includes(name)) {
  2750. scripts_echoLog({
  2751. type: 'whiteList',
  2752. text: 'Twitch.unfollowChannel',
  2753. id: name
  2754. });
  2755. return true;
  2756. }
  2757. const channelId = await this.#getChannelId(name);
  2758. if (!channelId) {
  2759. return false;
  2760. }
  2761. const logStatus = scripts_echoLog({
  2762. type: `${doTask ? '' : 'un'}followingTwitchChannel`,
  2763. text: name
  2764. });
  2765. const followData = `[{"operationName":"FollowButton_FollowUser","variables":{"input":{"disableNotifications":false,"targetID":"${channelId}` + '"}},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"800e7346bdf7e5278a3c1d3f21b2b56e2639928f86815677a7126b093b2fdd08"}}}]';
  2766. const unfollowData = `[{"operationName":"FollowButton_UnfollowUser","variables":{"input":{"targetID":"${channelId}"}},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"f7dae976ebf41c755ae2d758546bfd176b4eeb856656098bb40e0a672ca0d880"}}}]';
  2767. const {
  2768. result,
  2769. statusText,
  2770. status,
  2771. data
  2772. } = await tools_httpRequest({
  2773. url: 'https://gql.twitch.tv/gql',
  2774. method: 'POST',
  2775. dataType: 'json',
  2776. anonymous: true,
  2777. headers: {
  2778. Origin: 'https://www.twitch.tv',
  2779. Referer: 'https://www.twitch.tv/',
  2780. Authorization: `OAuth ${this.#auth.authToken}`,
  2781. 'Client-Id': this.#auth.clientId,
  2782. 'Client-Version': this.#auth.clientVersion,
  2783. 'X-Device-Id': this.#auth.deviceId,
  2784. 'Client-Session-Id': this.#auth.clientSessionId,
  2785. 'Client-Integrity': this.#integrityToken
  2786. },
  2787. data: doTask ? followData : unfollowData
  2788. });
  2789. if (result === 'Success') {
  2790. if (data?.status === 200 && data.response?.[0] && !data.response[0].errors) {
  2791. logStatus.success();
  2792. if (doTask) {
  2793. this.tasks.channels = unique([ ...this.tasks.channels, name ]);
  2794. }
  2795. return true;
  2796. }
  2797. logStatus.error(`Error:${data?.response?.[0].errors?.[0]?.message || `${data?.statusText}(${data?.status})`}`);
  2798. return false;
  2799. }
  2800. logStatus.error(`${result}:${statusText}(${status})`);
  2801. return false;
  2802. } catch (error) {
  2803. throwError(error, 'Twitch.toggleChannel');
  2804. return false;
  2805. }
  2806. }
  2807. async #getChannelId(name) {
  2808. try {
  2809. const logStatus = scripts_echoLog({
  2810. type: 'gettingTwitchChannelId',
  2811. text: name
  2812. });
  2813. const channelId = this.#cache[name];
  2814. if (channelId) {
  2815. logStatus.success();
  2816. return channelId;
  2817. }
  2818. const {
  2819. result,
  2820. statusText,
  2821. status,
  2822. data
  2823. } = await tools_httpRequest({
  2824. url: 'https://gql.twitch.tv/gql',
  2825. method: 'POST',
  2826. headers: {
  2827. Authorization: `OAuth ${this.#auth.authToken}`,
  2828. 'Client-Id': this.#auth.clientId
  2829. },
  2830. responseType: 'json',
  2831. data: `[{"operationName":"ActiveWatchParty","variables":{"channelLogin":"${name}"},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"4a8156c97b19e3a36e081cf6d6ddb5dbf9f9b02ae60e4d2ff26ed70aebc80a30"}}}]'
  2832. });
  2833. if (result === 'Success') {
  2834. if (data?.status === 200) {
  2835. const channelId = data.response?.[0]?.data?.user?.id;
  2836. if (channelId) {
  2837. this.#setCache(name, String(channelId));
  2838. logStatus.success();
  2839. return channelId;
  2840. }
  2841. logStatus.error(`Error:${data.statusText}(${data.status})`);
  2842. return false;
  2843. }
  2844. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2845. return false;
  2846. }
  2847. logStatus.error(`${result}:${statusText}(${status})`);
  2848. return false;
  2849. } catch (error) {
  2850. throwError(error, 'Twitch.getChannelId');
  2851. return false;
  2852. }
  2853. }
  2854. async toggle({
  2855. doTask = true,
  2856. channelLinks = []
  2857. }) {
  2858. try {
  2859. if (!this.#initialized) {
  2860. scripts_echoLog({
  2861. text: i18n('needInit')
  2862. });
  2863. return false;
  2864. }
  2865. const prom = [];
  2866. if (doTask && !globalOptions.doTask.twitch.channels || !doTask && !globalOptions.undoTask.twitch.channels) {
  2867. scripts_echoLog({
  2868. type: 'globalOptionsSkip',
  2869. text: 'twitch.channels'
  2870. });
  2871. } else {
  2872. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2]);
  2873. if (realChannels.length > 0) {
  2874. for (const channel of realChannels) {
  2875. prom.push(this.#toggleChannel({
  2876. name: channel,
  2877. doTask: doTask
  2878. }));
  2879. await delay(1e3);
  2880. }
  2881. }
  2882. }
  2883. return Promise.all(prom).then(() => true);
  2884. } catch (error) {
  2885. throwError(error, 'Twitch.toggle');
  2886. return false;
  2887. }
  2888. }
  2889. #setCache(name, id) {
  2890. try {
  2891. this.#cache[name] = id;
  2892. GM_setValue('twitchCache', this.#cache);
  2893. } catch (error) {
  2894. throwError(error, 'Twitch.setCache');
  2895. }
  2896. }
  2897. }
  2898. const social_Twitch = Twitch;
  2899. class Twitter extends social_Social {
  2900. tasks;
  2901. whiteList;
  2902. #verifyId = globalOptions.other.twitterVerifyId;
  2903. #auth = GM_getValue('twitterAuth') || {};
  2904. #cache = GM_getValue('twitterCache') || {};
  2905. #initialized = false;
  2906. constructor() {
  2907. super();
  2908. const defaultTasksTemplate = {
  2909. users: [],
  2910. retweets: [],
  2911. likes: []
  2912. };
  2913. this.tasks = defaultTasksTemplate;
  2914. this.whiteList = {
  2915. ...defaultTasksTemplate,
  2916. ...GM_getValue('whiteList')?.twitter || {}
  2917. };
  2918. }
  2919. async init() {
  2920. try {
  2921. if (this.#initialized) {
  2922. return true;
  2923. }
  2924. if (!this.#auth.ct0) {
  2925. if (await this.#updateAuth()) {
  2926. this.#initialized = true;
  2927. return true;
  2928. }
  2929. return false;
  2930. }
  2931. const isVerified = await this.#verifyAuth();
  2932. if (isVerified) {
  2933. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  2934. this.#initialized = true;
  2935. return true;
  2936. }
  2937. GM_setValue('twitterAuth', null);
  2938. if (await this.#updateAuth()) {
  2939. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  2940. this.#initialized = true;
  2941. return true;
  2942. }
  2943. scripts_echoLog({}).error(i18n('initFailed', 'Twitter'));
  2944. return false;
  2945. } catch (error) {
  2946. throwError(error, 'Twitter.init');
  2947. return false;
  2948. }
  2949. }
  2950. async #verifyAuth() {
  2951. try {
  2952. return await this.#toggleUser({
  2953. name: 'verify',
  2954. doTask: true,
  2955. verify: true
  2956. });
  2957. } catch (error) {
  2958. throwError(error, 'Twitter.verifyAuth');
  2959. return false;
  2960. }
  2961. }
  2962. async #updateAuth() {
  2963. try {
  2964. const logStatus = scripts_echoLog({
  2965. text: i18n('updatingAuth', 'Twitter')
  2966. });
  2967. return await new Promise(resolve => {
  2968. GM_cookie.list({
  2969. url: 'https://x.com/settings/account'
  2970. }, async (cookies, error) => {
  2971. if (!error) {
  2972. const [ ct0, isLogin ] = cookies.map(cookie => [ 'ct0', 'twid' ].includes(cookie.name) ? cookie.value : null).filter(cookie => cookie);
  2973. if (isLogin && ct0) {
  2974. GM_setValue('twitterAuth', {
  2975. ct0: ct0
  2976. });
  2977. this.#auth = {
  2978. ct0: ct0
  2979. };
  2980. logStatus.success();
  2981. resolve(await this.#verifyAuth());
  2982. } else {
  2983. logStatus.error(i18n('needLogin'));
  2984. resolve(false);
  2985. }
  2986. } else {
  2987. logStatus.error('Error: Update twitter auth failed!');
  2988. resolve(false);
  2989. }
  2990. });
  2991. });
  2992. } catch (error) {
  2993. throwError(error, 'Twitter.updateToken');
  2994. return false;
  2995. }
  2996. }
  2997. async #toggleUser({
  2998. name,
  2999. doTask = true,
  3000. verify = false,
  3001. retry = false
  3002. }) {
  3003. try {
  3004. if (!doTask && !verify && this.whiteList.users.includes(name)) {
  3005. scripts_echoLog({
  3006. type: 'whiteList',
  3007. text: 'Twitter.unfollowUser',
  3008. id: name
  3009. });
  3010. return true;
  3011. }
  3012. const userId = verify ? this.#verifyId : await this.userName2id(name);
  3013. if (!userId) {
  3014. return false;
  3015. }
  3016. const logStatus = verify ? scripts_echoLog({
  3017. text: i18n('verifyingAuth', 'Twitter')
  3018. }) : scripts_echoLog({
  3019. type: `${doTask ? '' : 'un'}followingTwitterUser`,
  3020. text: name
  3021. });
  3022. const {
  3023. result,
  3024. statusText,
  3025. status,
  3026. data
  3027. } = await tools_httpRequest({
  3028. url: `https://x.com/i/api/1.1/friendships/${doTask ? 'create' : 'destroy'}.json`,
  3029. method: 'POST',
  3030. headers: {
  3031. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3032. 'Content-Type': 'application/x-www-form-urlencoded',
  3033. 'x-csrf-token': this.#auth.ct0
  3034. },
  3035. responseType: 'json',
  3036. data: $.param({
  3037. include_profile_interstitial_type: 1,
  3038. include_blocking: 1,
  3039. include_blocked_by: 1,
  3040. include_followed_by: 1,
  3041. include_want_retweets: 1,
  3042. include_mute_edge: 1,
  3043. include_can_dm: 1,
  3044. include_can_media_tag: 1,
  3045. skip_status: 1,
  3046. id: userId
  3047. })
  3048. });
  3049. if (result === 'Success') {
  3050. if (data?.status === 200) {
  3051. logStatus.success();
  3052. if (doTask && !verify) {
  3053. this.tasks.users = unique([ ...this.tasks.users, name ]);
  3054. }
  3055. return true;
  3056. }
  3057. if (verify && data?.status === 403) {
  3058. if (data.response?.errors?.[0]?.code === 158) {
  3059. logStatus.success();
  3060. return true;
  3061. }
  3062. if (data.response?.errors?.[0]?.code === 353 && !retry && data.responseHeaders?.['set-cookie']) {
  3063. this.#auth.ct0 = data.responseHeaders['set-cookie']?.find(cookie => cookie.includes('ct0='))?.split(';')?.at(0)?.split('=')?.at(-1) || this.#auth.ct0;
  3064. logStatus.warning(i18n('retry'));
  3065. return this.#toggleUser({
  3066. name: name,
  3067. doTask: doTask,
  3068. verify: verify,
  3069. retry: true
  3070. });
  3071. }
  3072. }
  3073. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3074. return false;
  3075. }
  3076. logStatus.error(`${result}:${statusText}(${status})`);
  3077. return false;
  3078. } catch (error) {
  3079. throwError(error, 'Twitter.toggleUser');
  3080. return false;
  3081. }
  3082. }
  3083. async userName2id(name) {
  3084. try {
  3085. const logStatus = scripts_echoLog({
  3086. type: 'gettingTwitterUserId',
  3087. text: name
  3088. });
  3089. const userId = this.#cache[name];
  3090. if (userId) {
  3091. logStatus.success();
  3092. return userId;
  3093. }
  3094. const {
  3095. result,
  3096. statusText,
  3097. status,
  3098. data
  3099. } = await tools_httpRequest({
  3100. 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`,
  3101. method: 'GET',
  3102. headers: {
  3103. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3104. 'content-type': 'application/json',
  3105. referer: `https://x.com/${name}`,
  3106. 'x-csrf-token': this.#auth.ct0
  3107. },
  3108. responseType: 'json'
  3109. });
  3110. if (result === 'Success') {
  3111. if (data?.status === 200) {
  3112. let response = data.response || (typeof data.responseText === 'object' ? data.responseText : null);
  3113. if (!response) {
  3114. try {
  3115. response = JSON.parse(data.responseText);
  3116. } catch (error) {
  3117. response = null;
  3118. }
  3119. }
  3120. const userId = String(response?.data?.user?.result?.rest_id);
  3121. if (userId) {
  3122. this.#setCache(name, userId);
  3123. logStatus.success();
  3124. return userId;
  3125. }
  3126. logStatus.error(`Error:${data.statusText}(${data.status})`);
  3127. return false;
  3128. }
  3129. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3130. return false;
  3131. }
  3132. logStatus.error(`${result}:${statusText}(${status})`);
  3133. return false;
  3134. } catch (error) {
  3135. throwError(error, 'Twitter.getUserId');
  3136. return false;
  3137. }
  3138. }
  3139. async #toggleRetweet({
  3140. retweetId,
  3141. doTask = true
  3142. }) {
  3143. try {
  3144. if (!doTask && this.whiteList.retweets.includes(retweetId)) {
  3145. scripts_echoLog({
  3146. type: 'whiteList',
  3147. text: 'Twitter.unretweet',
  3148. id: retweetId
  3149. });
  3150. return true;
  3151. }
  3152. const logStatus = scripts_echoLog({
  3153. type: `${doTask ? '' : 'un'}retweetting`,
  3154. text: retweetId
  3155. });
  3156. const {
  3157. result,
  3158. statusText,
  3159. status,
  3160. data
  3161. } = await tools_httpRequest({
  3162. url: `https://x.com/i/api/graphql/${doTask ? 'ojPdsZsimiJrUGLR1sjUtA/CreateRetweet' : 'iQtK4dl5hBmXewYZuEOKVw/DeleteRetweet'}`,
  3163. method: 'POST',
  3164. headers: {
  3165. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3166. 'Content-Type': 'application/json',
  3167. 'x-csrf-token': this.#auth.ct0
  3168. },
  3169. data: `{"variables":{"tweet_id":"${retweetId}","dark_request":false},"queryId":"${doTask ? 'ojPdsZsimiJrUGLR1sjUtA' : 'iQtK4dl5hBmXewYZuEOKVw'}"}`,
  3170. responseType: 'json'
  3171. });
  3172. if (result === 'Success') {
  3173. if (data?.status === 200 || data?.status === 403 && data.response?.errors?.[0]?.code === 327) {
  3174. logStatus.success();
  3175. if (doTask) {
  3176. this.tasks.retweets = unique([ ...this.tasks.retweets, retweetId ]);
  3177. }
  3178. return true;
  3179. }
  3180. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3181. return false;
  3182. }
  3183. logStatus.error(`${result}:${statusText}(${status})`);
  3184. return false;
  3185. } catch (error) {
  3186. throwError(error, 'Twitter.toggleRetweet');
  3187. return false;
  3188. }
  3189. }
  3190. async toggle({
  3191. doTask = true,
  3192. userLinks = [],
  3193. retweetLinks = []
  3194. }) {
  3195. try {
  3196. if (!this.#initialized) {
  3197. scripts_echoLog({
  3198. text: i18n('needInit')
  3199. });
  3200. return false;
  3201. }
  3202. const prom = [];
  3203. if (doTask && !globalOptions.doTask.twitter.users || !doTask && !globalOptions.undoTask.twitter.users) {
  3204. scripts_echoLog({
  3205. type: 'globalOptionsSkip',
  3206. text: 'twitter.users'
  3207. });
  3208. } else {
  3209. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/x\.com\/(.+)/)?.[1] || link.match(/https:\/\/twitter\.com\/(.+)/)?.[1]);
  3210. if (realUsers.length > 0) {
  3211. for (const user of realUsers) {
  3212. prom.push(this.#toggleUser({
  3213. name: user,
  3214. doTask: doTask
  3215. }));
  3216. await delay(1e3);
  3217. }
  3218. }
  3219. }
  3220. if (doTask && !globalOptions.doTask.twitter.retweets || !doTask && !globalOptions.undoTask.twitter.retweets) {
  3221. scripts_echoLog({
  3222. type: 'globalOptionsSkip',
  3223. text: 'twitter.retweets'
  3224. });
  3225. } else {
  3226. const realRetweets = this.getRealParams('retweets', retweetLinks, doTask, link => link.match(/https:\/\/x\.com\/.*?\/status\/([\d]+)/)?.[1] || link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1]);
  3227. if (realRetweets.length > 0) {
  3228. for (const retweet of realRetweets) {
  3229. prom.push(this.#toggleRetweet({
  3230. retweetId: retweet,
  3231. doTask: doTask
  3232. }));
  3233. await delay(1e3);
  3234. }
  3235. }
  3236. }
  3237. return Promise.all(prom).then(() => true);
  3238. } catch (error) {
  3239. throwError(error, 'Twitter.toggle');
  3240. return false;
  3241. }
  3242. }
  3243. #setCache(name, id) {
  3244. try {
  3245. this.#cache[name] = id;
  3246. GM_setValue('twitterCache', this.#cache);
  3247. } catch (error) {
  3248. throwError(error, 'Twitter.setCache');
  3249. }
  3250. }
  3251. }
  3252. const social_Twitter = Twitter;
  3253. class Vk extends social_Social {
  3254. tasks;
  3255. whiteList;
  3256. #username = '';
  3257. #cache = GM_getValue('vkCache') || {};
  3258. #initialized = false;
  3259. constructor() {
  3260. super();
  3261. const defaultTasksTemplate = {
  3262. names: []
  3263. };
  3264. this.tasks = defaultTasksTemplate;
  3265. this.whiteList = {
  3266. ...defaultTasksTemplate,
  3267. ...GM_getValue('whiteList')?.vk || {}
  3268. };
  3269. }
  3270. async init() {
  3271. try {
  3272. if (this.#initialized) {
  3273. return true;
  3274. }
  3275. const isVerified = await this.#verifyAuth();
  3276. if (isVerified) {
  3277. scripts_echoLog({}).success(i18n('initSuccess', 'Vk'));
  3278. this.#initialized = true;
  3279. return true;
  3280. }
  3281. scripts_echoLog({}).error(i18n('initFailed', 'Vk'));
  3282. return false;
  3283. } catch (error) {
  3284. throwError(error, 'Vk.init');
  3285. return false;
  3286. }
  3287. }
  3288. async #verifyAuth() {
  3289. try {
  3290. const logStatus = scripts_echoLog({
  3291. text: i18n('verifyAuth', 'Vk')
  3292. });
  3293. const {
  3294. result,
  3295. statusText,
  3296. status,
  3297. data
  3298. } = await tools_httpRequest({
  3299. url: 'https://vk.com/im',
  3300. method: 'GET'
  3301. });
  3302. if (result === 'Success') {
  3303. if (data?.finalUrl.includes('vk.com/login')) {
  3304. logStatus.error(`Error:${i18n('loginVk')}`, true);
  3305. return false;
  3306. }
  3307. if (data?.status === 200) {
  3308. this.#username = data.responseText.match(/TopNavBtn__profileLink" href="\/(.*?)"/)?.[1] || '';
  3309. logStatus.success();
  3310. return true;
  3311. }
  3312. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3313. return false;
  3314. }
  3315. logStatus.error(`${result}:${statusText}(${status})`);
  3316. return false;
  3317. } catch (error) {
  3318. throwError(error, 'Vk.verifyAuth');
  3319. return false;
  3320. }
  3321. }
  3322. async #toggleGroup(name, dataParam, doTask = true) {
  3323. try {
  3324. const logStatus = scripts_echoLog({
  3325. type: doTask ? 'joiningVkGroup' : 'leavingVkGroup',
  3326. text: name
  3327. });
  3328. if (dataParam.groupAct === 'enter' && !doTask || dataParam.groupAct === 'leave' && doTask) {
  3329. logStatus.success();
  3330. return true;
  3331. }
  3332. const reqData = {
  3333. act: doTask ? 'enter' : 'leave',
  3334. al: 1,
  3335. gid: dataParam.groupId,
  3336. hash: dataParam.groupHash
  3337. };
  3338. if (doTask) {
  3339. reqData.context = '_';
  3340. }
  3341. const {
  3342. result,
  3343. statusText,
  3344. status,
  3345. data
  3346. } = await tools_httpRequest({
  3347. url: 'https://vk.com/al_groups.php',
  3348. method: 'POST',
  3349. headers: {
  3350. origin: 'https://vk.com',
  3351. referer: `https://vk.com/${name}`,
  3352. 'content-type': 'application/x-www-form-urlencoded'
  3353. },
  3354. data: $.param(reqData)
  3355. });
  3356. if (result === 'Success') {
  3357. if (data?.status === 200) {
  3358. logStatus.success();
  3359. if (doTask) {
  3360. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3361. }
  3362. return true;
  3363. }
  3364. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3365. return false;
  3366. }
  3367. logStatus.error(`${result}:${statusText}(${status})`);
  3368. return false;
  3369. } catch (error) {
  3370. throwError(error, 'Vk.toggleGroup');
  3371. return false;
  3372. }
  3373. }
  3374. async #togglePublic(name, dataParam, doTask = true) {
  3375. try {
  3376. const logStatus = scripts_echoLog({
  3377. type: doTask ? 'joiningVkPublic' : 'leavingVkPublic',
  3378. text: name
  3379. });
  3380. if (dataParam.publicJoined && doTask || !dataParam.publicJoined && !doTask) {
  3381. logStatus.success();
  3382. return true;
  3383. }
  3384. const {
  3385. result,
  3386. statusText,
  3387. status,
  3388. data
  3389. } = await tools_httpRequest({
  3390. url: 'https://vk.com/al_public.php',
  3391. method: 'POST',
  3392. headers: {
  3393. origin: 'https://vk.com',
  3394. referer: `https://vk.com/${name}`,
  3395. 'content-type': 'application/x-www-form-urlencoded'
  3396. },
  3397. data: $.param({
  3398. act: doTask ? 'a_enter' : 'a_leave',
  3399. al: 1,
  3400. pid: dataParam.publicPid,
  3401. hash: dataParam.publicHash
  3402. })
  3403. });
  3404. if (result === 'Success') {
  3405. if (data?.status === 200) {
  3406. logStatus.success();
  3407. if (doTask) {
  3408. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3409. }
  3410. return true;
  3411. }
  3412. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3413. return false;
  3414. }
  3415. logStatus.error(`${result}:${statusText}(${status})`);
  3416. return false;
  3417. } catch (error) {
  3418. throwError(error, 'Vk.togglePublic');
  3419. return false;
  3420. }
  3421. }
  3422. async #sendWall(name) {
  3423. try {
  3424. const logStatus = scripts_echoLog({
  3425. type: 'sendingVkWall',
  3426. text: name
  3427. });
  3428. const {
  3429. result,
  3430. statusText,
  3431. status,
  3432. data
  3433. } = await tools_httpRequest({
  3434. url: 'https://vk.com/like.php',
  3435. method: 'POST',
  3436. headers: {
  3437. origin: 'https://vk.com',
  3438. referer: `https://vk.com/${name}`,
  3439. 'content-type': 'application/x-www-form-urlencoded'
  3440. },
  3441. data: $.param({
  3442. act: 'publish_box',
  3443. al: 1,
  3444. object: name
  3445. })
  3446. });
  3447. if (result === 'Success') {
  3448. if (data?.status === 200) {
  3449. const hash = data.responseText.match(/shHash:[\s]*'(.*?)'/)?.[1];
  3450. if (hash) {
  3451. const {
  3452. result: resultR,
  3453. statusText: statusTextR,
  3454. status: statusR,
  3455. data: dataR
  3456. } = await tools_httpRequest({
  3457. url: 'https://vk.com/like.php',
  3458. method: 'POST',
  3459. headers: {
  3460. origin: 'https://vk.com',
  3461. referer: `https://vk.com/${name}`,
  3462. 'content-type': 'application/x-www-form-urlencoded'
  3463. },
  3464. data: $.param({
  3465. Message: '',
  3466. act: 'a_do_publish',
  3467. al: 1,
  3468. close_comments: 0,
  3469. friends_only: 0,
  3470. from: 'box',
  3471. hash: hash,
  3472. list: '',
  3473. mark_as_ads: 0,
  3474. mute_notifications: 0,
  3475. object: name,
  3476. ret_data: 1,
  3477. to: 0
  3478. })
  3479. });
  3480. if (resultR === 'Success') {
  3481. if (dataR?.status === 200) {
  3482. const jsonData = JSON.parse(dataR.responseText?.replace('\x3c!--', '') || '{}');
  3483. if (jsonData?.payload?.[1]?.[1]?.share_my === true) {
  3484. logStatus.success();
  3485. const postId = String(jsonData?.payload?.[1]?.[1]?.post_id);
  3486. const ownerId = String(jsonData?.payload?.[1]?.[1]?.owner_id);
  3487. if (postId && ownerId) {
  3488. this.#setCache(name, `${ownerId}_${postId}`);
  3489. }
  3490. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3491. return true;
  3492. }
  3493. }
  3494. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  3495. return false;
  3496. }
  3497. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  3498. return false;
  3499. }
  3500. logStatus.error('Error: Get "hash" failed');
  3501. return false;
  3502. }
  3503. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3504. return false;
  3505. }
  3506. logStatus.error(`${result}:${statusText}(${status})`);
  3507. return false;
  3508. } catch (error) {
  3509. throwError(error, 'Vk.sendWall');
  3510. return false;
  3511. }
  3512. }
  3513. async #deleteWall(name, dataParams) {
  3514. try {
  3515. const logStatus = scripts_echoLog({
  3516. type: 'deletingVkWall',
  3517. text: name
  3518. });
  3519. const {
  3520. result,
  3521. statusText,
  3522. status,
  3523. data
  3524. } = await tools_httpRequest({
  3525. url: 'https://vk.com/al_wall.php?act=delete',
  3526. method: 'POST',
  3527. headers: {
  3528. origin: 'https://vk.com',
  3529. referer: `https://vk.com/${this.#username}?w=wall${this.#cache[name]}%2Fall`,
  3530. 'content-type': 'application/x-www-form-urlencoded'
  3531. },
  3532. data: $.param({
  3533. act: 'delete',
  3534. al: 1,
  3535. confirm: 0,
  3536. from: 'wkview',
  3537. hash: dataParams.wallHash,
  3538. post: this.#cache[name]
  3539. })
  3540. });
  3541. if (result === 'Success') {
  3542. if (data?.status === 200) {
  3543. const jsonData = JSON.parse(data.responseText?.replace('\x3c!--', '') || '{}');
  3544. if (jsonData?.payload?.[1]?.[1]) {
  3545. logStatus.success();
  3546. return true;
  3547. }
  3548. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3549. return false;
  3550. }
  3551. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3552. return false;
  3553. }
  3554. logStatus.error(`${result}:${statusText}(${status})`);
  3555. return false;
  3556. } catch (error) {
  3557. throwError(error, 'Vk.deleteWall');
  3558. return false;
  3559. }
  3560. }
  3561. async #getId(name, doTask) {
  3562. try {
  3563. let url = `https://vk.com/${name}`;
  3564. if (/^wall-/.test(name)) {
  3565. if (doTask) {
  3566. return {
  3567. type: 'sendWall'
  3568. };
  3569. }
  3570. if (!this.#cache[name]) {
  3571. return {
  3572. type: 'unSupport'
  3573. };
  3574. }
  3575. url = `https://vk.com/${this.#username}?w=wall${this.#cache[name]}`;
  3576. }
  3577. const logStatus = scripts_echoLog({
  3578. type: 'gettingVkId',
  3579. text: name
  3580. });
  3581. const {
  3582. result,
  3583. statusText,
  3584. status,
  3585. data
  3586. } = await tools_httpRequest({
  3587. url: url,
  3588. method: 'GET'
  3589. });
  3590. if (result === 'Success') {
  3591. if (data?.status === 200) {
  3592. const [ , groupAct, groupId, , groupHash ] = data.responseText.match(/Groups.(enter|leave)\(.*?,.*?([\d]+?), (&#39;|')(.*?)(&#39;|')/) || [];
  3593. const publicHash = data.responseText.match(/"enterHash":"(.*?)"/)?.[1];
  3594. const publicPid = data.responseText.match(/"public_id":([\d]+?),/)?.[1];
  3595. const publicJoined = !data.responseText.includes('Public.subscribe');
  3596. if (groupAct && groupId && groupHash) {
  3597. logStatus.success();
  3598. return {
  3599. groupAct: groupAct,
  3600. groupId: groupId,
  3601. groupHash: groupHash,
  3602. type: 'group'
  3603. };
  3604. } else if (publicHash && publicPid) {
  3605. logStatus.success();
  3606. return {
  3607. publicHash: publicHash,
  3608. publicPid: publicPid,
  3609. publicJoined: publicJoined,
  3610. type: 'public'
  3611. };
  3612. } else if (data.responseText.includes('wall.deletePost') && !doTask) {
  3613. const wallHash = data.responseText.match(/wall\.deletePost\(this, '.*?', '(.*?)'\)/)?.[1];
  3614. if (wallHash) {
  3615. logStatus.success();
  3616. return {
  3617. type: 'deleteWall',
  3618. wallHash: wallHash
  3619. };
  3620. }
  3621. } else if (name.includes('wall') && doTask) {
  3622. logStatus.success();
  3623. return {
  3624. type: 'sendWall'
  3625. };
  3626. }
  3627. logStatus.error('Error: Parameters not found!');
  3628. return false;
  3629. }
  3630. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3631. return false;
  3632. }
  3633. logStatus.error(`${result}:${statusText}(${status})`);
  3634. return false;
  3635. } catch (error) {
  3636. throwError(error, 'Vk.getId');
  3637. return false;
  3638. }
  3639. }
  3640. async #toggleVk({
  3641. name,
  3642. doTask = true
  3643. }) {
  3644. try {
  3645. if (!doTask && this.whiteList.names.includes(name)) {
  3646. scripts_echoLog({
  3647. type: 'whiteList',
  3648. text: 'Vk.undoTask',
  3649. id: name
  3650. });
  3651. return true;
  3652. }
  3653. const formatName = name.replace(/\/$/, '');
  3654. const data = await this.#getId(formatName, doTask);
  3655. if (!data) {
  3656. return false;
  3657. }
  3658. switch (data.type) {
  3659. case 'group':
  3660. return await this.#toggleGroup(formatName, data, doTask);
  3661.  
  3662. case 'public':
  3663. return await this.#togglePublic(formatName, data, doTask);
  3664.  
  3665. case 'sendWall':
  3666. return doTask ? await this.#sendWall(formatName) : true;
  3667.  
  3668. case 'deleteWall':
  3669. return doTask ? true : await this.#deleteWall(formatName, data);
  3670.  
  3671. default:
  3672. return false;
  3673. }
  3674. } catch (error) {
  3675. throwError(error, 'Vk.toggleVk');
  3676. return false;
  3677. }
  3678. }
  3679. async toggle({
  3680. doTask = true,
  3681. nameLinks = []
  3682. }) {
  3683. try {
  3684. if (!this.#initialized) {
  3685. scripts_echoLog({
  3686. text: i18n('needInit')
  3687. });
  3688. return false;
  3689. }
  3690. const prom = [];
  3691. if (doTask && !globalOptions.doTask.vk.names || !doTask && !globalOptions.undoTask.vk.names) {
  3692. scripts_echoLog({
  3693. type: 'globalOptionsSkip',
  3694. text: 'vk.names'
  3695. });
  3696. } else {
  3697. const realNames = this.getRealParams('names', nameLinks, doTask, link => link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1]);
  3698. if (realNames.length > 0) {
  3699. for (const name of realNames) {
  3700. prom.push(this.#toggleVk({
  3701. name: name,
  3702. doTask: doTask
  3703. }));
  3704. await delay(1e3);
  3705. }
  3706. }
  3707. }
  3708. return Promise.all(prom).then(() => true);
  3709. } catch (error) {
  3710. throwError(error, 'Vk.toggle');
  3711. return false;
  3712. }
  3713. }
  3714. #setCache(name, postId) {
  3715. try {
  3716. this.#cache[name] = postId;
  3717. GM_setValue('vkCache', this.#cache);
  3718. } catch (error) {
  3719. throwError(error, 'Vk.setCache');
  3720. }
  3721. }
  3722. }
  3723. const social_Vk = Vk;
  3724. const getInfo = async function(link, type) {
  3725. try {
  3726. const logStatus = scripts_echoLog({
  3727. text: i18n('gettingYtbToken')
  3728. });
  3729. const {
  3730. result,
  3731. statusText,
  3732. status,
  3733. data
  3734. } = await tools_httpRequest({
  3735. url: link,
  3736. method: 'GET'
  3737. });
  3738. if (result === 'Success') {
  3739. if (data?.status === 200) {
  3740. if (data.responseText.includes('accounts.google.com/ServiceLogin?service=youtube')) {
  3741. logStatus.error(`Error:${i18n('loginYtb')}`, true);
  3742. return {
  3743. needLogin: true
  3744. };
  3745. }
  3746. const apiKey = data.responseText.match(/"INNERTUBE_API_KEY":"(.*?)"/)?.[1];
  3747. const context = (data.responseText.match(/\(\{"INNERTUBE_CONTEXT":([\w\W]*?)\}\)/) || data.responseText.match(/"INNERTUBE_CONTEXT":([\w\W]*?\}),"INNERTUBE/))?.[1] || '{}';
  3748. const {
  3749. client,
  3750. request
  3751. } = JSON.parse(context);
  3752. if (apiKey && client && request) {
  3753. client.hl = 'en';
  3754. if (type === 'channel') {
  3755. const channelId = data.responseText.match(/"channelId":"(.+?)"/)?.[1];
  3756. if (channelId) {
  3757. logStatus.success();
  3758. return {
  3759. params: {
  3760. apiKey: apiKey,
  3761. client: client,
  3762. request: request,
  3763. channelId: channelId
  3764. }
  3765. };
  3766. }
  3767. logStatus.error('Error: Get "channelId" failed!');
  3768. return {};
  3769. } else if (type === 'likeVideo') {
  3770. const videoId = data.responseText.match(/<link rel="shortlinkUrl" href="https:\/\/youtu\.be\/(.*?)">/)?.[1];
  3771. const likeParams = data.responseText.match(/"likeParams":"(.*?)"/)?.[1];
  3772. if (videoId) {
  3773. logStatus.success();
  3774. return {
  3775. params: {
  3776. apiKey: apiKey,
  3777. client: client,
  3778. request: request,
  3779. videoId: videoId,
  3780. likeParams: likeParams
  3781. }
  3782. };
  3783. }
  3784. logStatus.error('Error: Get "videoId" failed!');
  3785. return {};
  3786. }
  3787. logStatus.error('Error: Unknown type');
  3788. return {};
  3789. }
  3790. logStatus.error('Error: Parameter "apiKey" not found!');
  3791. return {};
  3792. }
  3793. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3794. return {};
  3795. }
  3796. logStatus.error(`${result}:${statusText}(${status})`);
  3797. return {};
  3798. } catch (error) {
  3799. throwError(error, 'Youtube.getInfo');
  3800. return {};
  3801. }
  3802. };
  3803. class Youtube extends social_Social {
  3804. tasks;
  3805. whiteList;
  3806. #auth = GM_getValue('youtubeAuth') || {};
  3807. #initialized = false;
  3808. #verifyChannel = `https://www.youtube.com/channel/${globalOptions.other.youtubeVerifyChannel}`;
  3809. constructor() {
  3810. super();
  3811. const defaultTasksTemplate = {
  3812. channels: [],
  3813. likes: []
  3814. };
  3815. this.tasks = defaultTasksTemplate;
  3816. this.whiteList = {
  3817. ...defaultTasksTemplate,
  3818. ...GM_getValue('whiteList')?.youtube || {}
  3819. };
  3820. }
  3821. async init() {
  3822. try {
  3823. if (this.#initialized) {
  3824. return true;
  3825. }
  3826. if (!this.#auth.PAPISID) {
  3827. if (await this.#updateAuth()) {
  3828. this.#initialized = true;
  3829. return true;
  3830. }
  3831. return false;
  3832. }
  3833. const isVerified = await this.#verifyAuth();
  3834. if (isVerified) {
  3835. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  3836. this.#initialized = true;
  3837. return true;
  3838. }
  3839. GM_setValue('youtubeAuth', null);
  3840. if (await this.#updateAuth()) {
  3841. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  3842. this.#initialized = true;
  3843. return true;
  3844. }
  3845. scripts_echoLog({}).error(i18n('initFailed', 'Youtube'));
  3846. return false;
  3847. } catch (error) {
  3848. throwError(error, 'Youtube.init');
  3849. return false;
  3850. }
  3851. }
  3852. async #verifyAuth() {
  3853. try {
  3854. return await this.#toggleChannel({
  3855. link: this.#verifyChannel,
  3856. doTask: true,
  3857. verify: true
  3858. });
  3859. } catch (error) {
  3860. throwError(error, 'Youtube.verifyAuth');
  3861. return false;
  3862. }
  3863. }
  3864. async #updateAuth() {
  3865. try {
  3866. const logStatus = scripts_echoLog({
  3867. text: i18n('updatingAuth', 'Youtube')
  3868. });
  3869. return await new Promise(resolve => {
  3870. GM_cookie.list({
  3871. url: 'https://www.youtube.com/@YouTube'
  3872. }, async (cookies, error) => {
  3873. if (!error) {
  3874. const PAPISID = cookies.find(cookie => cookie.name === '__Secure-3PAPISID')?.value;
  3875. if (PAPISID) {
  3876. GM_setValue('youtubeAuth', {
  3877. PAPISID: PAPISID
  3878. });
  3879. this.#auth = {
  3880. PAPISID: PAPISID
  3881. };
  3882. logStatus.success();
  3883. resolve(await this.#verifyAuth());
  3884. } else {
  3885. logStatus.error(i18n('needLogin'));
  3886. resolve(false);
  3887. }
  3888. } else {
  3889. logStatus.error('Error: Update youtube auth failed!');
  3890. resolve(false);
  3891. }
  3892. });
  3893. });
  3894. } catch (error) {
  3895. throwError(error, 'Youtube.updateAuth');
  3896. return false;
  3897. }
  3898. }
  3899. #getInfo(link, type) {
  3900. return getInfo(link, type);
  3901. }
  3902. async #toggleChannel({
  3903. link,
  3904. doTask = true,
  3905. verify = false
  3906. }) {
  3907. try {
  3908. const {
  3909. params,
  3910. needLogin
  3911. } = await this.#getInfo(link, 'channel');
  3912. const {
  3913. apiKey,
  3914. client,
  3915. request,
  3916. channelId
  3917. } = params || {};
  3918. if (needLogin) {
  3919. scripts_echoLog({
  3920. html: i18n('loginYtb')
  3921. });
  3922. return false;
  3923. }
  3924. if (!(apiKey && client && request && channelId)) {
  3925. scripts_echoLog({
  3926. text: '"getYtbToken" failed'
  3927. });
  3928. return false;
  3929. }
  3930. if (!doTask && !verify && this.whiteList.channels.includes(channelId)) {
  3931. scripts_echoLog({
  3932. type: 'whiteList',
  3933. text: 'Youtube.unfollowChannel',
  3934. id: channelId
  3935. });
  3936. return true;
  3937. }
  3938. const logStatus = verify ? scripts_echoLog({
  3939. text: i18n('verifyingAuth', 'Youtube')
  3940. }) : scripts_echoLog({
  3941. type: doTask ? 'followingYtbChannel' : 'unfollowingYtbChannel',
  3942. text: channelId
  3943. });
  3944. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  3945. const {
  3946. result,
  3947. statusText,
  3948. status,
  3949. data
  3950. } = await tools_httpRequest({
  3951. url: `https://www.youtube.com/youtubei/v1/subscription/${doTask ? '' : 'un'}subscribe?key=${apiKey}&prettyPrint=false`,
  3952. method: 'POST',
  3953. headers: {
  3954. origin: 'https://www.youtube.com',
  3955. referer: `https://www.youtube.com/channel/${channelId}`,
  3956. 'content-type': 'application/json',
  3957. 'x-goog-authuser': '0',
  3958. 'x-goog-visitor-id': client?.visitorData,
  3959. 'x-origin': 'https://www.youtube.com',
  3960. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  3961. },
  3962. data: JSON.stringify({
  3963. context: {
  3964. client: client,
  3965. request: {
  3966. sessionId: request?.sessionId,
  3967. internalExperimentFlags: [],
  3968. consistencyTokenJars: []
  3969. },
  3970. user: {}
  3971. },
  3972. channelIds: [ channelId ],
  3973. params: doTask ? 'EgIIAhgA' : 'CgIIAhgA'
  3974. })
  3975. });
  3976. if (result === 'Success') {
  3977. if (data?.status === 200) {
  3978. if (doTask && (/"subscribed":true/.test(data.responseText) || data.responseText.includes('The subscription already exists')) || !doTask && /"subscribed":false/.test(data.responseText)) {
  3979. logStatus.success();
  3980. if (doTask && !verify) {
  3981. this.tasks.channels = unique([ ...this.tasks.channels, link ]);
  3982. }
  3983. return true;
  3984. }
  3985. if (verify && data.responseText.includes('You may not subscribe to yourself')) {
  3986. logStatus.success();
  3987. return true;
  3988. }
  3989. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  3990. return false;
  3991. }
  3992. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3993. return false;
  3994. }
  3995. logStatus.error(`${result}:${statusText}(${status})`);
  3996. return false;
  3997. } catch (error) {
  3998. throwError(error, 'Youtube.toggleChannel');
  3999. return false;
  4000. }
  4001. }
  4002. async #toggleLikeVideo({
  4003. link,
  4004. doTask = true
  4005. }) {
  4006. try {
  4007. const {
  4008. params,
  4009. needLogin
  4010. } = await this.#getInfo(link, 'likeVideo');
  4011. const {
  4012. apiKey,
  4013. client,
  4014. request,
  4015. videoId,
  4016. likeParams
  4017. } = params || {};
  4018. if (needLogin) {
  4019. scripts_echoLog({
  4020. html: `${i18n('loginYtb')}`
  4021. });
  4022. return false;
  4023. }
  4024. if (!(apiKey && client && request && videoId && likeParams)) {
  4025. scripts_echoLog({
  4026. text: '"getYtbToken" failed'
  4027. });
  4028. return false;
  4029. }
  4030. if (!doTask && this.whiteList.likes.includes(videoId)) {
  4031. scripts_echoLog({
  4032. type: 'whiteList',
  4033. text: 'Youtube.unlikeVideo',
  4034. id: videoId
  4035. });
  4036. return true;
  4037. }
  4038. const logStatus = scripts_echoLog({
  4039. type: doTask ? 'likingYtbVideo' : 'unlikingYtbVideo',
  4040. text: videoId
  4041. });
  4042. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  4043. const likeVideoData = {
  4044. context: {
  4045. client: client,
  4046. request: {
  4047. sessionId: request.sessionId,
  4048. internalExperimentFlags: [],
  4049. consistencyTokenJars: []
  4050. },
  4051. user: {}
  4052. },
  4053. target: {
  4054. videoId: videoId
  4055. }
  4056. };
  4057. if (doTask) {
  4058. if (likeParams) {
  4059. likeVideoData.params = likeParams;
  4060. } else {
  4061. logStatus.error('Empty likeParams');
  4062. return false;
  4063. }
  4064. }
  4065. const {
  4066. result,
  4067. statusText,
  4068. status,
  4069. data
  4070. } = await tools_httpRequest({
  4071. url: `https://www.youtube.com/youtubei/v1/like/${doTask ? '' : 'remove'}like?key=${apiKey}`,
  4072. method: 'POST',
  4073. headers: {
  4074. origin: 'https://www.youtube.com',
  4075. referer: `https://www.youtube.com/watch?v=${videoId}`,
  4076. 'content-type': 'application/json',
  4077. 'x-goog-authuser': '0',
  4078. 'x-goog-visitor-id': client.visitorData,
  4079. 'x-origin': 'https://www.youtube.com',
  4080. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  4081. },
  4082. data: JSON.stringify(likeVideoData)
  4083. });
  4084. if (result === 'Success') {
  4085. if (data?.status === 200) {
  4086. if (doTask && data.responseText.includes('Added to Liked videos') || !doTask && (data.responseText.includes('Removed from Liked videos') || data.responseText.includes('Dislike removed'))) {
  4087. logStatus.success();
  4088. if (doTask) {
  4089. this.tasks.likes = unique([ ...this.tasks.likes, link ]);
  4090. }
  4091. return true;
  4092. }
  4093. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4094. return false;
  4095. }
  4096. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4097. return false;
  4098. }
  4099. logStatus.error(`${result}:${statusText}(${status})`);
  4100. return false;
  4101. } catch (error) {
  4102. throwError(error, 'Youtube.toggleLikeVideo');
  4103. return false;
  4104. }
  4105. }
  4106. async toggle({
  4107. doTask = true,
  4108. channelLinks = [],
  4109. videoLinks = []
  4110. }) {
  4111. try {
  4112. if (!this.#initialized) {
  4113. scripts_echoLog({
  4114. text: i18n('needInit')
  4115. });
  4116. return false;
  4117. }
  4118. const prom = [];
  4119. if (doTask && !globalOptions.doTask.youtube.channels || !doTask && !globalOptions.undoTask.youtube.channels) {
  4120. scripts_echoLog({
  4121. type: 'globalOptionsSkip',
  4122. text: 'youtube.channels'
  4123. });
  4124. } else {
  4125. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => {
  4126. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4127. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4128. }
  4129. return link;
  4130. });
  4131. if (realChannels.length > 0) {
  4132. for (const channel of realChannels) {
  4133. prom.push(this.#toggleChannel({
  4134. link: channel,
  4135. doTask: doTask
  4136. }));
  4137. await delay(1e3);
  4138. }
  4139. }
  4140. }
  4141. if (doTask && !globalOptions.doTask.youtube.likes || !doTask && !globalOptions.undoTask.youtube.likes) {
  4142. scripts_echoLog({
  4143. type: 'globalOptionsSkip',
  4144. text: 'youtube.likes'
  4145. });
  4146. } else {
  4147. const realLikes = this.getRealParams('likes', videoLinks, doTask, link => {
  4148. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4149. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4150. }
  4151. return link;
  4152. });
  4153. if (realLikes.length > 0) {
  4154. for (const video of realLikes) {
  4155. prom.push(this.#toggleLikeVideo({
  4156. link: video,
  4157. doTask: doTask
  4158. }));
  4159. await delay(1e3);
  4160. }
  4161. }
  4162. }
  4163. return Promise.all(prom).then(() => true);
  4164. } catch (error) {
  4165. throwError(error, 'Youtube.toggle');
  4166. return false;
  4167. }
  4168. }
  4169. }
  4170. class SteamASF {
  4171. #asfOptions;
  4172. #botName = 'asf';
  4173. #groupInfo;
  4174. async init() {
  4175. try {
  4176. const asfCommandsUrl = new URL('/Api/Command/', globalOptions.ASF.AsfIpcUrl);
  4177. this.#asfOptions = {
  4178. url: asfCommandsUrl.href,
  4179. method: 'POST',
  4180. responseType: 'json',
  4181. headers: {
  4182. accept: 'application/json',
  4183. 'Content-Type': 'application/json',
  4184. Host: asfCommandsUrl.host,
  4185. Origin: asfCommandsUrl.origin,
  4186. Referer: asfCommandsUrl.href,
  4187. Authentication: globalOptions.ASF.AsfIpcPassword
  4188. }
  4189. };
  4190. if (globalOptions.ASF.AsfBotname) {
  4191. this.#botName = globalOptions.ASF.AsfBotname;
  4192. }
  4193. const logStatus = scripts_echoLog({
  4194. text: i18n('initingASF')
  4195. });
  4196. const {
  4197. result,
  4198. statusText,
  4199. status,
  4200. data
  4201. } = await tools_httpRequest({
  4202. ...this.#asfOptions,
  4203. data: '{"Command":"!stats"}'
  4204. });
  4205. if (result === 'Success') {
  4206. if (data?.response?.Success === true && data.response.Message === 'OK' && data.response.Result) {
  4207. logStatus.success();
  4208. return true;
  4209. }
  4210. if (data?.response?.Result || data?.response?.Message) {
  4211. logStatus.error(data?.response?.Result || data.response.Message);
  4212. return false;
  4213. }
  4214. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4215. return false;
  4216. }
  4217. logStatus.error(`${result}:${statusText}(${status})`);
  4218. return false;
  4219. } catch (error) {
  4220. throwError(error, 'SteamASF.init');
  4221. return false;
  4222. }
  4223. }
  4224. async joinGroup(groupName) {
  4225. try {
  4226. const logStatus = scripts_echoLog({
  4227. type: 'joiningSteamGroup',
  4228. text: groupName
  4229. });
  4230. const {
  4231. result,
  4232. statusText,
  4233. status,
  4234. data
  4235. } = await tools_httpRequest({
  4236. ...this.#asfOptions,
  4237. data: JSON.stringify({
  4238. Command: `!JOINGROUP ${this.#botName} ${groupName}`
  4239. })
  4240. });
  4241. if (result === 'Success') {
  4242. if (data?.status === 200 && [ '已加入', '已申请', 'Joined', 'Applied', 'Присоединился', 'costs' ].find(text => data.response?.Result?.includes(text))) {
  4243. logStatus.success();
  4244. return true;
  4245. }
  4246. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4247. return false;
  4248. }
  4249. logStatus.error(`${result}:${statusText}(${status})`);
  4250. return false;
  4251. } catch (error) {
  4252. throwError(error, 'SteamASF.joinGroup');
  4253. return false;
  4254. }
  4255. }
  4256. async leaveGroup(groupName) {
  4257. try {
  4258. if (!this.#groupInfo) {
  4259. if (!await this.#getGroupId()) {
  4260. return false;
  4261. }
  4262. }
  4263. const groupId = await this.#groupInfo[groupName];
  4264. if (!groupId) {
  4265. return false;
  4266. }
  4267. const logStatus = scripts_echoLog({
  4268. type: 'leavingSteamGroup',
  4269. text: groupName
  4270. });
  4271. const {
  4272. result,
  4273. statusText,
  4274. status,
  4275. data
  4276. } = await tools_httpRequest({
  4277. ...this.#asfOptions,
  4278. data: JSON.stringify({
  4279. Command: `!LEAVEGROUP ${this.#botName} ${groupId}`
  4280. })
  4281. });
  4282. if (result === 'Success') {
  4283. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4284. logStatus.success();
  4285. return true;
  4286. }
  4287. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4288. return false;
  4289. }
  4290. logStatus.error(`${result}:${statusText}(${status})`);
  4291. return false;
  4292. } catch (error) {
  4293. throwError(error, 'SteamASF.leaveGroup');
  4294. return false;
  4295. }
  4296. }
  4297. async #getGroupId() {
  4298. try {
  4299. const logStatus = scripts_echoLog({
  4300. type: 'gettingSteamGroupId',
  4301. text: 'All'
  4302. });
  4303. const {
  4304. result,
  4305. statusText,
  4306. status,
  4307. data
  4308. } = await tools_httpRequest({
  4309. ...this.#asfOptions,
  4310. data: JSON.stringify({
  4311. Command: `!GROUPLIST ${this.#botName}`
  4312. })
  4313. });
  4314. if (result === 'Success') {
  4315. if (data?.status === 200 && data.response?.Result?.includes('|')) {
  4316. this.#groupInfo = Object.fromEntries(data.response.Result.split('\n').map(line => {
  4317. const [ , name, id ] = line.trim().split('|');
  4318. if (name && id) {
  4319. return [ name, id ];
  4320. }
  4321. return null;
  4322. }).filter(ele => ele));
  4323. logStatus.success();
  4324. return true;
  4325. }
  4326. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4327. return false;
  4328. }
  4329. logStatus.error(`${result}:${statusText}(${status})`);
  4330. return false;
  4331. } catch (error) {
  4332. throwError(error, 'SteamASF.getGroupID');
  4333. return false;
  4334. }
  4335. }
  4336. async addToWishlist(gameId) {
  4337. try {
  4338. const logStatus = scripts_echoLog({
  4339. type: 'addingToWishlist',
  4340. text: gameId
  4341. });
  4342. if ((await this.#checkGame(gameId)).wishlist === true) {
  4343. logStatus.success();
  4344. return true;
  4345. }
  4346. const {
  4347. result,
  4348. statusText,
  4349. status,
  4350. data
  4351. } = await tools_httpRequest({
  4352. ...this.#asfOptions,
  4353. data: JSON.stringify({
  4354. Command: `!ADDWISHLIST ${this.#botName} ${gameId}`
  4355. })
  4356. });
  4357. if (result === 'Success') {
  4358. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4359. logStatus.success();
  4360. return true;
  4361. }
  4362. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4363. return false;
  4364. }
  4365. logStatus.error(`${result}:${statusText}(${status})`);
  4366. return false;
  4367. } catch (error) {
  4368. throwError(error, 'SteamASF.addToWishlist');
  4369. return false;
  4370. }
  4371. }
  4372. async removeFromWishlist(gameId) {
  4373. try {
  4374. const logStatus = scripts_echoLog({
  4375. type: 'removingFromWishlist',
  4376. text: gameId
  4377. });
  4378. if ((await this.#checkGame(gameId)).wishlist === false) {
  4379. logStatus.success();
  4380. return true;
  4381. }
  4382. const {
  4383. result,
  4384. statusText,
  4385. status,
  4386. data
  4387. } = await tools_httpRequest({
  4388. ...this.#asfOptions,
  4389. data: JSON.stringify({
  4390. Command: `!REMOVEWISHLIST ${this.#botName} ${gameId}`
  4391. })
  4392. });
  4393. if (result === 'Success') {
  4394. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4395. logStatus.success();
  4396. return true;
  4397. }
  4398. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4399. return false;
  4400. }
  4401. logStatus.error(`${result}:${statusText}(${status})`);
  4402. return false;
  4403. } catch (error) {
  4404. throwError(error, 'SteamASF.removeFromWishlist');
  4405. return false;
  4406. }
  4407. }
  4408. async toggleFollowGame(gameId, doTask) {
  4409. try {
  4410. const logStatus = scripts_echoLog({
  4411. type: `${doTask ? '' : 'un'}followingGame`,
  4412. text: gameId
  4413. });
  4414. if (doTask && (await this.#checkGame(gameId)).followed === true || !doTask && (await this.#checkGame(gameId)).followed === false) {
  4415. logStatus.success();
  4416. return true;
  4417. }
  4418. const {
  4419. result,
  4420. statusText,
  4421. status,
  4422. data
  4423. } = await tools_httpRequest({
  4424. ...this.#asfOptions,
  4425. data: JSON.stringify({
  4426. Command: `!${doTask ? '' : 'UN'}FOLLOWGAME ${this.#botName} ${gameId}`
  4427. })
  4428. });
  4429. if (result === 'Success') {
  4430. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4431. logStatus.success();
  4432. return true;
  4433. }
  4434. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4435. return false;
  4436. }
  4437. logStatus.error(`${result}:${statusText}(${status})`);
  4438. return false;
  4439. } catch (error) {
  4440. throwError(error, 'SteamASF.toggleFollowGame');
  4441. return false;
  4442. }
  4443. }
  4444. async #checkGame(gameId) {
  4445. try {
  4446. const {
  4447. result,
  4448. data
  4449. } = await tools_httpRequest({
  4450. ...this.#asfOptions,
  4451. data: JSON.stringify({
  4452. Command: `!CHECK ${this.#botName} ${gameId}`
  4453. })
  4454. });
  4455. if (result === 'Success') {
  4456. if (data?.status === 200 && data.response?.Result?.includes(gameId)) {
  4457. const matchedResult = data.response.Result.split('\n').find(result => result.includes(gameId))?.split('|');
  4458. if (matchedResult?.length > 3) {
  4459. return {
  4460. wishlist: matchedResult.at(-3).trim() === '√' || matchedResult.at(-2).trim() === '√',
  4461. followed: matchedResult.at(-1).trim() === '√'
  4462. };
  4463. }
  4464. return {};
  4465. }
  4466. return {};
  4467. }
  4468. return {};
  4469. } catch (error) {
  4470. throwError(error, 'SteamASF.checkGame');
  4471. return {};
  4472. }
  4473. }
  4474. async toggleCurator(curatorId, doTask = true) {
  4475. try {
  4476. const logStatus = scripts_echoLog({
  4477. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  4478. text: curatorId
  4479. });
  4480. const {
  4481. result,
  4482. statusText,
  4483. status,
  4484. data
  4485. } = await tools_httpRequest({
  4486. ...this.#asfOptions,
  4487. data: JSON.stringify({
  4488. Command: `!${doTask ? '' : 'UN'}FOLLOWCURATOR ${this.#botName} ${curatorId}`
  4489. })
  4490. });
  4491. if (result === 'Success') {
  4492. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4493. logStatus.success();
  4494. return true;
  4495. }
  4496. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4497. return false;
  4498. }
  4499. logStatus.error(`${result}:${statusText}(${status})`);
  4500. return false;
  4501. } catch (error) {
  4502. throwError(error, 'Steam.toggleCurator');
  4503. return false;
  4504. }
  4505. }
  4506. async addLicense(id) {
  4507. try {
  4508. const [ type, ids ] = id.split('-');
  4509. if (type === 'appid') {
  4510. const logStatus = scripts_echoLog({
  4511. type: 'addingFreeLicense',
  4512. text: ids
  4513. });
  4514. const {
  4515. result,
  4516. statusText,
  4517. status,
  4518. data
  4519. } = await tools_httpRequest({
  4520. ...this.#asfOptions,
  4521. data: JSON.stringify({
  4522. Command: `!addlicense ${this.#botName} app/${ids}`
  4523. })
  4524. });
  4525. if (result === 'Success') {
  4526. if (data?.status === 200 && [ 'AlreadyPurchased', 'OK' ].find(text => data.response?.Result?.includes(text))) {
  4527. logStatus.success();
  4528. return true;
  4529. }
  4530. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4531. return false;
  4532. }
  4533. logStatus.error(`${result}:${statusText}(${status})`);
  4534. return false;
  4535. } else if (type === 'subid') {
  4536. const idsArr = ids.split(',');
  4537. const logStatus = scripts_echoLog({
  4538. type: 'addingFreeLicenseSubid',
  4539. text: ids
  4540. });
  4541. const {
  4542. result,
  4543. statusText,
  4544. status,
  4545. data
  4546. } = await tools_httpRequest({
  4547. ...this.#asfOptions,
  4548. data: JSON.stringify({
  4549. Command: `!addlicense ${this.#botName} ${idsArr.map(id => `sub/${id}`).join(',')}`
  4550. })
  4551. });
  4552. if (result === 'Success') {
  4553. if (data?.status === 200 && data.response?.Result) {
  4554. const resultLines = data.response.Result.split('\n');
  4555. idsArr.forEach(subid => {
  4556. const targetLine = resultLines.find(text => text.includes(subid));
  4557. if (targetLine && [ '成功', 'Success', 'Успех' ].find(text => targetLine.includes(text))) {
  4558. scripts_echoLog({}).success(targetLine);
  4559. } else {
  4560. scripts_echoLog({}).error(targetLine);
  4561. }
  4562. });
  4563. return true;
  4564. }
  4565. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4566. return false;
  4567. }
  4568. logStatus.error(`${result}:${statusText}(${status})`);
  4569. return false;
  4570. }
  4571. return false;
  4572. } catch (error) {
  4573. throwError(error, 'SteamASF.addLicense');
  4574. return false;
  4575. }
  4576. }
  4577. async requestPlayTestAccess(id) {
  4578. try {
  4579. const logStatus = scripts_echoLog({
  4580. type: 'requestingPlayTestAccess',
  4581. text: id
  4582. });
  4583. const {
  4584. result,
  4585. statusText,
  4586. status,
  4587. data
  4588. } = await tools_httpRequest({
  4589. ...this.#asfOptions,
  4590. data: JSON.stringify({
  4591. Command: `!REQUESTACCESS ${this.#botName} ${id}`
  4592. })
  4593. });
  4594. if (result === 'Success') {
  4595. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4596. logStatus.success();
  4597. return true;
  4598. }
  4599. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4600. return false;
  4601. }
  4602. logStatus.error(`${result}:${statusText}(${status})`);
  4603. return false;
  4604. } catch (error) {
  4605. throwError(error, 'Steam.requestPlayTestAccess');
  4606. return false;
  4607. }
  4608. }
  4609. }
  4610. const social_SteamASF = SteamASF;
  4611. class Steam extends social_Social {
  4612. tasks;
  4613. whiteList;
  4614. #cache = {
  4615. ...{
  4616. group: {},
  4617. officialGroup: {},
  4618. forum: {},
  4619. workshop: {},
  4620. curator: {}
  4621. },
  4622. ...GM_getValue('steamCache')
  4623. };
  4624. #auth = {};
  4625. #storeInitialized = false;
  4626. #communityInitialized = false;
  4627. #area = 'CN';
  4628. #oldArea;
  4629. #areaStatus = 'end';
  4630. #ASF;
  4631. constructor() {
  4632. super();
  4633. const defaultTasksTemplate = {
  4634. groups: [],
  4635. officialGroups: [],
  4636. wishlists: [],
  4637. follows: [],
  4638. forums: [],
  4639. workshops: [],
  4640. workshopVotes: [],
  4641. curators: [],
  4642. curatorLikes: [],
  4643. announcements: [],
  4644. licenses: [],
  4645. playtests: []
  4646. };
  4647. this.tasks = defaultTasksTemplate;
  4648. this.whiteList = {
  4649. ...defaultTasksTemplate,
  4650. ...GM_getValue('whiteList')?.steam || {}
  4651. };
  4652. }
  4653. async init(type = 'all') {
  4654. try {
  4655. if (globalOptions.ASF.AsfEnabled && globalOptions.ASF.AsfIpcUrl && globalOptions.ASF.AsfIpcPassword) {
  4656. this.#ASF = new social_SteamASF();
  4657. if (await this.#ASF.init()) {
  4658. this.#storeInitialized = true;
  4659. this.#communityInitialized = true;
  4660. return true;
  4661. }
  4662. return false;
  4663. }
  4664. if (type === 'store') {
  4665. if (this.#storeInitialized) {
  4666. return true;
  4667. }
  4668. let storeInitialized = await this.#updateStoreAuth();
  4669. if (!storeInitialized) {
  4670. storeInitialized = await this.#updateStoreAuthTab();
  4671. }
  4672. this.#storeInitialized = storeInitialized;
  4673. if (!this.#storeInitialized) {
  4674. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4675. return false;
  4676. }
  4677. scripts_echoLog({}).success(i18n('initSuccess', 'SteamStore'));
  4678. return true;
  4679. }
  4680. if (type === 'community') {
  4681. if (this.#communityInitialized) {
  4682. return true;
  4683. }
  4684. let communityInitialized = await this.#updateCommunityAuth();
  4685. if (!communityInitialized) {
  4686. communityInitialized = await this.#updateCommunityAuthTab();
  4687. GM_setValue('steamCommunityAuth', null);
  4688. }
  4689. this.#communityInitialized = communityInitialized;
  4690. if (!this.#communityInitialized) {
  4691. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4692. return false;
  4693. }
  4694. scripts_echoLog({}).success(i18n('initSuccess', 'SteamCommunity'));
  4695. return true;
  4696. }
  4697. if (this.#storeInitialized && this.#communityInitialized) {
  4698. scripts_echoLog({}).success(i18n('initSuccess', 'Steam'));
  4699. return true;
  4700. }
  4701. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  4702. return false;
  4703. } catch (error) {
  4704. throwError(error, 'Steam.init');
  4705. return false;
  4706. }
  4707. }
  4708. async #refreshToken(type = 'steamStore') {
  4709. try {
  4710. const host = {
  4711. steamStore: 'store.steampowered.com',
  4712. steamCommunity: 'steamcommunity.com'
  4713. };
  4714. const logStatus = scripts_echoLog({
  4715. text: i18n('refreshingToken', i18n(type))
  4716. });
  4717. const formData = new FormData();
  4718. formData.append('redir', `https://${host[type]}/`);
  4719. const {
  4720. result,
  4721. statusText,
  4722. status,
  4723. data
  4724. } = await tools_httpRequest({
  4725. url: 'https://login.steampowered.com/jwt/ajaxrefresh',
  4726. method: 'POST',
  4727. responseType: 'json',
  4728. headers: {
  4729. Host: 'login.steampowered.com',
  4730. Origin: `https://${host[type]}`,
  4731. Referer: `https://${host[type]}/`
  4732. },
  4733. data: formData
  4734. });
  4735. if (result === 'Success') {
  4736. if (data?.response?.success) {
  4737. if (await this.#setStoreToken(data.response, type)) {
  4738. logStatus.success();
  4739. return true;
  4740. }
  4741. logStatus.error('Error');
  4742. return false;
  4743. }
  4744. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4745. return false;
  4746. }
  4747. logStatus.error(`${result}:${statusText}(${status})`);
  4748. return false;
  4749. } catch (error) {
  4750. throwError(error, 'Steam.refreshToken');
  4751. return false;
  4752. }
  4753. }
  4754. async #setStoreToken(param, type) {
  4755. try {
  4756. const host = {
  4757. steamStore: 'store.steampowered.com',
  4758. steamCommunity: 'steamcommunity.com'
  4759. };
  4760. const logStatus = scripts_echoLog({
  4761. text: i18n('settingToken', i18n(type))
  4762. });
  4763. const formData = new FormData();
  4764. formData.append('steamID', param.steamID);
  4765. formData.append('nonce', param.nonce);
  4766. formData.append('redir', param.redir);
  4767. formData.append('auth', param.auth);
  4768. const {
  4769. result,
  4770. statusText,
  4771. status,
  4772. data
  4773. } = await tools_httpRequest({
  4774. url: `https://${host[type]}/login/settoken`,
  4775. method: 'POST',
  4776. headers: {
  4777. Accept: 'application/json, text/plain, */*',
  4778. Host: host[type],
  4779. Origin: `https://${host[type]}`
  4780. },
  4781. data: formData
  4782. });
  4783. if (result === 'Success') {
  4784. if (data?.status === 200) {
  4785. logStatus.success();
  4786. return true;
  4787. }
  4788. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4789. return false;
  4790. }
  4791. logStatus.error(`${result}:${statusText}(${status})`);
  4792. return false;
  4793. } catch (error) {
  4794. throwError(error, 'Steam.setStoreToken');
  4795. return false;
  4796. }
  4797. }
  4798. async #updateStoreAuth(retry = false) {
  4799. try {
  4800. const logStatus = scripts_echoLog({
  4801. text: i18n('updatingAuth', i18n('steamStore'))
  4802. });
  4803. const {
  4804. result,
  4805. statusText,
  4806. status,
  4807. data
  4808. } = await tools_httpRequest({
  4809. url: 'https://store.steampowered.com/',
  4810. method: 'GET',
  4811. headers: {
  4812. 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',
  4813. 'Sec-Fetch-Dest': 'document',
  4814. 'Sec-Fetch-Mode': 'navigate',
  4815. 'Upgrade-Insecure-Requests': '1'
  4816. },
  4817. fetch: false,
  4818. redirect: 'manual'
  4819. });
  4820. if (data?.status === 200) {
  4821. if (!data.responseText.includes('data-miniprofile=')) {
  4822. if (await this.#refreshToken('steamStore')) {
  4823. logStatus.warning(i18n('retry'));
  4824. if (retry) {
  4825. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4826. return false;
  4827. }
  4828. return this.#updateStoreAuth(true);
  4829. }
  4830. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4831. return false;
  4832. }
  4833. const storeSessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  4834. if (storeSessionID) {
  4835. this.#auth.storeSessionID = storeSessionID;
  4836. logStatus.success();
  4837. return true;
  4838. }
  4839. logStatus.error('Error: Get "sessionID" failed');
  4840. return false;
  4841. }
  4842. if ([ 301, 302 ].includes(data?.status)) {
  4843. if (await this.#refreshToken('steamStore')) {
  4844. logStatus.warning(i18n('retry'));
  4845. if (retry) {
  4846. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4847. return false;
  4848. }
  4849. return this.#updateStoreAuth(true);
  4850. }
  4851. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  4852. return false;
  4853. }
  4854. logStatus.error(`${result}:${statusText}(${status})`);
  4855. return false;
  4856. } catch (error) {
  4857. throwError(error, 'Steam.updateStoreAuth');
  4858. return false;
  4859. }
  4860. }
  4861. async #updateStoreAuthTab() {
  4862. try {
  4863. const logStatus = scripts_echoLog({
  4864. text: i18n('updatingAuth', i18n('steamStoreTab'))
  4865. });
  4866. return await new Promise(resolve => {
  4867. GM_deleteValue('steamStoreAuth');
  4868. GM_setValue('ATv4_updateStoreAuth', true);
  4869. const newTab = GM_openInTab('https://store.steampowered.com/', {
  4870. active: true,
  4871. setParent: true
  4872. });
  4873. newTab.name = 'ATv4_updateStoreAuth';
  4874. const listenerId = GM_addValueChangeListener('steamStoreAuth', (key, oldValue, newValue) => {
  4875. GM_removeValueChangeListener(listenerId);
  4876. GM_deleteValue('ATv4_updateStoreAuth');
  4877. newTab?.close();
  4878. window.focus();
  4879. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  4880. this.#auth.storeSessionID = newValue.storeSessionID;
  4881. logStatus.success();
  4882. resolve(true);
  4883. return;
  4884. }
  4885. logStatus.error('Failed');
  4886. resolve(false);
  4887. });
  4888. newTab.onclose = () => {
  4889. GM_deleteValue('ATv4_updateStoreAuth');
  4890. };
  4891. });
  4892. } catch (error) {
  4893. throwError(error, 'Steam.updateStoreAuthTab');
  4894. return false;
  4895. }
  4896. }
  4897. async #updateCommunityAuthTab() {
  4898. try {
  4899. const logStatus = scripts_echoLog({
  4900. text: i18n('updatingAuth', i18n('steamCommunityTab'))
  4901. });
  4902. return await new Promise(resolve => {
  4903. GM_deleteValue('steamCommunityAuth');
  4904. GM_setValue('ATv4_updateCommunityAuth', true);
  4905. const newTab = GM_openInTab('https://steamcommunity.com/my', {
  4906. active: true,
  4907. setParent: true
  4908. });
  4909. newTab.name = 'ATv4_updateCommunityAuth';
  4910. const listenerId = GM_addValueChangeListener('steamCommunityAuth', (key, oldValue, newValue) => {
  4911. GM_removeValueChangeListener(listenerId);
  4912. GM_deleteValue('ATv4_updateCommunityAuth');
  4913. newTab?.close();
  4914. window.focus();
  4915. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  4916. this.#auth.steam64Id = newValue.steam64Id;
  4917. this.#auth.communitySessionID = newValue.communitySessionID;
  4918. logStatus.success();
  4919. resolve(true);
  4920. return;
  4921. }
  4922. logStatus.error('Failed');
  4923. resolve(false);
  4924. });
  4925. newTab.onclose = () => {
  4926. GM_deleteValue('ATv4_updateCommunityAuth');
  4927. };
  4928. });
  4929. } catch (error) {
  4930. throwError(error, 'Steam.updateCommunityAuthTab');
  4931. return false;
  4932. }
  4933. }
  4934. async #updateCommunityAuth() {
  4935. try {
  4936. const logStatus = scripts_echoLog({
  4937. text: i18n('gettingUserLink')
  4938. });
  4939. const {
  4940. result,
  4941. statusText,
  4942. status,
  4943. data
  4944. } = await tools_httpRequest({
  4945. url: 'https://steamcommunity.com/my',
  4946. method: 'GET',
  4947. headers: {
  4948. 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',
  4949. Host: 'steamcommunity.com',
  4950. 'Sec-Fetch-Dest': 'document',
  4951. 'Sec-Fetch-Mode': 'navigate'
  4952. },
  4953. fetch: false
  4954. });
  4955. if (data?.status === 200) {
  4956. if (data.finalUrl.includes('https://steamcommunity.com/login/home')) {
  4957. logStatus.error(`Error:${i18n('needLoginSteamCommunity')}`, true);
  4958. return false;
  4959. }
  4960. const steam64Id = data.responseText.match(/g_steamID = "(.+?)";/)?.[1];
  4961. const communitySessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  4962. if (steam64Id && communitySessionID) {
  4963. this.#auth.steam64Id = steam64Id;
  4964. this.#auth.communitySessionID = communitySessionID;
  4965. logStatus.success();
  4966. return true;
  4967. }
  4968. logStatus.error('Error: Get "sessionID" failed');
  4969. return false;
  4970. }
  4971. logStatus.error(`${result}:${statusText}(${status})`);
  4972. return false;
  4973. } catch (error) {
  4974. throwError(error, 'Steam.updateCommunityAuth');
  4975. return false;
  4976. }
  4977. }
  4978. async #getAreaInfo() {
  4979. try {
  4980. const logStatus = scripts_echoLog({
  4981. text: i18n('gettingAreaInfo')
  4982. });
  4983. const {
  4984. result,
  4985. statusText,
  4986. status,
  4987. data
  4988. } = await tools_httpRequest({
  4989. url: 'https://store.steampowered.com/cart/',
  4990. method: 'GET'
  4991. });
  4992. if (result === 'Success') {
  4993. if (data?.status === 200) {
  4994. const cartConfigRaw = data.responseText.match(/data-cart_config="(.*?)"/)?.[1];
  4995. const temp = document.createElement('div');
  4996. temp.innerHTML = cartConfigRaw || '{}';
  4997. const cartConfigStr = temp.textContent || temp.innerText;
  4998. let cartConfig;
  4999. try {
  5000. cartConfig = JSON.parse(cartConfigStr);
  5001. } catch (error) {
  5002. logStatus.error('Error: get country info filed');
  5003. console.error(error);
  5004. return {};
  5005. }
  5006. if (!cartConfig.rgUserCountryOptions) {
  5007. logStatus.warning('Warning: Area cannot be changed');
  5008. return {};
  5009. }
  5010. const userInfoRaw = data.responseText.match(/data-userinfo="(.*?)"/)?.[1];
  5011. const temp1 = document.createElement('div');
  5012. temp1.innerHTML = userInfoRaw || '{}';
  5013. const userInfoStr = temp1.textContent || temp1.innerText;
  5014. let userInfo;
  5015. try {
  5016. userInfo = JSON.parse(userInfoStr);
  5017. } catch (error) {
  5018. logStatus.error('Error: get country info filed');
  5019. console.error(error);
  5020. return {};
  5021. }
  5022. const currentArea = userInfo.country_code;
  5023. const areas = Object.keys(cartConfig.rgUserCountryOptions).filter(area => area !== 'help');
  5024. if (currentArea && areas.length > 0) {
  5025. this.#area = currentArea;
  5026. logStatus.success();
  5027. return {
  5028. currentArea: currentArea,
  5029. areas: areas
  5030. };
  5031. }
  5032. logStatus.error('Error: get country info filed');
  5033. return {};
  5034. }
  5035. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5036. return {};
  5037. }
  5038. logStatus.error(`${result}:${statusText}(${status})`);
  5039. return {};
  5040. } catch (error) {
  5041. throwError(error, 'Steam.getAreaInfo');
  5042. return {};
  5043. }
  5044. }
  5045. async #changeArea(area) {
  5046. try {
  5047. if (this.#areaStatus === 'waiting') {
  5048. await new Promise(resolve => {
  5049. const checker = setInterval(() => {
  5050. if (this.#areaStatus !== 'waiting') {
  5051. clearInterval(checker);
  5052. resolve(true);
  5053. }
  5054. });
  5055. });
  5056. }
  5057. if (this.#area === area || !area && this.#area !== 'CN') {
  5058. return true;
  5059. }
  5060. this.#areaStatus = 'waiting';
  5061. let aimedArea = area;
  5062. if (!aimedArea) {
  5063. const {
  5064. currentArea,
  5065. areas
  5066. } = await this.#getAreaInfo();
  5067. if (!currentArea || !areas) {
  5068. this.#areaStatus = 'error';
  5069. return false;
  5070. }
  5071. if (currentArea !== 'CN') {
  5072. this.#areaStatus = 'skip';
  5073. scripts_echoLog({
  5074. text: 'notNeededChangeArea'
  5075. });
  5076. return 'skip';
  5077. }
  5078. const anotherArea = areas.filter(area => area && area !== 'CN');
  5079. if (!anotherArea || anotherArea.length === 0) {
  5080. this.#areaStatus = 'noAnotherArea';
  5081. scripts_echoLog({
  5082. text: 'noAnotherArea'
  5083. });
  5084. return false;
  5085. }
  5086. [ aimedArea ] = anotherArea;
  5087. }
  5088. const logStatus = scripts_echoLog({
  5089. text: i18n('changingArea', aimedArea)
  5090. });
  5091. const {
  5092. result,
  5093. statusText,
  5094. status,
  5095. data
  5096. } = await tools_httpRequest({
  5097. url: 'https://store.steampowered.com/country/setcountry',
  5098. method: 'POST',
  5099. headers: {
  5100. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5101. },
  5102. data: $.param({
  5103. cc: aimedArea,
  5104. sessionid: this.#auth.storeSessionID
  5105. })
  5106. });
  5107. if (result === 'Success') {
  5108. if (data?.status === 200 && data.responseText === 'true') {
  5109. const {
  5110. currentArea
  5111. } = await this.#getAreaInfo();
  5112. if (currentArea) {
  5113. this.#area = currentArea;
  5114. if (!this.#oldArea) {
  5115. this.#oldArea = currentArea;
  5116. }
  5117. }
  5118. if (currentArea === aimedArea) {
  5119. this.#areaStatus = 'success';
  5120. logStatus.success();
  5121. return currentArea;
  5122. }
  5123. this.#areaStatus = 'error';
  5124. logStatus.error('Error: change country filed');
  5125. return 'CN';
  5126. }
  5127. this.#areaStatus = 'error';
  5128. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5129. return 'CN';
  5130. }
  5131. this.#areaStatus = 'error';
  5132. logStatus.error(`${result}:${statusText}(${status})`);
  5133. return 'CN';
  5134. } catch (error) {
  5135. this.#areaStatus = 'error';
  5136. throwError(error, 'Steam.changeArea');
  5137. return false;
  5138. }
  5139. }
  5140. async #joinGroup(groupName) {
  5141. try {
  5142. if (this.#ASF) {
  5143. if (await this.#ASF.joinGroup(groupName)) {
  5144. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5145. return true;
  5146. }
  5147. return false;
  5148. }
  5149. const logStatus = scripts_echoLog({
  5150. type: 'joiningSteamGroup',
  5151. text: groupName
  5152. });
  5153. const {
  5154. result,
  5155. statusText,
  5156. status,
  5157. data
  5158. } = await tools_httpRequest({
  5159. url: `https://steamcommunity.com/groups/${groupName}`,
  5160. method: 'POST',
  5161. headers: {
  5162. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5163. },
  5164. data: $.param({
  5165. action: 'join',
  5166. sessionID: this.#auth.communitySessionID
  5167. })
  5168. });
  5169. if (result === 'Success') {
  5170. if (data?.status === 200 && !data.responseText.includes('grouppage_join_area')) {
  5171. logStatus.success();
  5172. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5173. return true;
  5174. }
  5175. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5176. return false;
  5177. }
  5178. logStatus.error(`${result}:${statusText}(${status})`);
  5179. return false;
  5180. } catch (error) {
  5181. throwError(error, 'Steam.joinGroup');
  5182. return false;
  5183. }
  5184. }
  5185. async #leaveGroup(groupName) {
  5186. try {
  5187. if (this.whiteList.groups.includes(groupName)) {
  5188. scripts_echoLog({
  5189. type: 'whiteList',
  5190. text: 'Steam.leaveGroup',
  5191. id: groupName
  5192. });
  5193. return true;
  5194. }
  5195. if (this.#ASF) {
  5196. return await this.#ASF.leaveGroup(groupName);
  5197. }
  5198. const groupId = await this.#getGroupId(groupName);
  5199. if (!groupId) {
  5200. return false;
  5201. }
  5202. const logStatus = scripts_echoLog({
  5203. type: 'leavingSteamGroup',
  5204. text: groupName
  5205. });
  5206. const {
  5207. result,
  5208. statusText,
  5209. status,
  5210. data
  5211. } = await tools_httpRequest({
  5212. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5213. method: 'POST',
  5214. headers: {
  5215. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5216. },
  5217. data: $.param({
  5218. sessionID: this.#auth.communitySessionID,
  5219. action: 'leaveGroup',
  5220. groupId: groupId
  5221. })
  5222. });
  5223. if (result === 'Success') {
  5224. 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) {
  5225. logStatus.success();
  5226. return true;
  5227. }
  5228. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5229. return false;
  5230. }
  5231. logStatus.error(`${result}:${statusText}(${status})`);
  5232. return false;
  5233. } catch (error) {
  5234. throwError(error, 'Steam.leaveGroup');
  5235. return false;
  5236. }
  5237. }
  5238. async #getGroupId(groupName) {
  5239. try {
  5240. const logStatus = scripts_echoLog({
  5241. type: 'gettingSteamGroupId',
  5242. text: groupName
  5243. });
  5244. const groupId = this.#cache.group[groupName];
  5245. if (groupId) {
  5246. logStatus.success();
  5247. return groupId;
  5248. }
  5249. const {
  5250. result,
  5251. statusText,
  5252. status,
  5253. data
  5254. } = await tools_httpRequest({
  5255. url: `https://steamcommunity.com/groups/${groupName}`,
  5256. method: 'GET',
  5257. headers: {
  5258. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5259. }
  5260. });
  5261. if (result === 'Success') {
  5262. if (data?.status === 200) {
  5263. const groupId = data.responseText.match(/OpenGroupChat\( '([0-9]+)'/)?.[1];
  5264. if (groupId) {
  5265. this.#setCache('group', groupName, groupId);
  5266. logStatus.success();
  5267. return groupId;
  5268. }
  5269. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5270. return false;
  5271. }
  5272. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5273. return false;
  5274. }
  5275. logStatus.error(`${result}:${statusText}(${status})`);
  5276. return false;
  5277. } catch (error) {
  5278. throwError(error, 'Steam.getGroupID');
  5279. return false;
  5280. }
  5281. }
  5282. async #joinOfficialGroup(gameId) {
  5283. try {
  5284. if (this.#ASF) {
  5285. if (await this.#ASF.joinGroup(gameId)) {
  5286. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5287. return true;
  5288. }
  5289. return false;
  5290. }
  5291. const logStatus = scripts_echoLog({
  5292. type: 'joiningSteamOfficialGroup',
  5293. text: gameId
  5294. });
  5295. const {
  5296. result,
  5297. statusText,
  5298. status,
  5299. data
  5300. } = await tools_httpRequest({
  5301. url: `https://steamcommunity.com/games/${gameId}?action=join&sessionID=${this.#auth.communitySessionID}`,
  5302. method: 'GET',
  5303. headers: {
  5304. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5305. }
  5306. });
  5307. if (result === 'Success') {
  5308. if (data?.status === 200 && !data.responseText.includes('id="publicGroupJoin"')) {
  5309. logStatus.success();
  5310. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5311. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5312. if (groupId) {
  5313. this.#setCache('officialGroup', gameId, groupId);
  5314. }
  5315. return true;
  5316. }
  5317. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5318. return false;
  5319. }
  5320. logStatus.error(`${result}:${statusText}(${status})`);
  5321. return false;
  5322. } catch (error) {
  5323. throwError(error, 'Steam.joinOfficialGroup');
  5324. return false;
  5325. }
  5326. }
  5327. async #leaveOfficialGroup(gameId) {
  5328. try {
  5329. if (this.whiteList.officialGroups.includes(gameId)) {
  5330. scripts_echoLog({
  5331. type: 'whiteList',
  5332. text: 'Steam.leaveOfficialGroup',
  5333. id: gameId
  5334. });
  5335. return true;
  5336. }
  5337. if (this.#ASF) {
  5338. return await this.#ASF.leaveGroup(gameId);
  5339. }
  5340. const groupId = await this.#getOfficialGroupId(gameId);
  5341. if (!groupId) {
  5342. return false;
  5343. }
  5344. const logStatus = scripts_echoLog({
  5345. type: 'leavingSteamOfficialGroup',
  5346. text: gameId
  5347. });
  5348. const {
  5349. result,
  5350. statusText,
  5351. status,
  5352. data
  5353. } = await tools_httpRequest({
  5354. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5355. method: 'POST',
  5356. headers: {
  5357. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5358. },
  5359. data: $.param({
  5360. sessionID: this.#auth.communitySessionID,
  5361. action: 'leaveGroup',
  5362. groupId: groupId
  5363. })
  5364. });
  5365. if (result === 'Success') {
  5366. if (data?.status === 200) {
  5367. const {
  5368. result: resultR,
  5369. statusText: statusTextR,
  5370. status: statusR,
  5371. data: dataR
  5372. } = await tools_httpRequest({
  5373. url: `https://steamcommunity.com/games/${gameId}`,
  5374. method: 'GET',
  5375. headers: {
  5376. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5377. }
  5378. });
  5379. if (resultR === 'Success') {
  5380. if (dataR?.status === 200 && dataR.responseText.includes('id="publicGroupJoin"')) {
  5381. logStatus.success();
  5382. return true;
  5383. }
  5384. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5385. return false;
  5386. }
  5387. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5388. return false;
  5389. }
  5390. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5391. return false;
  5392. }
  5393. logStatus.error(`${result}:${statusText}(${status})`);
  5394. return false;
  5395. } catch (error) {
  5396. throwError(error, 'Steam.leaveOfficialGroup');
  5397. return false;
  5398. }
  5399. }
  5400. async #getOfficialGroupId(gameId) {
  5401. try {
  5402. const logStatus = scripts_echoLog({
  5403. type: 'gettingSteamOfficialGroupId',
  5404. text: gameId
  5405. });
  5406. const groupId = this.#cache.officialGroup[gameId];
  5407. if (groupId) {
  5408. logStatus.success();
  5409. return groupId;
  5410. }
  5411. const {
  5412. result,
  5413. statusText,
  5414. status,
  5415. data
  5416. } = await tools_httpRequest({
  5417. url: `https://steamcommunity.com/games/${gameId}`,
  5418. method: 'GET',
  5419. headers: {
  5420. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5421. }
  5422. });
  5423. if (result === 'Success') {
  5424. if (data?.status === 200) {
  5425. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5426. if (groupId) {
  5427. this.#setCache('officialGroup', gameId, groupId);
  5428. logStatus.success();
  5429. return groupId;
  5430. }
  5431. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5432. return false;
  5433. }
  5434. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5435. return false;
  5436. }
  5437. logStatus.error(`${result}:${statusText}(${status})`);
  5438. return false;
  5439. } catch (error) {
  5440. throwError(error, 'Steam.getGroupID');
  5441. return false;
  5442. }
  5443. }
  5444. async #addToWishlist(gameId) {
  5445. try {
  5446. if (this.#ASF) {
  5447. if (await this.#ASF.addToWishlist(gameId)) {
  5448. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5449. return true;
  5450. }
  5451. return false;
  5452. }
  5453. const logStatus = scripts_echoLog({
  5454. type: 'addingToWishlist',
  5455. text: gameId
  5456. });
  5457. const {
  5458. result,
  5459. data
  5460. } = await tools_httpRequest({
  5461. url: 'https://store.steampowered.com/api/addtowishlist',
  5462. method: 'POST',
  5463. headers: {
  5464. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5465. },
  5466. data: $.param({
  5467. sessionid: this.#auth.storeSessionID,
  5468. appid: gameId
  5469. }),
  5470. dataType: 'json'
  5471. });
  5472. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  5473. logStatus.success();
  5474. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5475. return true;
  5476. }
  5477. const {
  5478. result: resultR,
  5479. statusText: statusTextR,
  5480. status: statusR,
  5481. data: dataR
  5482. } = await tools_httpRequest({
  5483. url: `https://store.steampowered.com/app/${gameId}`,
  5484. method: 'GET'
  5485. });
  5486. if (resultR === 'Success') {
  5487. if (dataR?.status === 200) {
  5488. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  5489. logStatus.warning(i18n('changeAreaNotice'));
  5490. if (!await this.#changeArea()) {
  5491. return false;
  5492. }
  5493. return await this.#addToWishlist(gameId);
  5494. }
  5495. if (dataR.responseText.includes('class="queue_actions_ctn"') && dataR.responseText.includes('class="already_in_library"')) {
  5496. logStatus.success();
  5497. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5498. return true;
  5499. } 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"')) {
  5500. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  5501. return false;
  5502. }
  5503. logStatus.success();
  5504. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  5505. return true;
  5506. }
  5507. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5508. return false;
  5509. }
  5510. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5511. return false;
  5512. } catch (error) {
  5513. throwError(error, 'Steam.addToWishlist');
  5514. return false;
  5515. }
  5516. }
  5517. async #removeFromWishlist(gameId) {
  5518. try {
  5519. if (this.whiteList.wishlists.includes(gameId)) {
  5520. scripts_echoLog({
  5521. type: 'whiteList',
  5522. text: 'Steam.removeFromWishlist',
  5523. id: gameId
  5524. });
  5525. return true;
  5526. }
  5527. if (this.#ASF) {
  5528. return await this.#ASF.removeFromWishlist(gameId);
  5529. }
  5530. const logStatus = scripts_echoLog({
  5531. type: 'removingFromWishlist',
  5532. text: gameId
  5533. });
  5534. const {
  5535. result,
  5536. data
  5537. } = await tools_httpRequest({
  5538. url: 'https://store.steampowered.com/api/removefromwishlist',
  5539. method: 'POST',
  5540. headers: {
  5541. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5542. },
  5543. data: $.param({
  5544. sessionid: this.#auth.storeSessionID,
  5545. appid: gameId
  5546. }),
  5547. dataType: 'json'
  5548. });
  5549. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  5550. logStatus.success();
  5551. return true;
  5552. }
  5553. const {
  5554. result: resultR,
  5555. statusText: statusTextR,
  5556. status: statusR,
  5557. data: dataR
  5558. } = await tools_httpRequest({
  5559. url: `https://store.steampowered.com/app/${gameId}`,
  5560. method: 'GET'
  5561. });
  5562. if (resultR === 'Success') {
  5563. if (dataR?.status === 200) {
  5564. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  5565. logStatus.warning(i18n('changeAreaNotice'));
  5566. const result = await this.#changeArea();
  5567. if (!result || result === 'CN' || result === 'skip') {
  5568. return false;
  5569. }
  5570. return await this.#removeFromWishlist(gameId);
  5571. }
  5572. if (dataR.responseText.includes('class="queue_actions_ctn"') && (dataR.responseText.includes('ds_owned_flag ds_flag') || dataR.responseText.includes('add_to_wishlist_area'))) {
  5573. logStatus.success();
  5574. return true;
  5575. }
  5576. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  5577. return false;
  5578. }
  5579. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5580. return false;
  5581. }
  5582. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5583. return false;
  5584. } catch (error) {
  5585. throwError(error, 'Steam.removeFromWishlist');
  5586. return false;
  5587. }
  5588. }
  5589. async #toggleFollowGame(gameId, doTask) {
  5590. try {
  5591. if (!doTask && this.whiteList.follows.includes(gameId)) {
  5592. scripts_echoLog({
  5593. type: 'whiteList',
  5594. text: 'Steam.unfollowGame',
  5595. id: gameId
  5596. });
  5597. return true;
  5598. }
  5599. if (this.#ASF) {
  5600. if (await this.#ASF.toggleFollowGame(gameId, doTask)) {
  5601. if (doTask) {
  5602. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  5603. }
  5604. return true;
  5605. }
  5606. return false;
  5607. }
  5608. const logStatus = scripts_echoLog({
  5609. type: `${doTask ? '' : 'un'}followingGame`,
  5610. text: gameId
  5611. });
  5612. const requestData = {
  5613. sessionid: this.#auth.storeSessionID,
  5614. appid: gameId
  5615. };
  5616. if (!doTask) {
  5617. requestData.unfollow = '1';
  5618. }
  5619. const {
  5620. result,
  5621. data
  5622. } = await tools_httpRequest({
  5623. url: 'https://store.steampowered.com/explore/followgame/',
  5624. method: 'POST',
  5625. headers: {
  5626. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5627. },
  5628. data: $.param(requestData)
  5629. });
  5630. if (result === 'Success' && data?.status === 200 && data.responseText === 'true') {
  5631. logStatus.success();
  5632. return true;
  5633. }
  5634. const followed = await this.#isFollowedGame(gameId);
  5635. if (this.#area === 'CN' && followed === 'areaLocked') {
  5636. logStatus.warning(i18n('changeAreaNotice'));
  5637. if (!await this.#changeArea()) {
  5638. return false;
  5639. }
  5640. return await this.#toggleFollowGame(gameId, doTask);
  5641. }
  5642. if (doTask === followed) {
  5643. logStatus.success();
  5644. if (doTask) {
  5645. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  5646. }
  5647. return true;
  5648. }
  5649. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5650. return false;
  5651. } catch (error) {
  5652. throwError(error, 'Steam.toggleFollowGame');
  5653. return false;
  5654. }
  5655. }
  5656. async #isFollowedGame(gameId) {
  5657. try {
  5658. const {
  5659. result,
  5660. data
  5661. } = await tools_httpRequest({
  5662. url: `https://store.steampowered.com/app/${gameId}`,
  5663. method: 'GET'
  5664. });
  5665. if (result === 'Success') {
  5666. if (data?.status === 200) {
  5667. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  5668. return 'areaLocked';
  5669. }
  5670. if ($(data.responseText.replace(/<img.*?>/g, '')).find('.queue_control_button.queue_btn_follow>.btnv6_blue_hoverfade.btn_medium.queue_btn_active').css('display') !== 'none') {
  5671. return true;
  5672. }
  5673. return false;
  5674. }
  5675. return false;
  5676. }
  5677. return false;
  5678. } catch (error) {
  5679. throwError(error, 'Steam.isFollowedGame');
  5680. return false;
  5681. }
  5682. }
  5683. async #toggleForum(gameId, doTask = true) {
  5684. try {
  5685. if (!doTask && this.whiteList.forums.includes(gameId)) {
  5686. scripts_echoLog({
  5687. type: 'whiteList',
  5688. text: 'Steam.unsubscribeForum',
  5689. id: gameId
  5690. });
  5691. return true;
  5692. }
  5693. const forumId = await this.#getForumId(gameId);
  5694. if (!forumId) {
  5695. return false;
  5696. }
  5697. const logStatus = scripts_echoLog({
  5698. type: `${doTask ? '' : 'un'}subscribingForum`,
  5699. text: gameId
  5700. });
  5701. const [ id, feature ] = forumId.split('_');
  5702. const {
  5703. result,
  5704. statusText,
  5705. status,
  5706. data
  5707. } = await tools_httpRequest({
  5708. url: `https://steamcommunity.com/forum/${id}/General/${doTask ? '' : 'un'}subscribe/${feature || '0'}/`,
  5709. method: 'POST',
  5710. responseType: 'json',
  5711. headers: {
  5712. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5713. },
  5714. data: $.param({
  5715. sessionid: this.#auth.communitySessionID
  5716. })
  5717. });
  5718. if (result === 'Success') {
  5719. if (data?.status === 200 && (data.response?.success === 1 || data.response?.success === 29)) {
  5720. if (doTask) {
  5721. this.tasks.forums = unique([ ...this.tasks.forums, gameId ]);
  5722. }
  5723. logStatus.success();
  5724. return true;
  5725. }
  5726. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5727. return true;
  5728. }
  5729. logStatus.error(`${result}:${statusText}(${status})`);
  5730. return true;
  5731. } catch (error) {
  5732. throwError(error, 'Steam.toggleForum');
  5733. return true;
  5734. }
  5735. }
  5736. async #getForumId(gameId) {
  5737. try {
  5738. const logStatus = scripts_echoLog({
  5739. type: 'gettingForumId',
  5740. text: gameId
  5741. });
  5742. const forumId = this.#cache.forum[gameId];
  5743. if (forumId) {
  5744. logStatus.success();
  5745. return forumId;
  5746. }
  5747. const {
  5748. result,
  5749. statusText,
  5750. status,
  5751. data
  5752. } = await tools_httpRequest({
  5753. url: `https://steamcommunity.com/app/${gameId}/discussions/`,
  5754. method: 'GET'
  5755. });
  5756. if (result === 'Success') {
  5757. if (data?.status === 200) {
  5758. const forumId = data.responseText?.match(/General_([\d]+(_[\d]+)?)/)?.[1];
  5759. if (forumId) {
  5760. this.#setCache('forum', gameId, forumId);
  5761. logStatus.success();
  5762. return forumId;
  5763. }
  5764. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5765. return false;
  5766. }
  5767. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5768. return false;
  5769. }
  5770. logStatus.error(`${result}:${statusText}(${status})`);
  5771. return false;
  5772. } catch (error) {
  5773. throwError(error, 'Steam.getForumId');
  5774. return false;
  5775. }
  5776. }
  5777. async #toggleFavoriteWorkshop(id, doTask = true) {
  5778. try {
  5779. if (!doTask && this.whiteList.workshops.includes(id)) {
  5780. scripts_echoLog({
  5781. type: 'whiteList',
  5782. text: 'Steam.unfavoriteWorkshop',
  5783. id: id
  5784. });
  5785. return true;
  5786. }
  5787. const appid = await this.#getWorkshopAppId(id);
  5788. if (!appid) {
  5789. return false;
  5790. }
  5791. const logStatus = scripts_echoLog({
  5792. type: doTask ? 'favoritingWorkshop' : 'unfavoritingWorkshop',
  5793. text: id
  5794. });
  5795. const {
  5796. result,
  5797. statusText,
  5798. status,
  5799. data
  5800. } = await tools_httpRequest({
  5801. url: `https://steamcommunity.com/sharedfiles/${doTask ? '' : 'un'}favorite`,
  5802. method: 'POST',
  5803. headers: {
  5804. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5805. },
  5806. data: $.param({
  5807. id: id,
  5808. appid: appid,
  5809. sessionid: this.#auth.communitySessionID
  5810. })
  5811. });
  5812. if (result === 'Success') {
  5813. if (data?.status === 200 && !data.responseText) {
  5814. if (doTask) {
  5815. this.tasks.workshops = unique([ ...this.tasks.workshops, id ]);
  5816. }
  5817. logStatus.success();
  5818. return true;
  5819. }
  5820. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5821. return false;
  5822. }
  5823. logStatus.error(`${result}:${statusText}(${status})`);
  5824. return false;
  5825. } catch (error) {
  5826. throwError(error, 'Steam.toggleFavoriteWorkshop');
  5827. return false;
  5828. }
  5829. }
  5830. async #getWorkshopAppId(id) {
  5831. try {
  5832. const logStatus = scripts_echoLog({
  5833. type: 'gettingWorkshopAppId',
  5834. text: id
  5835. });
  5836. const appId = this.#cache.workshop[id];
  5837. if (appId) {
  5838. logStatus.success();
  5839. return appId;
  5840. }
  5841. const {
  5842. result,
  5843. statusText,
  5844. status,
  5845. data
  5846. } = await tools_httpRequest({
  5847. url: `https://steamcommunity.com/sharedfiles/filedetails/?id=${id}`,
  5848. method: 'GET'
  5849. });
  5850. if (result === 'Success') {
  5851. if (data?.status === 200) {
  5852. const appId = data.responseText.match(/<input type="hidden" name="appid" value="([\d]+?)" \/>/)?.[1];
  5853. if (appId) {
  5854. this.#setCache('workshop', id, appId);
  5855. logStatus.success();
  5856. return appId;
  5857. }
  5858. logStatus.error('Error: getWorkshopAppId failed');
  5859. return false;
  5860. }
  5861. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5862. return false;
  5863. }
  5864. logStatus.error(`${result}:${statusText}(${status})`);
  5865. return false;
  5866. } catch (error) {
  5867. throwError(error, 'Steam.getWorkshopAppId');
  5868. return false;
  5869. }
  5870. }
  5871. async #voteUpWorkshop(id) {
  5872. try {
  5873. const logStatus = scripts_echoLog({
  5874. type: 'votingUpWorkshop',
  5875. text: id
  5876. });
  5877. const {
  5878. result,
  5879. statusText,
  5880. status,
  5881. data
  5882. } = await tools_httpRequest({
  5883. url: 'https://steamcommunity.com/sharedfiles/voteup',
  5884. method: 'POST',
  5885. responseType: 'json',
  5886. headers: {
  5887. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5888. },
  5889. data: $.param({
  5890. id: id,
  5891. sessionid: this.#auth.communitySessionID
  5892. })
  5893. });
  5894. if (result === 'Success') {
  5895. if (data?.status === 200 && data.response?.success === 1) {
  5896. logStatus.success();
  5897. return true;
  5898. }
  5899. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5900. return true;
  5901. }
  5902. logStatus.error(`${result}:${statusText}(${status})`);
  5903. return true;
  5904. } catch (error) {
  5905. throwError(error, 'Steam.voteupWorkshop');
  5906. return true;
  5907. }
  5908. }
  5909. async #toggleCurator(curatorId, doTask = true) {
  5910. try {
  5911. if (!doTask && this.whiteList.curators.includes(curatorId)) {
  5912. scripts_echoLog({
  5913. type: 'whiteList',
  5914. text: 'Steam.unfollowCurator',
  5915. id: curatorId
  5916. });
  5917. return true;
  5918. }
  5919. if (this.#ASF) {
  5920. return await this.#ASF.toggleCurator(curatorId, doTask);
  5921. }
  5922. const logStatus = scripts_echoLog({
  5923. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  5924. text: curatorId
  5925. });
  5926. const {
  5927. result,
  5928. statusText,
  5929. status,
  5930. data
  5931. } = await tools_httpRequest({
  5932. url: 'https://store.steampowered.com/curators/ajaxfollow',
  5933. method: 'POST',
  5934. headers: {
  5935. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5936. },
  5937. data: $.param({
  5938. clanid: curatorId,
  5939. sessionid: this.#auth.storeSessionID,
  5940. follow: doTask
  5941. }),
  5942. dataType: 'json'
  5943. });
  5944. if (result === 'Success') {
  5945. if (data?.status === 200 && data.response?.success?.success === 1) {
  5946. logStatus.success();
  5947. return true;
  5948. }
  5949. logStatus.error(`Error:${data?.statusText}(${data?.response?.success}` || `${data?.status})`);
  5950. return false;
  5951. }
  5952. logStatus.error(`${result}:${statusText}(${status})`);
  5953. return false;
  5954. } catch (error) {
  5955. throwError(error, 'Steam.toggleCurator');
  5956. return false;
  5957. }
  5958. }
  5959. async getCuratorId(path, name) {
  5960. try {
  5961. const logStatus = scripts_echoLog({
  5962. type: 'gettingCuratorId',
  5963. text: `${path}/${name}`
  5964. });
  5965. const curatorId = this.#cache.curator[`${path}/${name}`];
  5966. if (curatorId) {
  5967. logStatus.success();
  5968. return curatorId;
  5969. }
  5970. const {
  5971. result,
  5972. statusText,
  5973. status,
  5974. data
  5975. } = await tools_httpRequest({
  5976. url: `https://store.steampowered.com/${path}/${name}`,
  5977. method: 'GET',
  5978. headers: {
  5979. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5980. }
  5981. });
  5982. if (result === 'Success') {
  5983. if (data?.status === 200) {
  5984. const curatorId = data.responseText.match(/g_pagingData.*?"clanid":([\d]+)/)?.[1];
  5985. if (curatorId) {
  5986. this.#setCache('curator', `${path}/${name}`, curatorId);
  5987. logStatus.success();
  5988. return curatorId;
  5989. }
  5990. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5991. return false;
  5992. }
  5993. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5994. return false;
  5995. }
  5996. logStatus.error(`${result}:${statusText}(${status})`);
  5997. return false;
  5998. } catch (error) {
  5999. throwError(error, 'Steam.getCuratorID');
  6000. return false;
  6001. }
  6002. }
  6003. async #toggleCuratorLike(link, doTask = true) {
  6004. try {
  6005. const [ path, name ] = link.split('/');
  6006. if (!(path && name)) {
  6007. scripts_echoLog({
  6008. text: i18n('errorLink', link)
  6009. });
  6010. return false;
  6011. }
  6012. const curatorId = await this.getCuratorId(path, name);
  6013. if (curatorId) {
  6014. return await this.#toggleCurator(curatorId, doTask);
  6015. }
  6016. return false;
  6017. } catch (error) {
  6018. throwError(error, 'Steam.toggleCuratorLike');
  6019. return false;
  6020. }
  6021. }
  6022. async #getAnnouncementParams(appId, viewId) {
  6023. try {
  6024. const logStatus = scripts_echoLog({
  6025. type: 'gettingAnnouncementParams',
  6026. text: appId,
  6027. id: viewId
  6028. });
  6029. const {
  6030. result,
  6031. statusText,
  6032. status,
  6033. data
  6034. } = await tools_httpRequest({
  6035. 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`,
  6036. method: 'GET',
  6037. responseType: 'json',
  6038. headers: {
  6039. Host: 'store.steampowered.com',
  6040. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6041. }
  6042. });
  6043. if (result === 'Success') {
  6044. if (data?.status === 200 && data?.response?.success === 1) {
  6045. const {
  6046. clanid,
  6047. gid
  6048. } = data.response.event?.announcement_body || {};
  6049. if (clanid) {
  6050. logStatus.success();
  6051. return {
  6052. clanId: clanid,
  6053. gid: gid
  6054. };
  6055. }
  6056. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6057. return {};
  6058. }
  6059. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6060. return {};
  6061. }
  6062. logStatus.error(`${result}:${statusText}(${status})`);
  6063. return {};
  6064. } catch (error) {
  6065. throwError(error, 'Steam.likeAnnouncement');
  6066. return {};
  6067. }
  6068. }
  6069. async #likeAnnouncement(id) {
  6070. try {
  6071. const [ appId, viewId ] = id.split('/');
  6072. if (!(appId && viewId)) {
  6073. scripts_echoLog({}).error(`${i18n('missParams')}(id)`);
  6074. return false;
  6075. }
  6076. const {
  6077. clanId,
  6078. gid
  6079. } = await this.#getAnnouncementParams(appId, viewId);
  6080. if (!clanId) {
  6081. return false;
  6082. }
  6083. const logStatus = scripts_echoLog({
  6084. type: 'likingAnnouncement',
  6085. text: appId,
  6086. id: viewId
  6087. });
  6088. const {
  6089. result,
  6090. statusText,
  6091. status,
  6092. data
  6093. } = await tools_httpRequest({
  6094. url: `https://store.steampowered.com/updated/ajaxrateupdate/${gid || viewId}`,
  6095. method: 'POST',
  6096. headers: {
  6097. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6098. Host: 'store.steampowered.com',
  6099. Origin: 'https://store.steampowered.com',
  6100. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6101. },
  6102. data: $.param({
  6103. sessionid: this.#auth.storeSessionID,
  6104. voteup: 1,
  6105. clanid: clanId,
  6106. ajax: 1
  6107. }),
  6108. dataType: 'json'
  6109. });
  6110. if (result === 'Success') {
  6111. if (data?.status === 200 && data.response.success === 1) {
  6112. logStatus.success();
  6113. return true;
  6114. }
  6115. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6116. return false;
  6117. }
  6118. logStatus.error(`${result}:${statusText}(${status})`);
  6119. return false;
  6120. } catch (error) {
  6121. throwError(error, 'Steam.likeAnnouncement');
  6122. return false;
  6123. }
  6124. }
  6125. async #appid2subid(id) {
  6126. try {
  6127. const logStatus = scripts_echoLog({
  6128. type: 'gettingSubid',
  6129. text: id
  6130. });
  6131. const {
  6132. result,
  6133. statusText,
  6134. status,
  6135. data
  6136. } = await tools_httpRequest({
  6137. url: `https://store.steampowered.com/app/${id}`,
  6138. method: 'GET',
  6139. headers: {
  6140. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6141. }
  6142. });
  6143. if (result === 'Success') {
  6144. if (data?.status === 200) {
  6145. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6146. logStatus.success(i18n('owned'));
  6147. return false;
  6148. }
  6149. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6150. logStatus.warning(i18n('changeAreaNotice'));
  6151. const result = await this.#changeArea();
  6152. if (!result || result === 'CN' || result === 'skip') {
  6153. return false;
  6154. }
  6155. return await this.#appid2subid(id);
  6156. }
  6157. let subid = data.responseText.match(/name="subid" value="([\d]+?)"/)?.[1];
  6158. if (subid) {
  6159. logStatus.success();
  6160. return subid;
  6161. }
  6162. subid = data.responseText.match(/AddFreeLicense\(\s*(\d+)/)?.[1];
  6163. if (subid) {
  6164. logStatus.success();
  6165. return subid;
  6166. }
  6167. logStatus.error(`Error:${i18n('noSubid')}`);
  6168. return false;
  6169. }
  6170. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6171. return false;
  6172. }
  6173. logStatus.error(`${result}:${statusText}(${status})`);
  6174. return false;
  6175. } catch (error) {
  6176. throwError(error, 'Steam.appid2subid');
  6177. return false;
  6178. }
  6179. }
  6180. async #getLicenses() {
  6181. try {
  6182. const logStatus = scripts_echoLog({
  6183. text: i18n('gettingLicenses')
  6184. });
  6185. const {
  6186. result,
  6187. statusText,
  6188. status,
  6189. data
  6190. } = await tools_httpRequest({
  6191. url: `https://store.steampowered.com/dynamicstore/userdata/?t=${new Date().getTime()}`,
  6192. method: 'GET',
  6193. responseType: 'json'
  6194. });
  6195. if (result === 'Success') {
  6196. if (data?.status === 200) {
  6197. logStatus.success();
  6198. return data.response?.rgOwnedPackages;
  6199. }
  6200. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6201. return false;
  6202. }
  6203. logStatus.error(`${result}:${statusText}(${status})`);
  6204. return false;
  6205. } catch (error) {
  6206. throwError(error, 'Steam.getLicenses');
  6207. return false;
  6208. }
  6209. }
  6210. async #addLicense(id) {
  6211. try {
  6212. if (this.#ASF) {
  6213. return await this.#ASF.addLicense(id);
  6214. }
  6215. const [ type, ids ] = id.split('-');
  6216. if (type === 'appid') {
  6217. const subid = await this.#appid2subid(ids);
  6218. if (!subid) {
  6219. return false;
  6220. }
  6221. const logStatus = scripts_echoLog({
  6222. type: 'addingFreeLicense',
  6223. text: ids
  6224. });
  6225. if (!await this.#addFreeLicense(subid, logStatus)) {
  6226. return false;
  6227. }
  6228. const {
  6229. result,
  6230. statusText,
  6231. status,
  6232. data
  6233. } = await tools_httpRequest({
  6234. url: `https://store.steampowered.com/app/${ids}`,
  6235. method: 'GET'
  6236. });
  6237. if (result === 'Success') {
  6238. if (data?.status === 200) {
  6239. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6240. logStatus.success();
  6241. return true;
  6242. }
  6243. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6244. return false;
  6245. }
  6246. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6247. return false;
  6248. }
  6249. logStatus.error(`${result}:${statusText}(${status})`);
  6250. return false;
  6251. } else if (type === 'subid') {
  6252. if (this.#area === 'CN') {
  6253. scripts_echoLog({}).success(i18n('tryChangeAreaNotice'));
  6254. await this.#changeArea();
  6255. }
  6256. const logStatusArr = {};
  6257. const idsArr = ids.split(',');
  6258. for (const subid of idsArr) {
  6259. const logStatus = scripts_echoLog({
  6260. type: 'addingFreeLicenseSubid',
  6261. text: subid
  6262. });
  6263. if (!await this.#addFreeLicense(subid, logStatus)) {
  6264. return false;
  6265. }
  6266. logStatusArr[subid] = logStatus;
  6267. }
  6268. const licenses = await this.#getLicenses();
  6269. if (!licenses) {
  6270. return false;
  6271. }
  6272. for (const subid of idsArr) {
  6273. if (licenses.includes(parseInt(subid, 10))) {
  6274. logStatusArr[subid].success();
  6275. } else {
  6276. logStatusArr[subid].error();
  6277. }
  6278. }
  6279. return true;
  6280. }
  6281. return false;
  6282. } catch (error) {
  6283. throwError(error, 'Steam.addLicense');
  6284. return false;
  6285. }
  6286. }
  6287. async #addFreeLicense(id, logStatusPre) {
  6288. try {
  6289. const logStatus = logStatusPre || scripts_echoLog({
  6290. type: 'addingFreeLicenseSubid',
  6291. text: id
  6292. });
  6293. const {
  6294. result,
  6295. statusText,
  6296. status,
  6297. data
  6298. } = await tools_httpRequest({
  6299. url: `https://store.steampowered.com/freelicense/addfreelicense/${id}`,
  6300. method: 'POST',
  6301. headers: {
  6302. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6303. Host: 'store.steampowered.com',
  6304. Origin: 'https://store.steampowered.com',
  6305. Referer: 'https://store.steampowered.com/account/licenses/'
  6306. },
  6307. data: $.param({
  6308. ajax: true,
  6309. sessionid: this.#auth.storeSessionID
  6310. }),
  6311. dataType: 'json'
  6312. });
  6313. if (result === 'Success') {
  6314. if (data?.status === 200) {
  6315. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6316. logStatus.warning(i18n('changeAreaNotice'));
  6317. const result = await this.#changeArea();
  6318. if (!result || [ 'CN', 'skip' ].includes(result)) {
  6319. return false;
  6320. }
  6321. return await this.#addFreeLicense(id);
  6322. }
  6323. logStatus.success();
  6324. return true;
  6325. }
  6326. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6327. return false;
  6328. }
  6329. logStatus.error(`${result}:${statusText}(${status})`);
  6330. return false;
  6331. } catch (error) {
  6332. throwError(error, 'Steam.addFreeLicense');
  6333. return false;
  6334. }
  6335. }
  6336. async #requestPlayTestAccess(id) {
  6337. try {
  6338. if (this.#ASF) {
  6339. return await this.#ASF.requestPlayTestAccess(id);
  6340. }
  6341. const logStatus = scripts_echoLog({
  6342. type: 'requestingPlayTestAccess',
  6343. text: id
  6344. });
  6345. const {
  6346. result,
  6347. statusText,
  6348. status,
  6349. data
  6350. } = await tools_httpRequest({
  6351. url: `https://store.steampowered.com/ajaxrequestplaytestaccess/${id}`,
  6352. method: 'POST',
  6353. headers: {
  6354. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6355. Host: 'store.steampowered.com',
  6356. Origin: 'https://store.steampowered.com',
  6357. Referer: `https://store.steampowered.com/app/${id}`
  6358. },
  6359. data: $.param({
  6360. sessionid: this.#auth.storeSessionID
  6361. }),
  6362. dataType: 'json'
  6363. });
  6364. if (result === 'Success') {
  6365. if (data?.status === 200 && data?.response?.success === 1) {
  6366. logStatus.success();
  6367. return true;
  6368. }
  6369. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6370. return false;
  6371. }
  6372. logStatus.error(`${result}:${statusText}(${status})`);
  6373. return false;
  6374. } catch (error) {
  6375. throwError(error, 'Steam.requestPlayTestAccess');
  6376. return false;
  6377. }
  6378. }
  6379. async toggle({
  6380. doTask = true,
  6381. groupLinks = [],
  6382. officialGroupLinks = [],
  6383. wishlistLinks = [],
  6384. followLinks = [],
  6385. forumLinks = [],
  6386. workshopLinks = [],
  6387. workshopVoteLinks = [],
  6388. curatorLinks = [],
  6389. curatorLikeLinks = [],
  6390. announcementLinks = [],
  6391. licenseLinks = [],
  6392. playtestLinks = []
  6393. }) {
  6394. try {
  6395. if ([ ...groupLinks, ...officialGroupLinks, ...forumLinks, ...workshopLinks, ...workshopVoteLinks ].length > 0 && !this.#communityInitialized) {
  6396. scripts_echoLog({
  6397. text: i18n('needInit')
  6398. });
  6399. return false;
  6400. }
  6401. if ([ ...wishlistLinks, ...followLinks, ...curatorLinks, ...curatorLikeLinks, ...announcementLinks, ...licenseLinks, ...playtestLinks ].length > 0 && !this.#storeInitialized) {
  6402. scripts_echoLog({
  6403. text: i18n('needInit')
  6404. });
  6405. return false;
  6406. }
  6407. const prom = [];
  6408. if (doTask && !globalOptions.doTask.steam.groups || !doTask && !globalOptions.undoTask.steam.groups) {
  6409. scripts_echoLog({
  6410. type: 'globalOptionsSkip',
  6411. text: 'steam.groups'
  6412. });
  6413. } else {
  6414. const realGroups = this.getRealParams('groups', groupLinks, doTask, link => link.match(/groups\/(.+)\/?/)?.[1]);
  6415. if (realGroups.length > 0) {
  6416. for (const group of realGroups) {
  6417. if (doTask) {
  6418. prom.push(this.#joinGroup(group));
  6419. } else {
  6420. prom.push(this.#leaveGroup(group));
  6421. }
  6422. await delay(1e3);
  6423. }
  6424. }
  6425. }
  6426. if (doTask && !globalOptions.doTask.steam.officialGroups || !doTask && !globalOptions.undoTask.steam.officialGroups) {
  6427. scripts_echoLog({
  6428. type: 'globalOptionsSkip',
  6429. text: 'steam.officialGroups'
  6430. });
  6431. } else {
  6432. const realOfficialGroups = this.getRealParams('officialGroups', officialGroupLinks, doTask, link => link.match(/games\/(.+)\/?/)?.[1]);
  6433. if (realOfficialGroups.length > 0) {
  6434. for (const officialGroup of realOfficialGroups) {
  6435. if (doTask) {
  6436. prom.push(this.#joinOfficialGroup(officialGroup));
  6437. } else {
  6438. prom.push(this.#leaveOfficialGroup(officialGroup));
  6439. }
  6440. await delay(1e3);
  6441. }
  6442. }
  6443. }
  6444. if (doTask && !globalOptions.doTask.steam.wishlists || !doTask && !globalOptions.undoTask.steam.wishlists) {
  6445. scripts_echoLog({
  6446. type: 'globalOptionsSkip',
  6447. text: 'steam.wishlists'
  6448. });
  6449. } else {
  6450. const realWishlists = this.getRealParams('wishlists', wishlistLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6451. if (realWishlists.length > 0) {
  6452. for (const game of realWishlists) {
  6453. if (doTask) {
  6454. prom.push(this.#addToWishlist(game));
  6455. } else {
  6456. prom.push(this.#removeFromWishlist(game));
  6457. }
  6458. await delay(1e3);
  6459. }
  6460. }
  6461. }
  6462. if (doTask && !globalOptions.doTask.steam.follows || !doTask && !globalOptions.undoTask.steam.follows) {
  6463. scripts_echoLog({
  6464. type: 'globalOptionsSkip',
  6465. text: 'steam.follows'
  6466. });
  6467. } else {
  6468. const realFollows = this.getRealParams('follows', followLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6469. if (realFollows.length > 0) {
  6470. for (const game of realFollows) {
  6471. prom.push(this.#toggleFollowGame(game, doTask));
  6472. await delay(1e3);
  6473. }
  6474. }
  6475. }
  6476. if (doTask && !globalOptions.doTask.steam.forums || !doTask && !globalOptions.undoTask.steam.forums) {
  6477. scripts_echoLog({
  6478. type: 'globalOptionsSkip',
  6479. text: 'steam.forums'
  6480. });
  6481. } else {
  6482. const realForums = this.getRealParams('forums', forumLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6483. if (realForums.length > 0) {
  6484. for (const forum of realForums) {
  6485. prom.push(this.#toggleForum(forum, doTask));
  6486. await delay(1e3);
  6487. }
  6488. }
  6489. }
  6490. if (doTask && !globalOptions.doTask.steam.workshops || !doTask && !globalOptions.undoTask.steam.workshops) {
  6491. scripts_echoLog({
  6492. type: 'globalOptionsSkip',
  6493. text: 'steam.workshops'
  6494. });
  6495. } else {
  6496. const realWorkshops = this.getRealParams('workshops', workshopLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  6497. if (realWorkshops.length > 0) {
  6498. for (const workshop of realWorkshops) {
  6499. prom.push(this.#toggleFavoriteWorkshop(workshop, doTask));
  6500. await delay(1e3);
  6501. }
  6502. }
  6503. }
  6504. if (doTask && !globalOptions.doTask.steam.workshopVotes) {
  6505. scripts_echoLog({
  6506. type: 'globalOptionsSkip',
  6507. text: 'steam.workshopVotes'
  6508. });
  6509. } else {
  6510. const realworkshopVotes = this.getRealParams('workshopVotes', workshopVoteLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  6511. if (doTask && realworkshopVotes.length > 0) {
  6512. for (const workshop of realworkshopVotes) {
  6513. prom.push(this.#voteUpWorkshop(workshop));
  6514. await delay(1e3);
  6515. }
  6516. }
  6517. }
  6518. if (doTask && !globalOptions.doTask.steam.curators || !doTask && !globalOptions.undoTask.steam.curators) {
  6519. scripts_echoLog({
  6520. type: 'globalOptionsSkip',
  6521. text: 'steam.curators'
  6522. });
  6523. } else {
  6524. const realCurators = this.getRealParams('curators', curatorLinks, doTask, link => link.match(/curator\/([\d]+)/)?.[1]);
  6525. const realCuratorLikes = this.getRealParams('curatorLikes', curatorLikeLinks, doTask, link => link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3).join('/'));
  6526. if (realCurators.length > 0) {
  6527. for (const curator of realCurators) {
  6528. prom.push(this.#toggleCurator(curator, doTask));
  6529. await delay(1e3);
  6530. }
  6531. }
  6532. if (realCuratorLikes.length > 0) {
  6533. for (const curatorLike of realCuratorLikes) {
  6534. prom.push(this.#toggleCuratorLike(curatorLike, doTask));
  6535. await delay(1e3);
  6536. }
  6537. }
  6538. }
  6539. if (doTask && !globalOptions.doTask.steam.announcements) {
  6540. scripts_echoLog({
  6541. type: 'globalOptionsSkip',
  6542. text: 'steam.announcements'
  6543. });
  6544. } else {
  6545. const realAnnouncements = this.getRealParams('announcements', announcementLinks, doTask, link => {
  6546. if (link.includes('store.steampowered.com')) {
  6547. return link.match(/store\.steampowered\.com\/news\/app\/([\d]+)\/view\/([\d]+)/)?.slice(1, 3).join('/');
  6548. }
  6549. return link.match(/steamcommunity\.com\/games\/([\d]+)\/announcements\/detail\/([\d]+)/)?.slice(1, 3).join('/');
  6550. });
  6551. if (doTask && realAnnouncements.length > 0) {
  6552. for (const id of realAnnouncements) {
  6553. prom.push(this.#likeAnnouncement(id));
  6554. await delay(1e3);
  6555. }
  6556. }
  6557. }
  6558. if (doTask && !globalOptions.doTask.steam.licenses) {
  6559. scripts_echoLog({
  6560. type: 'globalOptionsSkip',
  6561. text: 'steam.licenses'
  6562. });
  6563. } else if (doTask && globalOptions.doTask.steam.licenses && licenseLinks.length > 0) {
  6564. for (const ids of licenseLinks) {
  6565. const [ type, idsStr ] = ids.split('-');
  6566. const idsArr = idsStr.split(',');
  6567. for (const id of idsArr) {
  6568. prom.push(this.#addLicense(`${type}-${id}`));
  6569. await delay(1e3);
  6570. }
  6571. }
  6572. }
  6573. if (doTask && !globalOptions.doTask.steam.playtests) {
  6574. scripts_echoLog({
  6575. type: 'globalOptionsSkip',
  6576. text: 'steam.playtests'
  6577. });
  6578. } else {
  6579. const realPlaytests = this.getRealParams('playtests', playtestLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  6580. if (doTask && globalOptions.doTask.steam.playtests && realPlaytests.length > 0) {
  6581. for (const id of realPlaytests) {
  6582. prom.push(this.#requestPlayTestAccess(id));
  6583. await delay(1e3);
  6584. }
  6585. }
  6586. }
  6587. return Promise.all(prom).then(async () => {
  6588. if (this.#oldArea && this.#area !== this.#oldArea) {
  6589. scripts_echoLog({}).warning(i18n('steamFinishNotice') + this.#oldArea);
  6590. await this.#changeArea(this.#oldArea);
  6591. }
  6592. return true;
  6593. });
  6594. } catch (error) {
  6595. throwError(error, 'Steam.toggle');
  6596. return false;
  6597. }
  6598. }
  6599. #setCache(type, name, id) {
  6600. try {
  6601. this.#cache[type][name] = id;
  6602. GM_setValue('steamCache', this.#cache);
  6603. } catch (error) {
  6604. throwError(error, 'Steam.setCache');
  6605. }
  6606. }
  6607. }
  6608. const social_Steam = Steam;
  6609. class Website {
  6610. undoneTasks;
  6611. socialTasks;
  6612. giveawayId;
  6613. socialInitialized = {
  6614. discord: false,
  6615. instagram: false,
  6616. reddit: false,
  6617. twitch: false,
  6618. twitter: false,
  6619. vk: false,
  6620. youtube: false,
  6621. steamStore: false,
  6622. steamCommunity: false
  6623. };
  6624. initialized = false;
  6625. social = {};
  6626. async #bind(name, init) {
  6627. try {
  6628. return {
  6629. name: name,
  6630. result: await init
  6631. };
  6632. } catch (error) {
  6633. throwError(error, 'Website.bind');
  6634. return {
  6635. name: name,
  6636. result: false
  6637. };
  6638. }
  6639. }
  6640. async initSocial(action) {
  6641. try {
  6642. const pro = [];
  6643. const tasks = action === 'do' ? this.undoneTasks : this.socialTasks;
  6644. if (tasks.discord) {
  6645. const hasDiscord = Object.values(tasks.discord).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6646. if (hasDiscord && (!this.socialInitialized.discord || !this.social.discord)) {
  6647. this.social.discord = new social_Discord();
  6648. pro.push(this.#bind('discord', this.social.discord.init(action)));
  6649. }
  6650. }
  6651. if (tasks.instagram) {
  6652. const hasInstagram = Object.values(tasks.instagram).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6653. if (hasInstagram && (!this.socialInitialized.instagram || !this.social.instagram)) {
  6654. this.social.instagram = new social_Instagram();
  6655. pro.push(this.#bind('instagram', this.social.instagram.init()));
  6656. }
  6657. }
  6658. if (tasks.reddit) {
  6659. const hasReddit = Object.values(tasks.reddit).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6660. if (hasReddit && (!this.socialInitialized.reddit || !this.social.reddit)) {
  6661. this.social.reddit = new social_Reddit();
  6662. pro.push(this.#bind('reddit', this.social.reddit.init()));
  6663. }
  6664. }
  6665. if (tasks.twitch) {
  6666. const hasTwitch = Object.values(tasks.twitch).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6667. if (hasTwitch && (!this.socialInitialized.twitch || !this.social.twitch)) {
  6668. this.social.twitch = new social_Twitch();
  6669. pro.push(this.#bind('twitch', this.social.twitch.init()));
  6670. }
  6671. }
  6672. if (tasks.twitter) {
  6673. const hasTwitter = Object.values(tasks.twitter).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6674. if (hasTwitter && (!this.socialInitialized.twitter || !this.social.twitter)) {
  6675. this.social.twitter = new social_Twitter();
  6676. pro.push(this.#bind('twitter', this.social.twitter.init()));
  6677. }
  6678. }
  6679. if (tasks.vk) {
  6680. const hasVk = Object.values(tasks.vk).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6681. if (hasVk && (!this.socialInitialized.vk || !this.social.vk)) {
  6682. this.social.vk = new social_Vk();
  6683. pro.push(this.#bind('vk', this.social.vk.init()));
  6684. }
  6685. }
  6686. if (tasks.youtube) {
  6687. const hasYoutube = Object.values(tasks.youtube).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6688. if (hasYoutube && (!this.socialInitialized.youtube || !this.social.youtube)) {
  6689. this.social.youtube = new Youtube();
  6690. pro.push(this.#bind('youtube', this.social.youtube.init()));
  6691. }
  6692. }
  6693. if (tasks.steam) {
  6694. const steamLength = Object.values(tasks.steam).reduce((total, arr) => [ ...total, ...arr ]).length;
  6695. if (steamLength > 0) {
  6696. if (!this.social.steam) {
  6697. this.social.steam = new social_Steam();
  6698. }
  6699. 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);
  6700. if (steamLength - steamCommunityLength > 0 && !this.socialInitialized.steamStore) {
  6701. pro.push(this.#bind('steamStore', this.social.steam.init('store')));
  6702. }
  6703. if (steamCommunityLength > 0 && !this.socialInitialized.steamCommunity) {
  6704. pro.push(this.#bind('steamCommunity', this.social.steam.init('community')));
  6705. }
  6706. }
  6707. }
  6708. if (tasks.links && tasks.links.length > 0) {
  6709. this.social.visitLink = visitLink;
  6710. }
  6711. return await Promise.all(pro).then(result => {
  6712. let checked = true;
  6713. for (const data of result) {
  6714. if (data.result) {
  6715. this.socialInitialized[data.name] = data.result;
  6716. } else {
  6717. checked = false;
  6718. }
  6719. }
  6720. return checked;
  6721. });
  6722. } catch (error) {
  6723. throwError(error, 'Website.initSocial');
  6724. return false;
  6725. }
  6726. }
  6727. uniqueTasks(allTasks) {
  6728. try {
  6729. const result = {};
  6730. for (const [ social, types ] of Object.entries(allTasks)) {
  6731. result[social] = {};
  6732. for (const [ type, tasks ] of Object.entries(types)) {
  6733. result[social][type] = unique(tasks);
  6734. }
  6735. }
  6736. return result;
  6737. } catch (error) {
  6738. throwError(error, 'Website.uniqueTasks');
  6739. return allTasks;
  6740. }
  6741. }
  6742. async toggleTask(action) {
  6743. try {
  6744. if (!this.initialized && !this.init()) {
  6745. return false;
  6746. }
  6747. if (!await this.classifyTask(action)) {
  6748. return false;
  6749. }
  6750. await this.initSocial(action);
  6751. const pro = [];
  6752. const doTask = action === 'do';
  6753. const tasks = doTask ? this.undoneTasks : this.socialTasks;
  6754. if (this.socialInitialized.discord === true && this.social.discord) {
  6755. pro.push(this.social.discord.toggle({
  6756. doTask: doTask,
  6757. ...tasks.discord
  6758. }));
  6759. }
  6760. if (this.socialInitialized.instagram === true && this.social.instagram) {
  6761. pro.push(this.social.instagram.toggle({
  6762. doTask: doTask,
  6763. ...tasks.instagram
  6764. }));
  6765. }
  6766. if (this.socialInitialized.reddit === true && this.social.reddit) {
  6767. pro.push(this.social.reddit.toggle({
  6768. doTask: doTask,
  6769. ...tasks.reddit
  6770. }));
  6771. }
  6772. if (this.socialInitialized.twitch === true && this.social.twitch) {
  6773. pro.push(this.social.twitch.toggle({
  6774. doTask: doTask,
  6775. ...tasks.twitch
  6776. }));
  6777. }
  6778. if (this.socialInitialized.twitter === true && this.social.twitter) {
  6779. pro.push(this.social.twitter.toggle({
  6780. doTask: doTask,
  6781. ...tasks.twitter
  6782. }));
  6783. }
  6784. if (this.socialInitialized.vk === true && this.social.vk) {
  6785. pro.push(this.social.vk.toggle({
  6786. doTask: doTask,
  6787. ...tasks.vk
  6788. }));
  6789. }
  6790. if (this.socialInitialized.youtube === true && this.social.youtube) {
  6791. pro.push(this.social.youtube.toggle({
  6792. doTask: doTask,
  6793. ...tasks.youtube
  6794. }));
  6795. }
  6796. if (this.socialInitialized.steamCommunity === true && this.socialInitialized.steamStore === true && this.social.steam) {
  6797. pro.push(this.social.steam.toggle({
  6798. doTask: doTask,
  6799. ...tasks.steam
  6800. }));
  6801. }
  6802. if (this.social.visitLink && tasks.links && doTask) {
  6803. for (const link of tasks.links) {
  6804. pro.push(this.social.visitLink(link));
  6805. }
  6806. }
  6807. if (doTask && tasks.extra && this.extraDoTask) {
  6808. const hasExtra = Object.values(tasks.extra).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  6809. if (hasExtra) {
  6810. pro.push(this.extraDoTask(tasks.extra));
  6811. }
  6812. }
  6813. await Promise.all(pro);
  6814. scripts_echoLog({}).success(i18n('allTasksComplete'));
  6815. return true;
  6816. } catch (error) {
  6817. throwError(error, 'Website.toggleTask');
  6818. return false;
  6819. }
  6820. }
  6821. async doTask() {
  6822. try {
  6823. return await this.toggleTask('do');
  6824. } catch (error) {
  6825. throwError(error, 'Website.doTask');
  6826. return false;
  6827. }
  6828. }
  6829. async undoTask() {
  6830. try {
  6831. return await this.toggleTask('undo');
  6832. } catch (error) {
  6833. throwError(error, 'Website.undoTask');
  6834. return false;
  6835. }
  6836. }
  6837. }
  6838. const website_Website = Website;
  6839. const defaultTasksTemplate = {
  6840. steam: {
  6841. groupLinks: [],
  6842. wishlistLinks: [],
  6843. curatorLinks: [],
  6844. followLinks: []
  6845. },
  6846. vk: {
  6847. nameLinks: []
  6848. }
  6849. };
  6850. const defaultTasks = JSON.stringify(defaultTasksTemplate);
  6851. class FreeAnyWhere extends website_Website {
  6852. name = 'FreeAnyWhere';
  6853. tasks = [];
  6854. socialTasks = JSON.parse(defaultTasks);
  6855. undoneTasks = JSON.parse(defaultTasks);
  6856. buttons = [ 'doTask', 'undoTask', 'verifyTask', 'getKey' ];
  6857. static test() {
  6858. return window.location.host === 'freeanywhere.net';
  6859. }
  6860. async init() {
  6861. try {
  6862. const logStatus = scripts_echoLog({
  6863. text: i18n('initing')
  6864. });
  6865. if ($('a[href="#/login"]').length > 0) {
  6866. window.open('/#/login', '_self');
  6867. logStatus.warning(i18n('needLogin'));
  6868. return false;
  6869. }
  6870. if (window.location.href.includes('/login')) {
  6871. logStatus.warning(i18n('needLogin'));
  6872. return false;
  6873. }
  6874. if (!/^https?:\/\/freeanywhere\.net\/#\/giveaway\/[\d]+/.test(window.location.href)) {
  6875. const id = window.location.href.match(/https?:\/\/freeanywhere\.net\/.*?#\/giveaway\/([\d]+)/)?.[1];
  6876. if (!id) {
  6877. logStatus.error(i18n('getFailed', 'Id'));
  6878. return false;
  6879. }
  6880. window.location.href = `https://freeanywhere.net/#/giveaway/${id}`;
  6881. }
  6882. if (!this.#getGiveawayId()) {
  6883. return false;
  6884. }
  6885. if (!await this.#checkLeftKey()) {
  6886. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  6887. }
  6888. this.initialized = true;
  6889. logStatus.success();
  6890. return true;
  6891. } catch (error) {
  6892. throwError(error, 'Freeanywhere.init');
  6893. return false;
  6894. }
  6895. }
  6896. async classifyTask(action) {
  6897. try {
  6898. const logStatus = scripts_echoLog({
  6899. text: i18n('getTasksInfo')
  6900. });
  6901. if (action === 'undo') {
  6902. this.socialTasks = GM_getValue(`fawTasks-${this.giveawayId}`)?.tasks || JSON.parse(defaultTasks);
  6903. }
  6904. const {
  6905. result,
  6906. statusText,
  6907. status,
  6908. data
  6909. } = await tools_httpRequest({
  6910. url: `https://freeanywhere.net/api/v1/giveaway/${this.giveawayId}/?format=json`,
  6911. method: 'GET',
  6912. headers: {
  6913. authorization: `Token ${window.localStorage.getItem('token')}`,
  6914. 'x-csrftoken': external_Cookies_default().get('csrftoken')
  6915. },
  6916. responseType: 'json'
  6917. });
  6918. if (result === 'Success') {
  6919. const tasks = data?.response?.challenges;
  6920. if (tasks) {
  6921. if (action === 'verify') {
  6922. this.tasks = [];
  6923. }
  6924. for (const task of tasks) {
  6925. const type = task.challenge;
  6926. const social = task.challenge_provider;
  6927. const taskInfo = {
  6928. id: task.id,
  6929. title: task.title
  6930. };
  6931. if (action === 'verify' && !task.is_success) {
  6932. this.tasks.push(taskInfo);
  6933. continue;
  6934. }
  6935. switch (social) {
  6936. case 'steam':
  6937. taskInfo.social = 'steam';
  6938. switch (type) {
  6939. case 'WL':
  6940. if (action === 'undo') {
  6941. this.socialTasks.steam.wishlistLinks.push(task.link);
  6942. }
  6943. if (action === 'do' && !task.is_success) {
  6944. this.undoneTasks.steam.wishlistLinks.push(task.link);
  6945. }
  6946. break;
  6947.  
  6948. case 'JTG':
  6949. if (action === 'undo') {
  6950. this.socialTasks.steam.groupLinks.push(task.link);
  6951. }
  6952. if (action === 'do' && !task.is_success) {
  6953. this.undoneTasks.steam.groupLinks.push(task.link);
  6954. }
  6955. break;
  6956.  
  6957. case 'STC':
  6958. if (action === 'undo') {
  6959. this.socialTasks.steam.curatorLinks.push(task.link);
  6960. }
  6961. if (action === 'do' && !task.is_success) {
  6962. this.undoneTasks.steam.curatorLinks.push(task.link);
  6963. }
  6964. break;
  6965.  
  6966. case 'GF':
  6967. if (action === 'undo') {
  6968. this.socialTasks.steam.followLinks.push(task.link);
  6969. }
  6970. if (action === 'do' && !task.is_success) {
  6971. this.undoneTasks.steam.followLinks.push(task.link);
  6972. }
  6973. break;
  6974. }
  6975. break;
  6976.  
  6977. case 'vk-oauth2':
  6978. if (action === 'undo') {
  6979. this.socialTasks.vk.nameLinks.push(task.link);
  6980. }
  6981. if (action === 'do' && !task.is_success) {
  6982. this.undoneTasks.vk.nameLinks.push(task.link);
  6983. }
  6984. break;
  6985.  
  6986. case 'website':
  6987. break;
  6988.  
  6989. default:
  6990. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${social}`);
  6991. break;
  6992. }
  6993. }
  6994. logStatus.success();
  6995. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  6996. this.socialTasks = this.uniqueTasks(this.socialTasks);
  6997. if (window.DEBUG) {
  6998. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  6999. }
  7000. GM_setValue(`fawTasks-${this.giveawayId}`, {
  7001. tasks: this.socialTasks,
  7002. time: new Date().getTime()
  7003. });
  7004. return true;
  7005. }
  7006. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7007. return false;
  7008. }
  7009. logStatus.error(`${result}:${statusText}(${status})`);
  7010. return false;
  7011. } catch (error) {
  7012. throwError(error, 'Freeanywhere.classifyTask');
  7013. return false;
  7014. }
  7015. }
  7016. async verifyTask() {
  7017. try {
  7018. if (!this.initialized && !this.init()) {
  7019. return false;
  7020. }
  7021. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  7022. return false;
  7023. }
  7024. const pro = [];
  7025. for (const task of this.tasks) {
  7026. pro.push(this.#verify(task));
  7027. await delay(1e3);
  7028. }
  7029. await Promise.all(pro);
  7030. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7031. return !!await this.getKey(true);
  7032. } catch (error) {
  7033. throwError(error, 'Freeanywhere.verifyTask');
  7034. return false;
  7035. }
  7036. }
  7037. async getKey(initialized) {
  7038. try {
  7039. if (!initialized && !this.initialized && !this.init()) {
  7040. return false;
  7041. }
  7042. const logStatus = scripts_echoLog({
  7043. text: i18n('gettingKey')
  7044. });
  7045. const {
  7046. result,
  7047. statusText,
  7048. status,
  7049. data
  7050. } = await tools_httpRequest({
  7051. url: `https://freeanywhere.net/api/v1/giveaway/${this.giveawayId}/reward/?format=json`,
  7052. method: 'GET',
  7053. dataType: 'json',
  7054. headers: {
  7055. authorization: `Token ${window.localStorage.getItem('token')}`
  7056. }
  7057. });
  7058. if (result === 'Success') {
  7059. if (data?.response?.reward) {
  7060. logStatus.success();
  7061. scripts_echoLog({}).success(data.response.reward);
  7062. return data.response.reward;
  7063. }
  7064. if (data?.response?.completed === false) {
  7065. logStatus.error(i18n('tasksNotCompleted'));
  7066. return false;
  7067. }
  7068. if (data?.response?.completed === true) {
  7069. await this.#checkLeftKey();
  7070. }
  7071. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7072. return false;
  7073. }
  7074. logStatus.error(`${result}:${statusText}(${status})`);
  7075. return false;
  7076. } catch (error) {
  7077. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7078. return false;
  7079. }
  7080. }
  7081. #getGiveawayId() {
  7082. try {
  7083. const giveawayId = window.location.href.match(/\/giveaway\/([\d]+)/)?.[1];
  7084. if (giveawayId) {
  7085. this.giveawayId = giveawayId;
  7086. return true;
  7087. }
  7088. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  7089. return false;
  7090. } catch (error) {
  7091. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7092. return false;
  7093. }
  7094. }
  7095. async #verify(task) {
  7096. try {
  7097. const logStatus = scripts_echoLog({
  7098. html: `<li>${i18n('verifyingTask')}${task.title.trim()}...<font></font></li>`
  7099. });
  7100. const {
  7101. result,
  7102. statusText,
  7103. status,
  7104. data
  7105. } = await tools_httpRequest({
  7106. url: `https://freeanywhere.net/api/v1/giveaway/${this.giveawayId}/challenge-status/${task.id}/?format=json`,
  7107. method: 'GET',
  7108. dataType: 'json',
  7109. headers: {
  7110. authorization: `Token ${window.localStorage.getItem('token')}`,
  7111. 'x-csrftoken': external_Cookies_default().get('csrftoken')
  7112. }
  7113. });
  7114. if (result === 'Success') {
  7115. if (data?.response?.status) {
  7116. logStatus.success();
  7117. return true;
  7118. }
  7119. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7120. return false;
  7121. }
  7122. logStatus.error(`${result}:${statusText}(${status})`);
  7123. return false;
  7124. } catch (error) {
  7125. throwError(error, 'Freeanywhere.verify');
  7126. return false;
  7127. }
  7128. }
  7129. async #checkLeftKey() {
  7130. try {
  7131. if (!globalOptions.other.checkLeftKey) {
  7132. return true;
  7133. }
  7134. const {
  7135. data
  7136. } = await tools_httpRequest({
  7137. url: 'https://freeanywhere.net/api/v1/widget/?format=json',
  7138. method: 'GET',
  7139. dataType: 'json',
  7140. headers: {
  7141. authorization: `Token ${window.localStorage.getItem('token')}`
  7142. }
  7143. });
  7144. if (data?.response?.giveaways.find(giveaway => `${giveaway?.id}` === this.giveawayId)) {
  7145. return true;
  7146. }
  7147. await external_Swal_default().fire({
  7148. icon: 'warning',
  7149. title: i18n('notice'),
  7150. text: i18n('noKeysLeft'),
  7151. confirmButtonText: i18n('confirm'),
  7152. cancelButtonText: i18n('cancel'),
  7153. showCancelButton: true
  7154. }).then(({
  7155. value
  7156. }) => {
  7157. if (value) {
  7158. window.close();
  7159. }
  7160. });
  7161. return true;
  7162. } catch (error) {
  7163. throwError(error, 'Giveawaysu.checkLeftKey');
  7164. return false;
  7165. }
  7166. }
  7167. }
  7168. const Freeanywhere = FreeAnyWhere;
  7169. const Giveawaysu_defaultTasks = {
  7170. steam: {
  7171. groupLinks: [],
  7172. wishlistLinks: [],
  7173. curatorLinks: [],
  7174. curatorLikeLinks: [],
  7175. followLinks: [],
  7176. forumLinks: [],
  7177. announcementLinks: [],
  7178. workshopVoteLinks: [],
  7179. playtestLinks: []
  7180. },
  7181. discord: {
  7182. serverLinks: []
  7183. },
  7184. instagram: {
  7185. userLinks: []
  7186. },
  7187. vk: {
  7188. nameLinks: []
  7189. },
  7190. twitch: {
  7191. channelLinks: []
  7192. },
  7193. reddit: {
  7194. redditLinks: []
  7195. },
  7196. youtube: {
  7197. channelLinks: [],
  7198. likeLinks: []
  7199. },
  7200. twitter: {
  7201. userLinks: [],
  7202. retweetLinks: []
  7203. }
  7204. };
  7205. class GiveawaySu extends website_Website {
  7206. name = 'GiveawaySu';
  7207. socialTasks = Giveawaysu_defaultTasks;
  7208. undoneTasks = Giveawaysu_defaultTasks;
  7209. buttons = [ 'doTask', 'undoTask' ];
  7210. static test() {
  7211. return /^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(window.location.href);
  7212. }
  7213. async after() {
  7214. try {
  7215. if (!this.#checkLogin()) {
  7216. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7217. }
  7218. if (!await this.#checkLeftKey()) {
  7219. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7220. }
  7221. scripts_echoLog({}).warning(i18n('gsNotice'));
  7222. } catch (error) {
  7223. throwError(error, 'Giveawaysu.after');
  7224. }
  7225. }
  7226. init() {
  7227. try {
  7228. const logStatus = scripts_echoLog({
  7229. text: i18n('initing')
  7230. });
  7231. if ($('a.steam-login').length > 0) {
  7232. window.open('/steam/redirect', '_self');
  7233. logStatus.warning(i18n('needLogin'));
  7234. return false;
  7235. }
  7236. if (!this.#getGiveawayId()) {
  7237. return false;
  7238. }
  7239. this.initialized = true;
  7240. logStatus.success();
  7241. return true;
  7242. } catch (error) {
  7243. throwError(error, 'Giveawaysu.init');
  7244. return false;
  7245. }
  7246. }
  7247. async classifyTask(action) {
  7248. try {
  7249. const logStatus = scripts_echoLog({
  7250. text: i18n('getTasksInfo')
  7251. });
  7252. if (action === 'undo') {
  7253. this.socialTasks = GM_getValue(`gasTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  7254. return true;
  7255. }
  7256. const pro = [];
  7257. const tasks = $('#actions tr');
  7258. if ($('div.bind-discord').is(':visible')) {
  7259. $('div.bind-discord a')[0].click();
  7260. }
  7261. if ($('div.bind-twitch').is(':visible')) {
  7262. $('div.bind-twitch a')[0].click();
  7263. }
  7264. for (const task of tasks) {
  7265. pro.push(new Promise(resolve => {
  7266. const td = $(task).find('td:not(".hidden")');
  7267. const colorfulTask = td.eq(1).find('a:not([data-trigger="link"])');
  7268. const colorlessTask = td.eq(2).find('a:not([data-trigger="link"])');
  7269. const taskDes = colorfulTask.length > 0 ? colorfulTask : colorlessTask;
  7270. const taskIcon = td.eq(0).find('i').attr('class') || '';
  7271. const taskName = taskDes.text().trim();
  7272. if (taskIcon.includes('ban') || /disable adblock/gi.test(taskName)) {
  7273. return resolve(true);
  7274. }
  7275. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  7276. if (!taskLink) {
  7277. return resolve(false);
  7278. }
  7279. if (taskIcon.includes('steam') && /join/gi.test(taskName)) {
  7280. this.undoneTasks.steam.groupLinks.push(taskLink);
  7281. } else if (/like.*announcement/gi.test(taskName)) {
  7282. this.undoneTasks.steam.announcementLinks.push(taskLink);
  7283. } else if (/(follow|subscribe).*curator/gim.test(taskName) && /^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  7284. this.undoneTasks.steam.curatorLinks.push(taskLink);
  7285. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  7286. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  7287. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  7288. this.undoneTasks.steam.forumLinks.push(taskLink);
  7289. } else if (taskIcon.includes('thumbs-up') && /^https?:\/\/steamcommunity\.com\/sharedfiles\/filedetails\/\?id=[\d]+/.test(taskLink)) {
  7290. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7291. } else if (taskIcon.includes('plus') && /request.*playtest/gim.test(taskName)) {
  7292. this.undoneTasks.steam.playtestLinks.push(taskLink);
  7293. } else if (taskIcon.includes('discord') || /join.*discord/gim.test(taskName)) {
  7294. this.undoneTasks.discord.serverLinks.push(taskLink);
  7295. } else if (taskIcon.includes('instagram') || /follow.*instagram/gim.test(taskName)) {
  7296. this.undoneTasks.instagram.userLinks.push(taskLink);
  7297. } else if (taskIcon.includes('twitch') || /follow.*twitch.*channel/gim.test(taskName)) {
  7298. this.undoneTasks.twitch.channelLinks.push(taskLink);
  7299. } else if (taskIcon.includes('reddit') || /subscribe.*subreddit/gim.test(taskName) || /follow.*reddit/gim.test(taskName)) {
  7300. this.undoneTasks.reddit.redditLinks.push(taskLink);
  7301. } else if (/watch.*art/gim.test(taskName)) {
  7302. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7303. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  7304. this.undoneTasks.youtube.channelLinks.push(taskLink);
  7305. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  7306. this.undoneTasks.youtube.likeLinks.push(taskLink);
  7307. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  7308. this.undoneTasks.vk.nameLinks.push(taskLink);
  7309. } else {
  7310. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  7311. if (/wishlist.*game|add.*wishlist/gim.test(taskName)) {
  7312. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  7313. }
  7314. if (/follow.*button/gim.test(taskName)) {
  7315. this.undoneTasks.steam.followLinks.push(taskLink);
  7316. }
  7317. }
  7318. }
  7319. resolve(true);
  7320. }).catch(error => {
  7321. throwError(error, 'Giveawaysu.classifyTask->getRedirectLink');
  7322. return false;
  7323. });
  7324. }));
  7325. }
  7326. await Promise.all(pro);
  7327. logStatus.success();
  7328. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7329. this.socialTasks = this.undoneTasks;
  7330. if (window.DEBUG) {
  7331. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7332. }
  7333. GM_setValue(`gasTasks-${this.giveawayId}`, {
  7334. tasks: this.socialTasks,
  7335. time: new Date().getTime()
  7336. });
  7337. return true;
  7338. } catch (error) {
  7339. throwError(error, 'Giveawaysu.classifyTask');
  7340. return false;
  7341. }
  7342. }
  7343. #checkLogin() {
  7344. try {
  7345. if (!globalOptions.other.checkLogin) {
  7346. return true;
  7347. }
  7348. if ($('a.steam-login').length > 0) {
  7349. window.open('/steam/redirect', '_self');
  7350. }
  7351. return true;
  7352. } catch (error) {
  7353. throwError(error, 'Giveawaysu.checkLogin');
  7354. return false;
  7355. }
  7356. }
  7357. async #checkLeftKey() {
  7358. try {
  7359. if (!globalOptions.other.checkLeftKey) {
  7360. return true;
  7361. }
  7362. if ($('.giveaway-ended').length > 0 && $('.giveaway-key').length === 0) {
  7363. await external_Swal_default().fire({
  7364. icon: 'warning',
  7365. title: i18n('notice'),
  7366. text: i18n('noKeysLeft'),
  7367. confirmButtonText: i18n('confirm'),
  7368. cancelButtonText: i18n('cancel'),
  7369. showCancelButton: true
  7370. }).then(({
  7371. value
  7372. }) => {
  7373. if (value) {
  7374. window.close();
  7375. }
  7376. });
  7377. }
  7378. return true;
  7379. } catch (error) {
  7380. throwError(error, 'Giveawaysu.checkLeftKey');
  7381. return false;
  7382. }
  7383. }
  7384. #getGiveawayId() {
  7385. try {
  7386. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  7387. if (giveawayId) {
  7388. this.giveawayId = giveawayId;
  7389. return true;
  7390. }
  7391. scripts_echoLog({
  7392. text: i18n('getFailed', 'GiveawayId')
  7393. });
  7394. return false;
  7395. } catch (error) {
  7396. throwError(error, 'Giveawaysu.getGiveawayId');
  7397. return false;
  7398. }
  7399. }
  7400. }
  7401. class Indiedb {
  7402. name = 'Indiedb';
  7403. buttons = [ 'doTask' ];
  7404. static test() {
  7405. return window.location.host === 'www.indiedb.com';
  7406. }
  7407. async after() {
  7408. try {
  7409. if (!this.#checkLogin()) {
  7410. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7411. }
  7412. if (!await this.#checkLeftKey()) {
  7413. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7414. }
  7415. } catch (error) {
  7416. throwError(error, 'Indiedb.after');
  7417. }
  7418. }
  7419. async doTask() {
  7420. try {
  7421. if (!await this.#join()) {
  7422. return false;
  7423. }
  7424. return await this.#do();
  7425. } catch (error) {
  7426. throwError(error, 'Indiedb.doTask');
  7427. return false;
  7428. }
  7429. }
  7430. async #join() {
  7431. try {
  7432. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7433. scripts_echoLog({}).error(i18n('needLogin'));
  7434. return false;
  7435. }
  7436. const currentoption = $('a.buttonenter.buttongiveaway');
  7437. if (/join giveaway/gim.test(currentoption.text())) {
  7438. const logStatus = scripts_echoLog({
  7439. text: `${i18n('joiningGiveaway')}...`
  7440. });
  7441. const {
  7442. result,
  7443. statusText,
  7444. status,
  7445. data
  7446. } = await tools_httpRequest({
  7447. url: currentoption.attr('href'),
  7448. method: 'POST',
  7449. data: 'ajax=t',
  7450. dataType: 'json',
  7451. headers: {
  7452. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  7453. Accept: 'application/json, text/javascript, */*; q=0.01',
  7454. Origin: window.location.origin,
  7455. referer: window.location.href
  7456. }
  7457. });
  7458. if (result === 'Success') {
  7459. if (data?.status === 200) {
  7460. if (data.response?.success) {
  7461. currentoption.addClass('buttonentered').text('Success - Giveaway joined');
  7462. $('#giveawaysjoined').slideDown();
  7463. $('#giveawaysrecommend').slideDown();
  7464. logStatus.success(`Success${data.response?.text ? `:${data.response?.text}` : ''}`);
  7465. return true;
  7466. }
  7467. logStatus.error(`Error${data.response?.text ? `:${data.response?.text}` : ''}`);
  7468. return false;
  7469. }
  7470. if (await this.#join2()) {
  7471. logStatus.success('Success');
  7472. return true;
  7473. }
  7474. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7475. return false;
  7476. }
  7477. logStatus.error(`${result}:${statusText}(${status})`);
  7478. return false;
  7479. } else if (/success/gim.test($('a.buttonenter.buttongiveaway').text())) {
  7480. return true;
  7481. }
  7482. scripts_echoLog({}).warning(i18n('needJoinGiveaway'));
  7483. return false;
  7484. } catch (error) {
  7485. throwError(error, 'Indiedb.join');
  7486. return false;
  7487. }
  7488. }
  7489. async #join2() {
  7490. try {
  7491. return await new Promise(resolve => {
  7492. const targetNode = document.getElementById('giveawaysjoined');
  7493. const config = {
  7494. attributes: true
  7495. };
  7496. const observer = new MutationObserver(() => {
  7497. if ($('#giveawaysjoined').is(':visible')) {
  7498. resolve(true);
  7499. observer.disconnect();
  7500. }
  7501. });
  7502. observer.observe(targetNode, config);
  7503. $('a.buttonenter.buttongiveaway')[0]?.click();
  7504. setTimeout(() => {
  7505. resolve(false);
  7506. observer.disconnect();
  7507. }, 3e4);
  7508. });
  7509. } catch (error) {
  7510. throwError(error, 'Indiedb.join2');
  7511. return false;
  7512. }
  7513. }
  7514. async #do() {
  7515. try {
  7516. const id = $('script').map((index, script) => {
  7517. if (/\$\(document\)/gim.test(script.innerHTML)) {
  7518. return [ script.innerHTML.match(/"\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0], script.innerHTML.match(/"\/newsletter\/ajax\/subscribeprofile\/optin\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0] ];
  7519. }
  7520. return null;
  7521. });
  7522. if (id.length === 2) {
  7523. const pro = [];
  7524. const tasks = $('#giveawaysjoined a[class*=promo]');
  7525. for (const task of tasks) {
  7526. const promo = $(task);
  7527. if (!promo.hasClass('buttonentered')) {
  7528. const status = scripts_echoLog({
  7529. text: `${i18n('doing')}:${promo.parents('p').text()}...`
  7530. });
  7531. if (/facebookpromo|twitterpromo|visitpromo/gim.test(task.className)) {
  7532. let text = '';
  7533. if (promo.hasClass('facebookpromo')) {
  7534. text = 'facebookpromo';
  7535. } else if (promo.hasClass('twitterpromo')) {
  7536. text = 'twitterpromo';
  7537. } else {
  7538. text = 'visitpromo';
  7539. }
  7540. pro.push(new Promise(resolve => {
  7541. $.ajax({
  7542. type: 'POST',
  7543. url: urlPath(`/giveaways/ajax/${text}/${id[0]}`),
  7544. timeout: 6e4,
  7545. dataType: 'json',
  7546. data: {
  7547. ajax: 't'
  7548. },
  7549. error(response, error, exception) {
  7550. if (window.DEBUG) {
  7551. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7552. response: response,
  7553. error: error,
  7554. exception: exception
  7555. });
  7556. }
  7557. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7558. resolve(true);
  7559. },
  7560. success(response) {
  7561. if (response.success) {
  7562. status.success(`Success:${response.text}`);
  7563. promo.addClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7564. resolve(true);
  7565. } else {
  7566. status.error(`Error:${response.text}`);
  7567. resolve(true);
  7568. }
  7569. }
  7570. });
  7571. }));
  7572. } else if (promo.hasClass('emailoptinpromo')) {
  7573. pro.push(new Promise(resolve => {
  7574. $.ajax({
  7575. type: 'POST',
  7576. url: urlPath(`/newsletter/ajax/subscribeprofile/optin/${id[1]}`),
  7577. timeout: 6e4,
  7578. dataType: 'json',
  7579. data: {
  7580. ajax: 't',
  7581. emailsystoggle: 4
  7582. },
  7583. error(response, error, exception) {
  7584. if (window.DEBUG) {
  7585. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7586. response: response,
  7587. error: error,
  7588. exception: exception
  7589. });
  7590. }
  7591. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7592. resolve(true);
  7593. },
  7594. success(response) {
  7595. if (response.success) {
  7596. status.success(`Success:${response.text}`);
  7597. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7598. resolve(true);
  7599. } else {
  7600. status.error(`Error:${response.text}`);
  7601. resolve(true);
  7602. }
  7603. }
  7604. });
  7605. }));
  7606. } else if (promo.hasClass('watchingpromo')) {
  7607. pro.push(new Promise(resolve => {
  7608. const data = getUrlQuery(promo.attr('href'));
  7609. data.ajax = 't';
  7610. $.ajax({
  7611. type: 'POST',
  7612. url: urlPath(promo.attr('href')?.split(/[?#]/)[0]),
  7613. timeout: 6e4,
  7614. dataType: 'json',
  7615. data: data,
  7616. error(response, error, exception) {
  7617. if (window.DEBUG) {
  7618. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7619. response: response,
  7620. error: error,
  7621. exception: exception
  7622. });
  7623. }
  7624. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7625. resolve(true);
  7626. },
  7627. success(response) {
  7628. if (response.success) {
  7629. status.success(`Success:${response.text}`);
  7630. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7631. resolve(true);
  7632. } else {
  7633. status.error(`Error:${response.text}`);
  7634. resolve(true);
  7635. }
  7636. }
  7637. });
  7638. }));
  7639. } else if (!/the-challenge-of-adblock/gim.test(promo.attr('href'))) {
  7640. pro.push(new Promise(resolve => {
  7641. $.ajax({
  7642. type: 'POST',
  7643. url: urlPath(promo.attr('href')),
  7644. timeout: 6e4,
  7645. dataType: 'json',
  7646. data: {
  7647. ajax: 't'
  7648. },
  7649. error(response, error, exception) {
  7650. if (window.DEBUG) {
  7651. console.log('%cAuto-Task[Debug]:', 'color:red', {
  7652. response: response,
  7653. error: error,
  7654. exception: exception
  7655. });
  7656. }
  7657. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  7658. resolve(true);
  7659. },
  7660. success(response) {
  7661. if (response.success) {
  7662. status.success(`Success:${response.text}`);
  7663. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  7664. resolve(true);
  7665. } else {
  7666. status.error(`Error:${response.text}`);
  7667. resolve(true);
  7668. }
  7669. }
  7670. });
  7671. }));
  7672. } else {
  7673. status.error(`Error:${i18n('unKnownTaskType')}`);
  7674. }
  7675. }
  7676. }
  7677. await Promise.all(pro);
  7678. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7679. return true;
  7680. }
  7681. scripts_echoLog({}).error(i18n('getFailed', 'TaskId'));
  7682. return false;
  7683. } catch (error) {
  7684. throwError(error, 'Indiedb.classifyTask');
  7685. return false;
  7686. }
  7687. }
  7688. #checkLogin() {
  7689. try {
  7690. if (!globalOptions.other.checkLogin) {
  7691. return true;
  7692. }
  7693. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7694. window.open('/members/login', '_self');
  7695. }
  7696. return true;
  7697. } catch (error) {
  7698. throwError(error, 'Indiedb.checkLogin');
  7699. return false;
  7700. }
  7701. }
  7702. async #checkLeftKey() {
  7703. try {
  7704. if (!globalOptions.other.checkLeftKey) {
  7705. return true;
  7706. }
  7707. if ($('a.buttonenter:contains("next time"), a.buttonenter:contains("Giveaway is closed")').length > 0) {
  7708. await external_Swal_default().fire({
  7709. icon: 'warning',
  7710. title: i18n('notice'),
  7711. text: i18n('giveawayEnded'),
  7712. confirmButtonText: i18n('confirm'),
  7713. cancelButtonText: i18n('cancel'),
  7714. showCancelButton: true
  7715. }).then(({
  7716. value
  7717. }) => {
  7718. if (value) {
  7719. window.close();
  7720. }
  7721. });
  7722. }
  7723. return true;
  7724. } catch (error) {
  7725. throwError(error, 'Indiedb.checkLeftKey');
  7726. return false;
  7727. }
  7728. }
  7729. }
  7730. const website_Indiedb = Indiedb;
  7731. const Keyhub_defaultTasksTemplate = {
  7732. steam: {
  7733. groupLinks: [],
  7734. officialGroupLinks: [],
  7735. wishlistLinks: [],
  7736. curatorLinks: []
  7737. },
  7738. discord: {
  7739. serverLinks: []
  7740. },
  7741. extra: {
  7742. videoTasks: []
  7743. },
  7744. links: []
  7745. };
  7746. const Keyhub_defaultTasks = JSON.stringify(Keyhub_defaultTasksTemplate);
  7747. class Keyhub extends website_Website {
  7748. name = 'Keyhub';
  7749. socialTasks = JSON.parse(Keyhub_defaultTasks);
  7750. undoneTasks = JSON.parse(Keyhub_defaultTasks);
  7751. buttons = [ 'doTask', 'undoTask' ];
  7752. static test() {
  7753. return window.location.host === 'key-hub.eu';
  7754. }
  7755. async after() {
  7756. try {
  7757. if (!this.#checkLogin()) {
  7758. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7759. }
  7760. if (!await this.#checkLeftKey()) {
  7761. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7762. }
  7763. $('.NSFW').hide();
  7764. } catch (error) {
  7765. throwError(error, 'Keyhub.after');
  7766. }
  7767. }
  7768. init() {
  7769. try {
  7770. const logStatus = scripts_echoLog({
  7771. text: i18n('initing')
  7772. });
  7773. if ($('a[href*="/connect/steam"]').length > 0) {
  7774. window.open('/connect/steam', '_self');
  7775. logStatus.warning(i18n('needLogin'));
  7776. return false;
  7777. }
  7778. if (!this.#getGiveawayId()) {
  7779. return false;
  7780. }
  7781. $('#VPNoverlay').hide();
  7782. $('#mainArticleSection').show();
  7783. this.initialized = true;
  7784. logStatus.success();
  7785. return true;
  7786. } catch (error) {
  7787. throwError(error, 'Keyhub.init');
  7788. return false;
  7789. }
  7790. }
  7791. async classifyTask(action) {
  7792. try {
  7793. const logStatus = scripts_echoLog({
  7794. text: i18n('getTasksInfo')
  7795. });
  7796. if (action === 'undo') {
  7797. this.socialTasks = GM_getValue(`khTasks-${this.giveawayId}`)?.tasks || JSON.parse(Keyhub_defaultTasks);
  7798. }
  7799. const tasks = $('.task:not(".googleads")').filter((index, element) => action === 'do' ? $(element).find('i.fa-check-circle:visible').length === 0 : true).find('a');
  7800. for (const task of tasks) {
  7801. let link = $(task).attr('href');
  7802. const taskDes = $(task).text().trim();
  7803. if (!link) {
  7804. continue;
  7805. }
  7806. if (/\/away\?data=/.test(link) || /steamcommunity\.com\/gid\//.test(link)) {
  7807. link = await getRedirectLink(link) || link;
  7808. }
  7809. if (/https?:\/\/key-hub\.eu\/connect\/discord/.test(link)) {
  7810. GM_openInTab(link, {
  7811. active: true
  7812. });
  7813. } else if (/steamcommunity\.com\/groups\//.test(link)) {
  7814. if (action === 'undo') {
  7815. this.socialTasks.steam.groupLinks.push(link);
  7816. }
  7817. if (action === 'do') {
  7818. this.undoneTasks.steam.groupLinks.push(link);
  7819. }
  7820. } else if (/steamcommunity\.com\/games\/[\d]+/.test(link)) {
  7821. if (action === 'undo') {
  7822. this.socialTasks.steam.officialGroupLinks.push(link);
  7823. }
  7824. if (action === 'do') {
  7825. this.undoneTasks.steam.officialGroupLinks.push(link);
  7826. }
  7827. } else if (/store\.steampowered\.com\/app\//.test(link) && /wishlist/gim.test(taskDes)) {
  7828. if (action === 'undo') {
  7829. this.socialTasks.steam.wishlistLinks.push(link);
  7830. }
  7831. if (action === 'do') {
  7832. this.undoneTasks.steam.wishlistLinks.push(link);
  7833. }
  7834. } else if (/store\.steampowered\.com\/curator\//.test(link)) {
  7835. if (action === 'undo') {
  7836. this.socialTasks.steam.curatorLinks.push(link);
  7837. }
  7838. if (action === 'do') {
  7839. this.undoneTasks.steam.curatorLinks.push(link);
  7840. }
  7841. } else if (/^https?:\/\/discord\.com\/invite\//.test(link)) {
  7842. if (action === 'undo') {
  7843. this.socialTasks.discord.serverLinks.push(link);
  7844. }
  7845. if (action === 'do') {
  7846. this.undoneTasks.discord.serverLinks.push(link);
  7847. }
  7848. } else if (/^javascript:videoTask.+/.test(link)) {
  7849. if (action === 'do') {
  7850. const taskData = link.match(/javascript:videoTask\('.+?','(.+?)'/)?.[1];
  7851. if (taskData) {
  7852. this.undoneTasks.extra.videoTasks.push(taskData);
  7853. }
  7854. }
  7855. } 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 {
  7856. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  7857. }
  7858. }
  7859. logStatus.success();
  7860. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7861. this.socialTasks = this.uniqueTasks(this.socialTasks);
  7862. if (window.DEBUG) {
  7863. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7864. }
  7865. GM_setValue(`khTasks-${this.giveawayId}`, {
  7866. tasks: this.socialTasks,
  7867. time: new Date().getTime()
  7868. });
  7869. return true;
  7870. } catch (error) {
  7871. throwError(error, 'Keyhub.classifyTask');
  7872. return false;
  7873. }
  7874. }
  7875. async #doScriptTask(data) {
  7876. try {
  7877. const logStatus = scripts_echoLog({
  7878. text: i18n('doingKeyhubTask')
  7879. });
  7880. const {
  7881. result,
  7882. statusText,
  7883. status,
  7884. data: response
  7885. } = await tools_httpRequest({
  7886. url: `/away?data=${data}`,
  7887. method: 'GET',
  7888. headers: {
  7889. origin: 'https://key-hub.eu',
  7890. referer: 'https://key-hub.eu/'
  7891. }
  7892. });
  7893. if (result === 'Success') {
  7894. if (response?.status === 200) {
  7895. logStatus.success();
  7896. return true;
  7897. }
  7898. logStatus.error(`Error:${response?.statusText}(${response?.status})`);
  7899. return false;
  7900. }
  7901. logStatus.error(`${result}:${statusText}(${status})`);
  7902. return false;
  7903. } catch (error) {
  7904. throwError(error, 'Keyhub.doScriptTask');
  7905. return false;
  7906. }
  7907. }
  7908. async extraDoTask({
  7909. videoTasks
  7910. }) {
  7911. try {
  7912. const pro = [];
  7913. for (const data of videoTasks) {
  7914. pro.push(this.#doScriptTask(data));
  7915. }
  7916. return Promise.all(pro).then(() => true);
  7917. } catch (error) {
  7918. throwError(error, 'Keyhub.extraDoTask');
  7919. return false;
  7920. }
  7921. }
  7922. #getGiveawayId() {
  7923. try {
  7924. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  7925. if (giveawayId) {
  7926. this.giveawayId = giveawayId;
  7927. return true;
  7928. }
  7929. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  7930. return false;
  7931. } catch (error) {
  7932. throwError(error, 'Keyhub.getGiveawayId');
  7933. return false;
  7934. }
  7935. }
  7936. async #checkLeftKey() {
  7937. try {
  7938. if (!globalOptions.other.checkLeftKey) {
  7939. return true;
  7940. }
  7941. const leftKey = $('#keysleft').text().trim();
  7942. if (leftKey === '0') {
  7943. await external_Swal_default().fire({
  7944. icon: 'warning',
  7945. title: i18n('notice'),
  7946. text: i18n('noKeysLeft'),
  7947. confirmButtonText: i18n('confirm'),
  7948. cancelButtonText: i18n('cancel'),
  7949. showCancelButton: true
  7950. }).then(({
  7951. value
  7952. }) => {
  7953. if (value) {
  7954. window.close();
  7955. }
  7956. });
  7957. }
  7958. return true;
  7959. } catch (error) {
  7960. throwError(error, 'Keyhub.checkLeftKey');
  7961. return false;
  7962. }
  7963. }
  7964. #checkLogin() {
  7965. try {
  7966. if (!globalOptions.other.checkLogin) {
  7967. return true;
  7968. }
  7969. if ($('a[href*="/connect/steam"]').length > 0) {
  7970. window.open('/connect/steam', '_self');
  7971. }
  7972. return true;
  7973. } catch (error) {
  7974. throwError(error, 'Keyhub.checkLogin');
  7975. return false;
  7976. }
  7977. }
  7978. }
  7979. const website_Keyhub = Keyhub;
  7980. const Givekey_defaultTasksTemplate = {
  7981. steam: {
  7982. groupLinks: [],
  7983. wishlistLinks: [],
  7984. curatorLinks: [],
  7985. curatorLikeLinks: []
  7986. },
  7987. twitter: {
  7988. userLinks: []
  7989. },
  7990. vk: {
  7991. nameLinks: []
  7992. },
  7993. discord: {
  7994. serverLinks: []
  7995. }
  7996. };
  7997. const Givekey_defaultTasks = JSON.stringify(Givekey_defaultTasksTemplate);
  7998. class Givekey extends website_Website {
  7999. name = 'Givekey';
  8000. tasks = [];
  8001. socialTasks = JSON.parse(Givekey_defaultTasks);
  8002. undoneTasks = JSON.parse(Givekey_defaultTasks);
  8003. userId;
  8004. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8005. static test() {
  8006. return window.location.host === 'givekey.ru';
  8007. }
  8008. async after() {
  8009. try {
  8010. await new Promise(resolve => {
  8011. const checker = setInterval(() => {
  8012. if ($('#navbarDropdown').length > 0) {
  8013. clearInterval(checker);
  8014. resolve(true);
  8015. }
  8016. }, 500);
  8017. });
  8018. if (!await this.#checkLeftKey()) {
  8019. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8020. }
  8021. } catch (error) {
  8022. throwError(error, 'Givekey.after');
  8023. }
  8024. }
  8025. init() {
  8026. try {
  8027. const logStatus = scripts_echoLog({
  8028. text: i18n('initing')
  8029. });
  8030. if ($('a[href*="/auth/steam"]').length > 0) {
  8031. window.open('/auth/steam', '_self');
  8032. logStatus.warning(i18n('needLogin'));
  8033. return false;
  8034. }
  8035. if (!this.#getGiveawayId()) {
  8036. return false;
  8037. }
  8038. const userId = $('meta[name="user-id"]').attr('content');
  8039. if (!userId) {
  8040. logStatus.error(i18n('getFailed', i18n('userId')));
  8041. return false;
  8042. }
  8043. this.userId = userId;
  8044. this.initialized = true;
  8045. logStatus.success();
  8046. return true;
  8047. } catch (error) {
  8048. throwError(error, 'Givekey.init');
  8049. return false;
  8050. }
  8051. }
  8052. async classifyTask(action) {
  8053. try {
  8054. const logStatus = scripts_echoLog({
  8055. text: i18n('getTasksInfo')
  8056. });
  8057. if (action === 'undo') {
  8058. this.socialTasks = GM_getValue(`gkTasks-${this.giveawayId}`)?.tasks || JSON.parse(Givekey_defaultTasks);
  8059. }
  8060. const tasks = $('.card-body:has("button") .row');
  8061. for (const task of tasks) {
  8062. const taskEle = $(task);
  8063. const isSuccess = /Complete/i.test(taskEle.find('button').text().trim());
  8064. if (isSuccess && action !== 'undo') {
  8065. continue;
  8066. }
  8067. const checkButton = taskEle.find('#task_check');
  8068. const taskId = checkButton.attr('data-id');
  8069. if (taskId) {
  8070. this.tasks.push(taskId);
  8071. }
  8072. if (action === 'verify') {
  8073. continue;
  8074. }
  8075. let href = taskEle.find('a').attr('href') || null;
  8076. const text = taskEle.find('a').text().trim();
  8077. const icon = taskEle.find('i');
  8078. if (!href || !text) {
  8079. continue;
  8080. }
  8081. if (/^https?:\/\/givekey\.ru\/giveaway\/[\d]+\/execution_task/.test(href)) {
  8082. href = await getRedirectLink(href);
  8083. }
  8084. if (!href) {
  8085. continue;
  8086. }
  8087. if (/^https?:\/\/vk\.com\//.test(href)) {
  8088. this.socialTasks.vk.nameLinks.push(href);
  8089. if (action === 'do' && !isSuccess) {
  8090. this.undoneTasks.vk.nameLinks.push(href);
  8091. }
  8092. } else if (/^https?:\/\/steamcommunity\.com\/groups/.test(href)) {
  8093. this.socialTasks.steam.groupLinks.push(href);
  8094. if (action === 'do' && !isSuccess) {
  8095. this.undoneTasks.steam.groupLinks.push(href);
  8096. }
  8097. } else if (/^https?:\/\/store\.steampowered\.com\/app\//.test(href)) {
  8098. this.socialTasks.steam.wishlistLinks.push(href);
  8099. if (action === 'do' && !isSuccess) {
  8100. this.undoneTasks.steam.wishlistLinks.push(href);
  8101. }
  8102. } else if (/Subscribe/gi.test(text) && icon.hasClass('fa-steam-square')) {
  8103. if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(href)) {
  8104. this.socialTasks.steam.curatorLinks.push(href);
  8105. if (action === 'do' && !isSuccess) {
  8106. this.undoneTasks.steam.curatorLinks.push(href);
  8107. }
  8108. } else {
  8109. this.socialTasks.steam.curatorLikeLinks.push(href);
  8110. if (action === 'do' && !isSuccess) {
  8111. this.undoneTasks.steam.curatorLikeLinks.push(href);
  8112. }
  8113. }
  8114. } else if (/^https?:\/\/twitter\.com\//.test(href) && /Subscribe/gi.test(text)) {
  8115. this.socialTasks.twitter.userLinks.push(href);
  8116. if (action === 'do' && !isSuccess) {
  8117. this.undoneTasks.twitter.userLinks.push(href);
  8118. }
  8119. } else if (icon.hasClass('fa-discord') || /^https?:\/\/discord\.com\/invite\//.test(href)) {
  8120. this.socialTasks.discord.serverLinks.push(href);
  8121. if (action === 'do' && !isSuccess) {
  8122. this.undoneTasks.discord.serverLinks.push(href);
  8123. }
  8124. } else {
  8125. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${text}(${href})`);
  8126. }
  8127. }
  8128. logStatus.success();
  8129. this.tasks = unique(this.tasks);
  8130. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8131. this.socialTasks = this.uniqueTasks(this.socialTasks);
  8132. if (window.DEBUG) {
  8133. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8134. }
  8135. GM_setValue(`gkTasks-${this.giveawayId}`, {
  8136. tasks: this.socialTasks,
  8137. time: new Date().getTime()
  8138. });
  8139. return true;
  8140. } catch (error) {
  8141. throwError(error, 'Givekey.classifyTask');
  8142. return false;
  8143. }
  8144. }
  8145. async verifyTask() {
  8146. try {
  8147. if (!this.initialized && !this.init()) {
  8148. return false;
  8149. }
  8150. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  8151. return false;
  8152. }
  8153. scripts_echoLog({}).warning(i18n('giveKeyNoticeBefore'));
  8154. const taskLength = this.tasks.length;
  8155. for (let i = 0; i < taskLength; i++) {
  8156. await this.#verify(this.tasks[i]);
  8157. if (i < taskLength - 1) {
  8158. await delay(15e3);
  8159. }
  8160. }
  8161. scripts_echoLog({}).success(i18n('allTasksComplete'));
  8162. scripts_echoLog({
  8163. html: `<li><font class="warning">${i18n('giveKeyNoticeAfter')}</font></li>`
  8164. });
  8165. return true;
  8166. } catch (error) {
  8167. throwError(error, 'Givekey.verifyTask');
  8168. return false;
  8169. }
  8170. }
  8171. async #verify(task) {
  8172. try {
  8173. const logStatus = scripts_echoLog({
  8174. html: `<li>${i18n('verifyingTask')}${task}...<font></font></li>`
  8175. });
  8176. return await new Promise(resolve => {
  8177. $.ajax({
  8178. url: 'https://givekey.ru/giveaway/task',
  8179. method: 'POST',
  8180. data: `id=${task}&user_id=${this.userId}`,
  8181. dataType: 'json',
  8182. headers: {
  8183. 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  8184. },
  8185. success: data => {
  8186. if (data.btn) {
  8187. $(`button[data-id=${this.userId}]`).html(data.btn);
  8188. }
  8189. if (data.status === 'ok') {
  8190. $(`.task_check_${data.id}`).html(`<button class="btn btn-success mb-2 btn-block" disabled>${data.btn}</button>`);
  8191. logStatus.success();
  8192. resolve(true);
  8193. } else if (data.status === 'end') {
  8194. logStatus.success();
  8195. scripts_echoLog({}).success(data.key);
  8196. resolve(true);
  8197. } else {
  8198. logStatus.error(`Error:${data.msg}`);
  8199. resolve(false);
  8200. }
  8201. },
  8202. error: xhr => {
  8203. logStatus.error(`Error:${xhr.statusText}(${xhr.status})`);
  8204. resolve(false);
  8205. }
  8206. });
  8207. });
  8208. } catch (error) {
  8209. throwError(error, 'Givekey.verify');
  8210. return false;
  8211. }
  8212. }
  8213. #getGiveawayId() {
  8214. try {
  8215. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  8216. if (giveawayId) {
  8217. this.giveawayId = giveawayId;
  8218. return true;
  8219. }
  8220. scripts_echoLog({
  8221. text: i18n('getFailed', 'GiveawayId')
  8222. });
  8223. return false;
  8224. } catch (error) {
  8225. throwError(error, 'Givekey.getGiveawayId');
  8226. return false;
  8227. }
  8228. }
  8229. async #checkLeftKey() {
  8230. try {
  8231. if (!globalOptions.other.checkLeftKey) {
  8232. return true;
  8233. }
  8234. if (!$('#keys_count').text()) {
  8235. await external_Swal_default().fire({
  8236. icon: 'warning',
  8237. title: i18n('notice'),
  8238. text: i18n('noKeysLeft'),
  8239. confirmButtonText: i18n('confirm'),
  8240. cancelButtonText: i18n('cancel'),
  8241. showCancelButton: true
  8242. }).then(({
  8243. value
  8244. }) => {
  8245. if (value) {
  8246. window.close();
  8247. }
  8248. });
  8249. }
  8250. return true;
  8251. } catch (error) {
  8252. throwError(error, 'Givekey.checkLeftKey');
  8253. return false;
  8254. }
  8255. }
  8256. }
  8257. const website_Givekey = Givekey;
  8258. class GiveeClub extends GiveawaySu {
  8259. name = 'GiveeClub';
  8260. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8261. static test() {
  8262. return /^https?:\/\/givee\.club\/.*?\/event\/[\d]+/.test(window.location.href);
  8263. }
  8264. async after() {
  8265. try {
  8266. if (!this.#checkLogin()) {
  8267. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8268. }
  8269. if (!await this.#checkLeftKey()) {
  8270. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8271. }
  8272. } catch (error) {
  8273. throwError(error, 'GiveeClub.after');
  8274. }
  8275. }
  8276. init() {
  8277. try {
  8278. const logStatus = scripts_echoLog({
  8279. text: i18n('initing')
  8280. });
  8281. if (!this.#checkLogin()) {
  8282. logStatus.warning(i18n('needLogin'));
  8283. return false;
  8284. }
  8285. if (!this.#getGiveawayId()) {
  8286. return false;
  8287. }
  8288. this.initialized = true;
  8289. logStatus.success();
  8290. return true;
  8291. } catch (error) {
  8292. throwError(error, 'GiveeClub.init');
  8293. return false;
  8294. }
  8295. }
  8296. async classifyTask(action) {
  8297. try {
  8298. const logStatus = scripts_echoLog({
  8299. text: i18n('getTasksInfo')
  8300. });
  8301. if (action === 'undo') {
  8302. this.socialTasks = GM_getValue(`gcTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  8303. return true;
  8304. }
  8305. this.undoneTasks = Giveawaysu_defaultTasks;
  8306. const pro = [];
  8307. const tasks = $('.event-actions tr');
  8308. for (const task of tasks) {
  8309. pro.push(new Promise(resolve => {
  8310. const taskDes = $(task).find('.event-action-label a');
  8311. const taskIcon = $(task).find('.event-action-icon i').attr('class') || '';
  8312. const taskName = taskDes.text().trim();
  8313. const taskType = $(task).find('button[data-type]')?.attr('data-type');
  8314. const taskFinished = $(task).find('.event-action-buttons .btn-success')?.length;
  8315. if (taskIcon.includes('ban') || /AdBlock/i.test(taskName) || taskIcon.includes('envelope') || taskFinished) {
  8316. return resolve(true);
  8317. }
  8318. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  8319. if (!taskLink) {
  8320. return resolve(false);
  8321. }
  8322. if (taskType === 'steam.group.join' && /^https?:\/\/steamcommunity\.com\/groups/.test(taskLink)) {
  8323. this.undoneTasks.steam.groupLinks.push(taskLink);
  8324. } else if (/like.*announcement/gi.test(taskName)) {
  8325. this.undoneTasks.steam.announcementLinks.push(taskLink);
  8326. } else if (taskType === 'steam.game.wishlist' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8327. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  8328. } else if (taskType === 'steam.game.wishlist' && taskDes.attr('data-steam-wishlist-appid')) {
  8329. this.undoneTasks.steam.wishlistLinks.push(`https://store.steampowered.com/app/${taskDes.attr('data-steam-wishlist-appid')}`);
  8330. } else if (taskType === 'steam.game.follow' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8331. this.undoneTasks.steam.followLinks.push(taskLink);
  8332. } else if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  8333. this.undoneTasks.steam.curatorLinks.push(taskLink);
  8334. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  8335. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  8336. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  8337. this.undoneTasks.steam.forumLinks.push(taskLink);
  8338. } else if (taskIcon.includes('discord')) {
  8339. this.undoneTasks.discord.serverLinks.push(taskLink);
  8340. } else if (taskIcon.includes('instagram')) {
  8341. this.undoneTasks.instagram.userLinks.push(taskLink);
  8342. } else if (taskIcon.includes('twitch')) {
  8343. this.undoneTasks.twitch.channelLinks.push(taskLink);
  8344. } else if (taskIcon.includes('reddit')) {
  8345. this.undoneTasks.reddit.redditLinks.push(taskLink);
  8346. } else if (/watch.*art/gim.test(taskName)) {
  8347. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  8348. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  8349. this.undoneTasks.youtube.channelLinks.push(taskLink);
  8350. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  8351. this.undoneTasks.youtube.likeLinks.push(taskLink);
  8352. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  8353. this.undoneTasks.vk.nameLinks.push(taskLink);
  8354. } else if (taskIcon.includes('twitter')) {
  8355. if (/https?:\/\/(twitter|x)\.com\/[^/]+\/?$/gim.test(taskLink)) {
  8356. this.undoneTasks.twitter.userLinks.push(taskLink);
  8357. } else if (/https?:\/\/(twitter|x)\.com\/[^/]+?\/status\/[\d]+/gim.test(taskLink)) {
  8358. this.undoneTasks.twitter.retweetLinks.push(taskLink);
  8359. }
  8360. } else {
  8361. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  8362. if (/follow.*button/gim.test(taskName)) {
  8363. this.undoneTasks.steam.followLinks.push(taskLink);
  8364. }
  8365. }
  8366. }
  8367. resolve(true);
  8368. }).catch(error => {
  8369. throwError(error, 'GiveeClub.classifyTask->getRedirectLink');
  8370. return false;
  8371. });
  8372. }));
  8373. }
  8374. await Promise.all(pro);
  8375. logStatus.success();
  8376. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8377. this.socialTasks = this.undoneTasks;
  8378. if (window.DEBUG) {
  8379. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8380. }
  8381. GM_setValue(`gcTasks-${this.giveawayId}`, {
  8382. tasks: this.socialTasks,
  8383. time: new Date().getTime()
  8384. });
  8385. return true;
  8386. } catch (error) {
  8387. throwError(error, 'GiveeClub.classifyTask');
  8388. return false;
  8389. }
  8390. }
  8391. async verifyTask() {
  8392. try {
  8393. const logStatus = scripts_echoLog({
  8394. text: i18n('giveeClubVerifyNotice')
  8395. });
  8396. const taskButtons = $('.event-actions tr button').has('i.glyphicon-refresh').not('[data-type="user.adblock"]');
  8397. for (const button of taskButtons) {
  8398. button.click();
  8399. if ($(button).attr('data-type') !== 'steam.game.wishlist') {
  8400. await delay(1e3);
  8401. }
  8402. }
  8403. logStatus.warning(i18n('giveeClubVerifyFinished'));
  8404. return true;
  8405. } catch (error) {
  8406. throwError(error, 'Givekey.verifyTask');
  8407. return false;
  8408. }
  8409. }
  8410. #checkLogin() {
  8411. try {
  8412. if (!globalOptions.other.checkLogin) {
  8413. return true;
  8414. }
  8415. if ($('a[href*="/account/auth"]').length > 0) {
  8416. window.open($('a[href*="/account/auth"]').attr('href'), '_self');
  8417. }
  8418. return true;
  8419. } catch (error) {
  8420. throwError(error, 'GiveeClub.checkLogin');
  8421. return false;
  8422. }
  8423. }
  8424. #getGiveawayId() {
  8425. const giveawayId = window.location.href.match(/\/event\/([\d]+)/)?.[1];
  8426. if (giveawayId) {
  8427. this.giveawayId = giveawayId;
  8428. return true;
  8429. }
  8430. scripts_echoLog({
  8431. text: i18n('getFailed', 'GiveawayId')
  8432. });
  8433. return false;
  8434. }
  8435. async #checkLeftKey() {
  8436. try {
  8437. if (!globalOptions.other.checkLeftKey) {
  8438. return true;
  8439. }
  8440. if ($('.event-ended').length > 0 && $('.event-winner').length === 0) {
  8441. await external_Swal_default().fire({
  8442. icon: 'warning',
  8443. title: i18n('notice'),
  8444. text: i18n('giveawayEnded'),
  8445. confirmButtonText: i18n('confirm'),
  8446. cancelButtonText: i18n('cancel'),
  8447. showCancelButton: true
  8448. }).then(({
  8449. value
  8450. }) => {
  8451. if (value) {
  8452. window.close();
  8453. }
  8454. });
  8455. }
  8456. return true;
  8457. } catch (error) {
  8458. throwError(error, 'Giveawaysu.checkLeftKey');
  8459. return false;
  8460. }
  8461. }
  8462. }
  8463. const website_GiveeClub = GiveeClub;
  8464. const defaultOptions = {
  8465. maxPoint: '99999999'
  8466. };
  8467. class OpiumPulses {
  8468. name = 'OpiumPulses';
  8469. options = {
  8470. ...defaultOptions,
  8471. ...GM_getValue('OpiumPulsesOptions')
  8472. };
  8473. maxPoints = 99999999;
  8474. myPoints = 0;
  8475. buttons = [ 'doFreeTask', 'doPointTask' ];
  8476. static test() {
  8477. return window.location.host === 'www.opiumpulses.com';
  8478. }
  8479. async after() {
  8480. try {
  8481. if (!this.#checkLogin()) {
  8482. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8483. }
  8484. this.maxPoints = parseInt(this.options.maxPoint, 10);
  8485. } catch (error) {
  8486. throwError(error, 'OpiumPulses.after');
  8487. }
  8488. }
  8489. async doFreeTask() {
  8490. try {
  8491. this.#toggleTask('FREE');
  8492. } catch (error) {
  8493. throwError(error, 'OpiumPulses.doFreeTask');
  8494. }
  8495. }
  8496. async doPointTask() {
  8497. try {
  8498. this.myPoints = parseInt($('.page-header__nav-func-user-nav-items.points-items').text().match(/[\d]+/gim)?.[0] || '0', 10);
  8499. this.#toggleTask('points');
  8500. } catch (error) {
  8501. throwError(error, 'OpiumPulses.doPointTask');
  8502. }
  8503. }
  8504. async #toggleTask(type) {
  8505. try {
  8506. const items = $(`.giveaways-page-item:contains('${type}'):not(:contains('ENTERED'))`);
  8507. for (const item of items) {
  8508. const needPoints = parseInt($(item).find('.giveaways-page-item-header-points').text().match(/[\d]+/gim)?.[0] || '999999', 10);
  8509. const name = $(item).find('.giveaways-page-item-footer-name').text().trim();
  8510. if (type === 'points' && needPoints > this.myPoints) {
  8511. scripts_echoLog({}).warning(`${i18n('noPoints')}: ${name}`);
  8512. } else if (type === 'points' && !needPoints) {
  8513. scripts_echoLog({}).warning(`${i18n('getNeedPointsFailed')}: ${name}`);
  8514. } else if (!(type === 'points' && needPoints > this.maxPoints)) {
  8515. const logStatus = scripts_echoLog({
  8516. text: `${i18n('joiningLottery')}<a href="${$(item).find('a.giveaways-page-item-img-btn-more').attr('href')}" target="_blank">${name}</a>...`
  8517. });
  8518. const aElement = $(item).find('a.giveaways-page-item-img-btn-enter:contains(\'enter\')');
  8519. if (aElement?.attr('onclick')?.includes('checkUser')) {
  8520. const giveawayId = aElement.attr('onclick')?.match(/[\d]+/)?.[0];
  8521. if (giveawayId) {
  8522. checkUser(giveawayId);
  8523. }
  8524. }
  8525. if (!aElement.attr('href')) {
  8526. logStatus.error('Error: No "href".');
  8527. continue;
  8528. }
  8529. const {
  8530. result,
  8531. statusText,
  8532. status,
  8533. data
  8534. } = await tools_httpRequest({
  8535. url: aElement.attr('href'),
  8536. method: 'GET'
  8537. });
  8538. if (result === 'Success') {
  8539. const {
  8540. result: result0,
  8541. statusText: statusText0,
  8542. status: status0,
  8543. data: data0
  8544. } = await tools_httpRequest({
  8545. url: data?.finalUrl,
  8546. method: 'GET'
  8547. });
  8548. if (data0?.responseText && /You've entered this giveaway/gim.test(data0.responseText)) {
  8549. logStatus.success();
  8550. const points = data0.responseText.match(/Points:[\s]*?([\d]+)/)?.[1];
  8551. if (type === 'points' && points) {
  8552. this.myPoints = parseInt(points, 10);
  8553. }
  8554. } else if (data0?.responseText && /You're not eligible to enter/gim.test(data0.responseText)) {
  8555. logStatus.error('You\'re not eligible to enter');
  8556. } else {
  8557. logStatus.error(`${result0}:${statusText0}(${status0})`);
  8558. }
  8559. } else {
  8560. logStatus.error(`${result}:${statusText}(${status})`);
  8561. }
  8562. }
  8563. }
  8564. scripts_echoLog({
  8565. text: '-----END-----'
  8566. });
  8567. } catch (error) {
  8568. throwError(error, 'OpiumPulses.toggleTask');
  8569. }
  8570. }
  8571. init() {
  8572. return true;
  8573. }
  8574. classifyTask() {
  8575. return true;
  8576. }
  8577. #checkLogin() {
  8578. try {
  8579. if (!globalOptions.other.checkLogin) {
  8580. return true;
  8581. }
  8582. if ($('a[href*="/site/login"]').length > 1) {
  8583. window.open('/site/login', '_self');
  8584. }
  8585. return true;
  8586. } catch (error) {
  8587. throwError(error, 'OpiumPulses.checkLogin');
  8588. return false;
  8589. }
  8590. }
  8591. }
  8592. const website_OpiumPulses = OpiumPulses;
  8593. const external_dayjs_namespaceObject = dayjs;
  8594. var external_dayjs_default = __webpack_require__.n(external_dayjs_namespaceObject);
  8595. const leftKeyChecker = {
  8596. async classify(link) {
  8597. try {
  8598. if (/^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(link)) {
  8599. return await this.giveawaySu(link);
  8600. }
  8601. if (/^https?:\/\/givee\.club\/[\w]+?\/event\/[\d]+/.test(link)) {
  8602. return await this.giveeClub(link);
  8603. }
  8604. if (/^https?:\/\/gleam\.io\/.+?\/.+/.test(link)) {
  8605. return await this.gleam(link);
  8606. }
  8607. if (/^https?:\/\/www\.indiedb\.com\/giveaways\/.+/.test(link)) {
  8608. return await this.indieDb(link);
  8609. }
  8610. if (/^https?:\/\/key-hub\.eu\/giveaway\/[\d]+/.test(link)) {
  8611. return await this.keyhub(link);
  8612. }
  8613. if (/^https?:\/\/opquests\.com\/quests\/[\d]+/.test(link)) {
  8614. return await this.opquests(link);
  8615. }
  8616. if (/^https?:\/\/itch\.io\/s\/[\d]+?\/.*/.test(link)) {
  8617. return await this.itch(link);
  8618. }
  8619. return false;
  8620. } catch (error) {
  8621. throwError(error, 'leftKeyChecker.classify');
  8622. return false;
  8623. }
  8624. },
  8625. async giveawaySu(link) {
  8626. try {
  8627. const {
  8628. result,
  8629. data
  8630. } = await tools_httpRequest({
  8631. url: link,
  8632. method: 'GET'
  8633. });
  8634. if (result === 'Success' && data?.status === 200) {
  8635. if (data.responseText.includes('class="steam-login"')) {
  8636. return false;
  8637. }
  8638. if (data.responseText.includes('class="giveaway-ended"')) {
  8639. return 'Ended';
  8640. }
  8641. return 'Active';
  8642. }
  8643. return false;
  8644. } catch (error) {
  8645. throwError(error, 'leftKeyChecker.giveawaySu');
  8646. return false;
  8647. }
  8648. },
  8649. async giveeClub(link) {
  8650. try {
  8651. const {
  8652. result,
  8653. data
  8654. } = await tools_httpRequest({
  8655. url: link,
  8656. method: 'GET'
  8657. });
  8658. if (result === 'Success' && data?.status === 200) {
  8659. if (data.responseText.includes('class="event-winner"')) {
  8660. return 'Won';
  8661. }
  8662. if (data.responseText.includes('class="event-ended"')) {
  8663. return 'Ended';
  8664. }
  8665. return 'Active';
  8666. }
  8667. return false;
  8668. } catch (error) {
  8669. throwError(error, 'leftKeyChecker.giveeClub');
  8670. return false;
  8671. }
  8672. },
  8673. async gleam(link) {
  8674. try {
  8675. const {
  8676. result,
  8677. data
  8678. } = await tools_httpRequest({
  8679. url: link,
  8680. method: 'GET'
  8681. });
  8682. if (result === 'Success' && data?.status === 200) {
  8683. if (/incentives&quot;:{&quot;[\d]+?&quot;:\[&quot;.+?&quot;\]/.test(data.responseText)) {
  8684. return 'Won';
  8685. }
  8686. const campaignDiv = data.responseText.match(/<div class='popup-blocks-container'[\w\W]+?'>/)?.[0];
  8687. if (!campaignDiv) {
  8688. return false;
  8689. }
  8690. const campaignString = $(campaignDiv).attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  8691. if (!campaignString) {
  8692. return false;
  8693. }
  8694. const {
  8695. campaign
  8696. } = JSON.parse(campaignString);
  8697. if (campaign.banned) {
  8698. return 'Banned';
  8699. }
  8700. if (campaign.finished) {
  8701. return 'Ended';
  8702. }
  8703. if (campaign.paused) {
  8704. return 'Paused';
  8705. }
  8706. if (new Date().getTime() < campaign.starts_at * 1e3) {
  8707. return 'NotStart';
  8708. }
  8709. return 'Active';
  8710. }
  8711. return false;
  8712. } catch (error) {
  8713. throwError(error, 'leftKeyChecker.gleam');
  8714. return false;
  8715. }
  8716. },
  8717. async indieDb(link) {
  8718. try {
  8719. const {
  8720. result,
  8721. data
  8722. } = await tools_httpRequest({
  8723. url: link,
  8724. method: 'GET'
  8725. });
  8726. if (result === 'Success' && data?.status === 200) {
  8727. if (data.responseText.includes('Congrats you WON')) {
  8728. return 'Won';
  8729. }
  8730. if (data.responseText.includes('Giveaway is closed') || data.responseText.includes('next time')) {
  8731. return 'Ended';
  8732. }
  8733. return 'Active';
  8734. }
  8735. return false;
  8736. } catch (error) {
  8737. throwError(error, 'leftKeyChecker.indieDb');
  8738. return false;
  8739. }
  8740. },
  8741. async keyhub(link) {
  8742. try {
  8743. const {
  8744. result,
  8745. data
  8746. } = await tools_httpRequest({
  8747. url: link,
  8748. method: 'GET'
  8749. });
  8750. if (result === 'Success' && data?.status === 200) {
  8751. const keysleft = data.responseText.match(/<span id="keysleft">([\d]+?)<\/span>/)?.[1];
  8752. if (!keysleft) {
  8753. return false;
  8754. }
  8755. if (keysleft === '0') {
  8756. return 'Ended';
  8757. }
  8758. return `Active(${keysleft})`;
  8759. }
  8760. return false;
  8761. } catch (error) {
  8762. throwError(error, 'leftKeyChecker.keyhub');
  8763. return false;
  8764. }
  8765. },
  8766. async opquests(link) {
  8767. try {
  8768. const {
  8769. result,
  8770. data
  8771. } = await tools_httpRequest({
  8772. url: link,
  8773. method: 'GET'
  8774. });
  8775. if (result === 'Success' && data?.status === 200) {
  8776. const keysleft = data.responseText.match(/<div class="">[\s]*?([\d]+?)[\s]*?of/)?.[1];
  8777. if (!keysleft) {
  8778. return false;
  8779. }
  8780. if (keysleft === '0') {
  8781. return 'Ended';
  8782. }
  8783. return `Active(${keysleft})`;
  8784. } else if (data?.status === 404) {
  8785. return 'Ended';
  8786. }
  8787. return false;
  8788. } catch (error) {
  8789. throwError(error, 'leftKeyChecker.opquests');
  8790. return false;
  8791. }
  8792. },
  8793. async itch(link) {
  8794. try {
  8795. const {
  8796. result,
  8797. data
  8798. } = await tools_httpRequest({
  8799. url: link,
  8800. method: 'GET'
  8801. });
  8802. if (result === 'Success' && data?.status === 200) {
  8803. const endDate = data.responseText.match(/{"start_date":"[0-9A-Z-:]+?".*?"end_date":"([0-9A-Z-:]+?)".*?}/)?.[1];
  8804. if (!endDate) {
  8805. return false;
  8806. }
  8807. if (new Date().getTime() > new Date(endDate).getTime()) {
  8808. return 'Ended';
  8809. }
  8810. return `Active(${external_dayjs_default()(endDate).format('YYYY-MM-DD HH:mm:ss')})`;
  8811. }
  8812. return false;
  8813. } catch (error) {
  8814. throwError(error, 'leftKeyChecker.itch');
  8815. return false;
  8816. }
  8817. }
  8818. };
  8819. const website_leftKeyChecker = leftKeyChecker;
  8820. const Keylol_defaultTasksTemplate = {
  8821. steam: {
  8822. groupLinks: [],
  8823. wishlistLinks: [],
  8824. curatorLinks: [],
  8825. curatorLikeLinks: [],
  8826. followLinks: [],
  8827. forumLinks: [],
  8828. announcementLinks: [],
  8829. workshopVoteLinks: [],
  8830. licenseLinks: []
  8831. },
  8832. discord: {
  8833. serverLinks: []
  8834. },
  8835. instagram: {
  8836. userLinks: []
  8837. },
  8838. vk: {
  8839. nameLinks: []
  8840. },
  8841. twitch: {
  8842. channelLinks: []
  8843. },
  8844. reddit: {
  8845. redditLinks: []
  8846. },
  8847. twitter: {
  8848. userLinks: [],
  8849. retweetLinks: []
  8850. },
  8851. youtube: {
  8852. channelLinks: [],
  8853. likeLinks: []
  8854. }
  8855. };
  8856. const Keylol_defaultTasks = JSON.stringify(Keylol_defaultTasksTemplate);
  8857. class Keylol extends website_Website {
  8858. name = 'Keylol';
  8859. socialTasks = JSON.parse(Keylol_defaultTasks);
  8860. undoneTasks = JSON.parse(Keylol_defaultTasks);
  8861. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect' ];
  8862. static test() {
  8863. 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'));
  8864. }
  8865. init() {
  8866. return true;
  8867. }
  8868. after() {
  8869. try {
  8870. const selector = this.name === 'Keylol' ? '#postlist>div[id^="post_"]:first' : 'div.container';
  8871. const mainPost = $(selector);
  8872. const discordLinks = mainPost.find('a[href*="discord.com"]:visible');
  8873. const redditLinks = mainPost.find('a[href*="reddit.com"]:visible');
  8874. const insLinks = mainPost.find('a[href*="instagram.com"]:visible');
  8875. const twitterLinks = mainPost.find('a[href*="twitter.com"]:visible,a[href*="x.com"]:visible');
  8876. const twitchLinks = mainPost.find('a[href*="twitch.tv"]:visible');
  8877. const vkLinks = mainPost.find('a[href*="vk.com"]:visible');
  8878. const steamStoreLinks = mainPost.find('a[href*="store.steampowered.com"]:visible');
  8879. const steamCommunityLinks = mainPost.find('a[href*="steamcommunity.com"]:visible');
  8880. const ytbLinks = mainPost.find('a[href*="youtube.com"]:visible');
  8881. if (discordLinks.length > 0) {
  8882. for (const discordLink of discordLinks) {
  8883. const link = $(discordLink).attr('href');
  8884. if (!(link && /^https?:\/\/discord\.com\/invite\/.+/.test(link))) {
  8885. continue;
  8886. }
  8887. this.#addBtn(discordLink, 'discord', 'serverLinks', link);
  8888. }
  8889. }
  8890. if (redditLinks.length > 0) {
  8891. for (const redditLink of redditLinks) {
  8892. const link = $(redditLink).attr('href');
  8893. if (!(link && /^https?:\/\/www\.reddit\.com\/(r|user)\/.+/.test(link))) {
  8894. continue;
  8895. }
  8896. this.#addBtn(redditLink, 'reddit', 'redditLinks', link);
  8897. }
  8898. }
  8899. if (insLinks.length > 0) {
  8900. for (const insLink of insLinks) {
  8901. const link = $(insLink).attr('href');
  8902. if (!(link && /^https:\/\/www\.instagram\.com\/.+/.test(link))) {
  8903. continue;
  8904. }
  8905. this.#addBtn(insLink, 'instagram', 'userLinks', link);
  8906. }
  8907. }
  8908. if (twitterLinks.length > 0) {
  8909. for (const twitterLink of twitterLinks) {
  8910. const link = $(twitterLink).attr('href');
  8911. if (!(link && /^https:\/\/twitter\.com\/.+/.test(link))) {
  8912. continue;
  8913. }
  8914. if (/https:\/\/twitter\.com\/.*?\/status\/[\d]+/.test(link)) {
  8915. this.#addBtn(twitterLink, 'twitter', 'retweetLinks', link);
  8916. } else {
  8917. this.#addBtn(twitterLink, 'twitter', 'userLinks', link);
  8918. }
  8919. }
  8920. }
  8921. if (twitchLinks.length > 0) {
  8922. for (const twitchLink of twitchLinks) {
  8923. const link = $(twitchLink).attr('href');
  8924. if (!(link && /^https:\/\/(www\.)?twitch\.tv\/.+/.test(link))) {
  8925. continue;
  8926. }
  8927. this.#addBtn(twitchLink, 'twitch', 'channelLinks', link);
  8928. }
  8929. }
  8930. if (vkLinks.length > 0) {
  8931. for (const vkLink of vkLinks) {
  8932. const link = $(vkLink).attr('href');
  8933. if (!(link && /^https:\/\/vk\.com\/.+/.test(link))) {
  8934. continue;
  8935. }
  8936. this.#addBtn(vkLink, 'vk', 'nameLinks', link);
  8937. }
  8938. }
  8939. if (steamStoreLinks.length > 0) {
  8940. for (const steamStoreLink of steamStoreLinks) {
  8941. const link = $(steamStoreLink).attr('href');
  8942. if (!link) {
  8943. continue;
  8944. }
  8945. if (/curator\/[\d]+/.test(link)) {
  8946. this.#addBtn(steamStoreLink, 'steam', 'curatorLinks', link);
  8947. } else if (/(publisher|developer|franchise)\/.+/.test(link)) {
  8948. this.#addBtn(steamStoreLink, 'steam', 'curatorLikeLinks', link);
  8949. } else if (/news(hub)?\/app\/[\d]+\/view\/[\d]+/.test(link)) {
  8950. this.#addBtn(steamStoreLink, 'steam', 'announcementLinks', link);
  8951. } else if (/app\/[\d]+/.test(link)) {
  8952. this.#addBtn(steamStoreLink, 'steam', 'followLinks', link);
  8953. this.#addBtn(steamStoreLink, 'steam', 'wishlistLinks', link);
  8954. }
  8955. }
  8956. }
  8957. if (steamCommunityLinks.length > 0) {
  8958. for (const steamCommunityLink of steamCommunityLinks) {
  8959. const link = $(steamCommunityLink).attr('href');
  8960. if (!link) {
  8961. continue;
  8962. }
  8963. if (/groups\/.+/.test(link)) {
  8964. this.#addBtn(steamCommunityLink, 'steam', 'groupLinks', link);
  8965. } else if (/announcements\/detail\/[\d]+/.test(link)) {
  8966. this.#addBtn(steamCommunityLink, 'steam', 'announcementLinks', link);
  8967. }
  8968. }
  8969. }
  8970. if (ytbLinks.length > 0) {
  8971. for (const ytbLink of ytbLinks) {
  8972. const link = $(ytbLink).attr('href');
  8973. if (!link) {
  8974. continue;
  8975. }
  8976. this.#addBtn(ytbLink, 'youtube', 'channelLinks', link);
  8977. this.#addBtn(ytbLink, 'youtube', 'likeLinks', link);
  8978. }
  8979. }
  8980. 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');
  8981. if (giveawayLinks.length > 0) {
  8982. for (const giveawayLink of giveawayLinks) {
  8983. const link = $(giveawayLink).attr('href');
  8984. if (!link) {
  8985. continue;
  8986. }
  8987. website_leftKeyChecker.classify(link).then(status => {
  8988. if (!status) {
  8989. return;
  8990. }
  8991. if (/^Active/.test(status)) {
  8992. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status active" title="${i18n('Active')}">${status}</font>`);
  8993. return;
  8994. }
  8995. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status not-active" title="${i18n(status)}">${status}</font>`);
  8996. }).catch(error => {
  8997. throwError(error, 'keylol.after -> leftKeyChecker');
  8998. });
  8999. }
  9000. }
  9001. if (this.name === 'Keylol') {
  9002. const asfLinks = mainPost.find('a[href^="#asf"]:visible');
  9003. if (asfLinks.length > 0) {
  9004. for (const asfLink of asfLinks) {
  9005. const link = $(asfLink).attr('href');
  9006. if (!link) {
  9007. continue;
  9008. }
  9009. this.#addBtn($(`a[href="${link}"]`).after('<span style="color: #ccc; margin: 0 -5px 0 5px"> | </span>').next()[0], 'steam', 'licenseLinks', `appid-${link.replace('#asf', '')}`);
  9010. }
  9011. }
  9012. const subLinks = mainPost.find('a[href*="steamdb.info/sub/"]:visible');
  9013. if (subLinks.length > 0) {
  9014. for (const subLink of subLinks) {
  9015. const link = $(subLink).attr('href');
  9016. if (!link) {
  9017. continue;
  9018. }
  9019. const subid = link.match(/^https:\/\/steamdb\.info\/sub\/([\d]+)/)?.[1];
  9020. if (!subid) {
  9021. continue;
  9022. }
  9023. this.#addBtn(subLink, 'steam', 'licenseLinks', `subid-${subid}`);
  9024. }
  9025. }
  9026. const asfLinks2 = mainPost.find('.blockcode:contains("addlicense"):visible');
  9027. if (asfLinks2.length > 0) {
  9028. for (const asfLink of asfLinks2) {
  9029. const appid = [ ...asfLink.innerText.matchAll(/a(pp)?\/([\d]+)/g) ].map(matched => matched?.[2]).filter(id => id) || [];
  9030. if (appid.length > 0) {
  9031. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `appid-${appid.join(',')}`);
  9032. }
  9033. const subid = asfLink.innerText.match(/[\d]+/g)?.filter(matched => !appid.includes(matched));
  9034. if (!subid || subid.length === 0) {
  9035. continue;
  9036. }
  9037. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `subid-${subid.join(',')}`);
  9038. }
  9039. }
  9040. }
  9041. if ($('#threadindex').length > 0) {
  9042. const [ targetNode ] = $('#postlist').children('div[id^="post_"]');
  9043. const config = {
  9044. childList: true
  9045. };
  9046. const observer = new MutationObserver(() => {
  9047. observer.disconnect();
  9048. this.after();
  9049. });
  9050. observer.observe(targetNode, config);
  9051. }
  9052. } catch (error) {
  9053. throwError(error, 'keylol.after');
  9054. }
  9055. }
  9056. classifyTask(action) {
  9057. try {
  9058. this.socialTasks = JSON.parse(Keylol_defaultTasks);
  9059. this.undoneTasks = JSON.parse(Keylol_defaultTasks);
  9060. const selectedBtns = $('.auto-task-keylol[selected="selected"]:visible');
  9061. for (const btn of selectedBtns) {
  9062. const button = $(btn);
  9063. const social = button.attr('data-social');
  9064. const type = button.attr('data-type');
  9065. const link = button.attr('data-link');
  9066. if (!(social && type && link)) {
  9067. continue;
  9068. }
  9069. if (action === 'do') {
  9070. this.undoneTasks[social][type].push(link);
  9071. }
  9072. if (action === 'undo') {
  9073. this.socialTasks[social][type].push(link);
  9074. }
  9075. }
  9076. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9077. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9078. if (window.DEBUG) {
  9079. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9080. }
  9081. return true;
  9082. } catch (error) {
  9083. throwError(error, 'Keylol.classifyTask');
  9084. return false;
  9085. }
  9086. }
  9087. selectAll() {
  9088. try {
  9089. $('.auto-task-keylol:visible').attr('selected', 'selected');
  9090. } catch (error) {
  9091. throwError(error, 'Keylol.selectAll');
  9092. }
  9093. }
  9094. selectNone() {
  9095. try {
  9096. $('.auto-task-keylol:visible').removeAttr('selected');
  9097. } catch (error) {
  9098. throwError(error, 'Keylol.selectNone');
  9099. }
  9100. }
  9101. invertSelect() {
  9102. try {
  9103. $('.auto-task-keylol:visible').each((index, element) => {
  9104. element.getAttribute('selected') ? element.removeAttribute('selected') : element.setAttribute('selected', 'selected');
  9105. });
  9106. } catch (error) {
  9107. throwError(error, 'Keylol.invertSelect');
  9108. }
  9109. }
  9110. #addBtn(before, social, linkType, link) {
  9111. try {
  9112. $(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>`);
  9113. } catch (error) {
  9114. throwError(error, 'keylol.addBtn');
  9115. }
  9116. }
  9117. }
  9118. const website_Keylol = Keylol;
  9119. const Opquests_defaultTasks = {
  9120. steam: {
  9121. groupLinks: [],
  9122. wishlistLinks: [],
  9123. followLinks: [],
  9124. curatorLikeLinks: []
  9125. }
  9126. };
  9127. class Opquests extends website_Website {
  9128. name = 'Opquests';
  9129. undoneTasks = {
  9130. ...Opquests_defaultTasks
  9131. };
  9132. buttons = [ 'doTask', 'verifyTask', 'getKey' ];
  9133. static test() {
  9134. return window.location.host === 'opquests.com';
  9135. }
  9136. async before() {
  9137. try {
  9138. const opquestsVerifyTasks = GM_getValue('opquestsVerifyTasks') || [];
  9139. if (opquestsVerifyTasks.length > 0) {
  9140. const taskId = opquestsVerifyTasks.pop();
  9141. GM_setValue('opquestsVerifyTasks', opquestsVerifyTasks);
  9142. const [ verifyBtn ] = $(`#task_id[value="${taskId}"]`).parent().find('button[type="button"]').has('i.fa-check');
  9143. if (verifyBtn) {
  9144. verifyBtn.click();
  9145. return;
  9146. }
  9147. this.before();
  9148. return;
  9149. }
  9150. if (GM_getValue('opquestsVerifyTasks')) {
  9151. GM_deleteValue('opquestsVerifyTasks');
  9152. }
  9153. } catch (error) {
  9154. throwError(error, 'Opquests.before');
  9155. }
  9156. }
  9157. async after() {
  9158. try {
  9159. if (!this.#checkLogin()) {
  9160. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9161. }
  9162. } catch (error) {
  9163. throwError(error, 'Opquests.after');
  9164. }
  9165. }
  9166. init() {
  9167. try {
  9168. const logStatus = scripts_echoLog({
  9169. text: i18n('initing')
  9170. });
  9171. if ($('a[href*="/auth/redirect"]').length > 0) {
  9172. window.open('/auth/redirect', '_self');
  9173. logStatus.warning(i18n('needLogin'));
  9174. return false;
  9175. }
  9176. if (!this.#getGiveawayId()) {
  9177. return false;
  9178. }
  9179. this.initialized = true;
  9180. logStatus.success();
  9181. return true;
  9182. } catch (error) {
  9183. throwError(error, 'Opquests.init');
  9184. return false;
  9185. }
  9186. }
  9187. async classifyTask(action) {
  9188. try {
  9189. if (action === 'undo') {
  9190. scripts_echoLog({
  9191. text: i18n('cannotUndo')
  9192. });
  9193. return false;
  9194. }
  9195. const logStatus = scripts_echoLog({
  9196. text: i18n('getTasksInfo')
  9197. });
  9198. const tasks = $('.w-full:contains("Validate") .items-center');
  9199. for (const task of tasks) {
  9200. const link = $(task).find('a:contains("Open")').attr('href');
  9201. const taskDes = $(task).find('div').eq(1).text().trim();
  9202. if (!link) {
  9203. continue;
  9204. }
  9205. if (/steamcommunity\.com\/groups\//.test(link)) {
  9206. this.undoneTasks.steam.groupLinks.push(link);
  9207. } else if (/store\.steampowered\.com\/app\//.test(link)) {
  9208. if (/wishlist/gim.test(taskDes)) {
  9209. this.undoneTasks.steam.wishlistLinks.push(link);
  9210. } else if (/follow/gim.test(taskDes)) {
  9211. this.undoneTasks.steam.followLinks.push(link);
  9212. }
  9213. } else if (/store\.steampowered\.com\/(publisher|developer|curator)\//.test(link) && /follow/gim.test(taskDes)) {
  9214. this.undoneTasks.steam.curatorLikeLinks.push(link);
  9215. } else {
  9216. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  9217. }
  9218. }
  9219. logStatus.success();
  9220. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9221. if (window.DEBUG) {
  9222. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9223. }
  9224. return true;
  9225. } catch (error) {
  9226. throwError(error, 'Opquests.classifyTask');
  9227. return false;
  9228. }
  9229. }
  9230. async verifyTask() {
  9231. try {
  9232. if (!this.initialized) {
  9233. this.init();
  9234. }
  9235. const tasks = $.makeArray($('.items-center').has('input[name="task_id"]')).map(ele => $(ele).find('input[name="task_id"]').val());
  9236. await this.#confirm();
  9237. const taskId = tasks.pop();
  9238. GM_setValue('opquestsVerifyTasks', tasks);
  9239. $(`#task_id[value="${taskId}"]`).parent().find('button[type="button"]').has('i.fa-check')[0]?.click();
  9240. return true;
  9241. } catch (error) {
  9242. throwError(error, 'Opquests.verifyTask');
  9243. return false;
  9244. }
  9245. }
  9246. async #confirm() {
  9247. try {
  9248. const logStatus = scripts_echoLog({
  9249. html: `<li>${i18n('confirmingTask')}...<font></font></li>`
  9250. });
  9251. const {
  9252. result,
  9253. statusText,
  9254. status,
  9255. data
  9256. } = await tools_httpRequest({
  9257. url: `https://opquests.com/quests/${this.giveawayId}?confirm=1`,
  9258. method: 'GET',
  9259. nochche: true,
  9260. headers: {
  9261. origin: 'https://opquests.com',
  9262. referer: `https://opquests.com/warning?id=${this.giveawayId}`
  9263. }
  9264. });
  9265. if (result === 'Success') {
  9266. if (data?.status === 200) {
  9267. logStatus.success();
  9268. return true;
  9269. }
  9270. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9271. return false;
  9272. }
  9273. logStatus.error(`${result}:${statusText}(${status})`);
  9274. return false;
  9275. } catch (error) {
  9276. throwError(error, 'Opquests.confirm');
  9277. return false;
  9278. }
  9279. }
  9280. async getKey(isButton) {
  9281. try {
  9282. const logStatus = scripts_echoLog({
  9283. text: i18n('gettingKey')
  9284. });
  9285. const {
  9286. result,
  9287. statusText,
  9288. status,
  9289. data
  9290. } = await tools_httpRequest({
  9291. url: 'https://opquests.com/keys',
  9292. method: 'GET'
  9293. });
  9294. if (result === 'Success') {
  9295. if (data?.responseText) {
  9296. const key = $(data?.responseText).find(`div.items-center:contains("${$('h1.font-bold').text().trim().replace(' Quest', '')}")`).find('div.font-bold').next().text();
  9297. if (!key) {
  9298. logStatus.error('Error: Key was not found');
  9299. if (isButton) {
  9300. window.open('https://opquests.com/keys', '_self');
  9301. }
  9302. return false;
  9303. }
  9304. logStatus.success();
  9305. scripts_echoLog({}).success(key);
  9306. return true;
  9307. }
  9308. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9309. return false;
  9310. }
  9311. logStatus.error(`${result}:${statusText}(${status})`);
  9312. return false;
  9313. } catch (error) {
  9314. throwError(error, 'Opquests.getGiveawayId');
  9315. return false;
  9316. }
  9317. }
  9318. #getGiveawayId() {
  9319. try {
  9320. const giveawayId = window.location.href.match(/quests\/([\d]+)/)?.[1];
  9321. if (giveawayId) {
  9322. this.giveawayId = giveawayId;
  9323. return true;
  9324. }
  9325. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  9326. return false;
  9327. } catch (error) {
  9328. throwError(error, 'Opquests.getGiveawayId');
  9329. return false;
  9330. }
  9331. }
  9332. #checkLogin() {
  9333. try {
  9334. if (!globalOptions.other.checkLogin) {
  9335. return true;
  9336. }
  9337. if ($('a[href*="/auth/redirect"]').length > 0) {
  9338. window.open('/auth/redirect', '_self');
  9339. }
  9340. return true;
  9341. } catch (error) {
  9342. throwError(error, 'Opquests.checkLogin');
  9343. return false;
  9344. }
  9345. }
  9346. }
  9347. const website_Opquests = Opquests;
  9348. const Gleam_defaultTasksTemplate = {
  9349. steam: {
  9350. groupLinks: [],
  9351. wishlistLinks: [],
  9352. followLinks: [],
  9353. curatorLinks: [],
  9354. curatorLikeLinks: []
  9355. },
  9356. twitter: {
  9357. userLinks: [],
  9358. retweetLinks: []
  9359. },
  9360. twitch: {
  9361. channelLinks: []
  9362. },
  9363. discord: {
  9364. serverLinks: []
  9365. },
  9366. youtube: {
  9367. channelLinks: []
  9368. },
  9369. extra: {
  9370. gleam: []
  9371. }
  9372. };
  9373. const Gleam_defaultTasks = JSON.stringify(Gleam_defaultTasksTemplate);
  9374. class Gleam extends website_Website {
  9375. name = 'Gleam';
  9376. undoneTasks = JSON.parse(Gleam_defaultTasks);
  9377. socialTasks = JSON.parse(Gleam_defaultTasks);
  9378. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  9379. static test() {
  9380. return window.location.host === 'gleam.io';
  9381. }
  9382. before() {
  9383. try {
  9384. unsafeWindow.confirm = () => {};
  9385. unsafeWindow.alert = () => {};
  9386. unsafeWindow.prompt = () => {};
  9387. } catch (error) {
  9388. throwError(error, 'Gleam.before');
  9389. }
  9390. }
  9391. async after() {
  9392. try {
  9393. if (window.location.search.includes('8b07d23f4bfa65f9')) {
  9394. const checkComplete = setInterval(() => {
  9395. if ($('.entry-content .entry-method i.fa-check').length > 0) {
  9396. clearInterval(checkComplete);
  9397. window.close();
  9398. }
  9399. });
  9400. for (const task of $('.entry-content .entry-method')) {
  9401. const taskInfo = $(task).find('.user-links');
  9402. const expandInfo = $(task).find('.expandable');
  9403. const aElements = expandInfo.find('a.btn,a:contains(Continue),button:contains(Continue)');
  9404. if (aElements.length > 0) {
  9405. for (const element of aElements) {
  9406. const $element = $(element);
  9407. const href = $element.attr('href');
  9408. $element.removeAttr('href')[0].click();
  9409. $element.attr('href', href);
  9410. await delay(1e3);
  9411. }
  9412. }
  9413. taskInfo[0].click();
  9414. await delay(1e3);
  9415. }
  9416. scripts_echoLog({}).warning(i18n('gleamTaskNotice'));
  9417. } else if (!await this.#checkLeftKey()) {
  9418. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  9419. }
  9420. } catch (error) {
  9421. throwError(error, 'Gleam.after');
  9422. }
  9423. }
  9424. init() {
  9425. try {
  9426. const logStatus = scripts_echoLog({
  9427. text: i18n('initing')
  9428. });
  9429. if (!this.#getGiveawayId()) {
  9430. return false;
  9431. }
  9432. this.initialized = true;
  9433. logStatus.success();
  9434. return true;
  9435. } catch (error) {
  9436. throwError(error, 'Gleam.init');
  9437. return false;
  9438. }
  9439. }
  9440. async classifyTask(action) {
  9441. try {
  9442. const logStatus = scripts_echoLog({
  9443. text: i18n('getTasksInfo')
  9444. });
  9445. if (action === 'undo') {
  9446. this.socialTasks = GM_getValue(`gleamTasks-${this.giveawayId}`)?.tasks || JSON.parse(Gleam_defaultTasks);
  9447. }
  9448. const tasks = $('.entry-content .entry-method');
  9449. for (const task of tasks) {
  9450. const $task = $(task);
  9451. if (action === 'do' && $task.find('i.fa-question').length === 0) {
  9452. continue;
  9453. }
  9454. const socialIcon = $task.find('.icon-wrapper i');
  9455. const taskInfo = $task.find('.user-links');
  9456. const taskText = taskInfo.text().trim();
  9457. const expandInfo = $task.find('.expandable');
  9458. const aElements = expandInfo.find('a.btn');
  9459. if (aElements.length > 0) {
  9460. for (const element of aElements) {
  9461. const $element = $(element);
  9462. const href = $element.attr('href');
  9463. $element.removeAttr('href')[0].click();
  9464. $element.attr('href', href);
  9465. }
  9466. }
  9467. if (socialIcon.hasClass('fa-twitter') || socialIcon.hasClass('fa-x-twitter')) {
  9468. const link = $task.find('a[href^="https://twitter.com/"],a[href^="https://x.com/"]').attr('href');
  9469. if (!link) {
  9470. continue;
  9471. }
  9472. if (/follow/gi.test(taskText)) {
  9473. if (action === 'undo') {
  9474. this.socialTasks.twitter.userLinks.push(link);
  9475. }
  9476. if (action === 'do') {
  9477. this.undoneTasks.twitter.userLinks.push(link);
  9478. }
  9479. } else if (/retweet/gim.test(taskText)) {
  9480. if (action === 'undo') {
  9481. this.socialTasks.twitter.retweetLinks.push(link);
  9482. }
  9483. if (action === 'do') {
  9484. this.undoneTasks.twitter.retweetLinks.push(link);
  9485. }
  9486. }
  9487. } else if (socialIcon.hasClass('fa-twitch')) {
  9488. if (/follow/gim.test(taskText)) {
  9489. const link = $task.find('a[href^="https://twitch.tv/"]').attr('href');
  9490. if (!link) {
  9491. continue;
  9492. }
  9493. if (action === 'undo') {
  9494. this.socialTasks.twitch.channelLinks.push(link);
  9495. }
  9496. if (action === 'do') {
  9497. this.undoneTasks.twitch.channelLinks.push(link);
  9498. }
  9499. }
  9500. } else if (socialIcon.hasClass('fa-discord')) {
  9501. if (/join/gim.test(taskText)) {
  9502. let link = $task.find('a[href^="https://discord.com/invite/"]').attr('href');
  9503. if (!link) {
  9504. const ggLink = $task.find('a[href^="https://discord.gg/"]').attr('href')?.match(/discord\.gg\/([^/]+)/)?.[1];
  9505. if (!ggLink) {
  9506. continue;
  9507. }
  9508. link = `https://discord.com/invite/${ggLink}`;
  9509. }
  9510. if (action === 'undo') {
  9511. this.socialTasks.discord.serverLinks.push(link);
  9512. }
  9513. if (action === 'do') {
  9514. this.undoneTasks.discord.serverLinks.push(link);
  9515. }
  9516. }
  9517. } else if (socialIcon.hasClass('fa-external-link-square-alt')) {
  9518. continue;
  9519. } else if (socialIcon.hasClass('fa-youtube')) {
  9520. if (/subscribe/gim.test(taskText)) {
  9521. const link = $task.find('a[href^="https://www.youtube.com/channel/"]').attr('href');
  9522. if (!link) {
  9523. continue;
  9524. }
  9525. if (action === 'undo') {
  9526. this.socialTasks.youtube.channelLinks.push(link);
  9527. }
  9528. if (action === 'do') {
  9529. this.undoneTasks.youtube.channelLinks.push(link);
  9530. }
  9531. }
  9532. } else if (socialIcon.attr('class')?.includes('steam')) {
  9533. if (/join.*group/gi.test(taskText)) {
  9534. const link = $task.find('a[href^="https://steamcommunity.com/groups/"]').attr('href');
  9535. if (!link) {
  9536. continue;
  9537. }
  9538. if (action === 'undo') {
  9539. this.socialTasks.steam.groupLinks.push(link);
  9540. }
  9541. if (action === 'do') {
  9542. this.undoneTasks.steam.groupLinks.push(link);
  9543. }
  9544. } else if (/follow.*curator/gi.test(taskText)) {
  9545. const link = $task.find('a[href^="https://store.steampowered.com/curator/"]').attr('href');
  9546. if (!link) {
  9547. continue;
  9548. }
  9549. if (action === 'undo') {
  9550. this.socialTasks.steam.curatorLinks.push(link);
  9551. }
  9552. if (action === 'do') {
  9553. this.undoneTasks.steam.curatorLinks.push(link);
  9554. }
  9555. }
  9556. } else if (socialIcon.hasClass('fa-bullhorn') && /Complete/gi.test(taskText)) {
  9557. if (action !== 'do') {
  9558. continue;
  9559. }
  9560. const gleamLink = await this.#getGleamLink(taskText);
  9561. if (!gleamLink) {
  9562. continue;
  9563. }
  9564. this.undoneTasks.extra.gleam.push(gleamLink);
  9565. } 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 {
  9566. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskText}`);
  9567. }
  9568. }
  9569. logStatus.success();
  9570. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9571. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9572. if (window.DEBUG) {
  9573. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9574. }
  9575. GM_setValue(`gleamTasks-${this.giveawayId}`, {
  9576. tasks: this.socialTasks,
  9577. time: new Date().getTime()
  9578. });
  9579. return true;
  9580. } catch (error) {
  9581. throwError(error, 'Gleam.classifyTask');
  9582. return false;
  9583. }
  9584. }
  9585. async extraDoTask({
  9586. gleam
  9587. }) {
  9588. try {
  9589. const pro = [];
  9590. for (const link of gleam) {
  9591. pro.push(this.#doGleamTask(link));
  9592. }
  9593. return Promise.all(pro).then(() => true);
  9594. } catch (error) {
  9595. throwError(error, 'Gleam.extraDoTask');
  9596. return false;
  9597. }
  9598. }
  9599. async verifyTask() {
  9600. try {
  9601. scripts_echoLog({
  9602. text: `${i18n('verifyingTask')}...`
  9603. });
  9604. const tasks = $('.entry-content .entry-method');
  9605. unsafeWindow._OxA = '_OxA';
  9606. for (const task of tasks) {
  9607. if ($('[campaign-key="campaign.key"]').length > 0) {
  9608. return scripts_echoLog({
  9609. text: i18n('campaign')
  9610. });
  9611. }
  9612. const $task = $(task);
  9613. if ($task.find('i.fa-question').length === 0) {
  9614. continue;
  9615. }
  9616. const taskInfo = $task.find('.user-links');
  9617. taskInfo[0].click();
  9618. const aElements = $task.find('.expandable').find('a.btn');
  9619. if (aElements.length > 0) {
  9620. for (const element of aElements) {
  9621. const $element = $(element);
  9622. const href = $element.attr('href');
  9623. $element.removeAttr('href')[0].click();
  9624. $element.attr('href', href);
  9625. }
  9626. }
  9627. unsafeWindow.$hookTimer?.setSpeed(1e3);
  9628. const visitBtn = $task.find('.expandable').find('span:contains(more seconds),button:contains(more seconds)').filter(':visible');
  9629. if (visitBtn.length > 0 && unsafeWindow.$hookTimer) {
  9630. const newTab = GM_openInTab('', {
  9631. active: true
  9632. });
  9633. await delay(1e3);
  9634. newTab?.close();
  9635. window.focus();
  9636. }
  9637. await delay(3e3);
  9638. unsafeWindow.$hookTimer?.setSpeed(1);
  9639. const expandInfo = $task.find('.expandable');
  9640. const [ input ] = expandInfo.find('input');
  9641. if (input) {
  9642. const evt = new Event('input', {
  9643. bubbles: true,
  9644. cancelable: true,
  9645. composed: true
  9646. });
  9647. const valuelimit = [ ...expandInfo.text().matchAll(/"(.+?)"/g) ].at(-1)?.[1];
  9648. input.value = valuelimit || 'vloot';
  9649. input.dispatchEvent(evt);
  9650. await delay(1e3);
  9651. }
  9652. await this.#checkSync();
  9653. const continueBtn = $task.find('.expandable').find('span:contains(Continue),button:contains(Continue)');
  9654. for (const button of continueBtn) {
  9655. button.click();
  9656. await delay(500);
  9657. await this.#checkSync();
  9658. }
  9659. }
  9660. scripts_echoLog({
  9661. text: i18n('verifiedGleamTasks')
  9662. });
  9663. } catch (error) {
  9664. throwError(error, 'Gleam.verifyTask');
  9665. return false;
  9666. }
  9667. }
  9668. async #checkSync() {
  9669. try {
  9670. return await new Promise(resolve => {
  9671. const checker = setInterval(() => {
  9672. if ($('.entry-content .entry-method i.fa-sync').length === 0) {
  9673. clearInterval(checker);
  9674. resolve(true);
  9675. }
  9676. }, 500);
  9677. });
  9678. } catch (error) {
  9679. throwError(error, 'Gleam.checkSync');
  9680. return false;
  9681. }
  9682. }
  9683. async #doGleamTask(link) {
  9684. try {
  9685. const logStatus = scripts_echoLog({
  9686. text: i18n('doingGleamTask')
  9687. });
  9688. return await new Promise(resolve => {
  9689. GM_openInTab(`${link}?8b07d23f4bfa65f9`, {
  9690. active: true,
  9691. insert: true,
  9692. setParent: true
  9693. }).onclose = () => {
  9694. logStatus.success();
  9695. resolve(true);
  9696. };
  9697. });
  9698. } catch (error) {
  9699. throwError(error, 'Gleam.doGleamTask');
  9700. return false;
  9701. }
  9702. }
  9703. #getGiveawayId() {
  9704. try {
  9705. const giveawayId = window.location.pathname;
  9706. if (giveawayId) {
  9707. this.giveawayId = giveawayId;
  9708. return true;
  9709. }
  9710. scripts_echoLog({
  9711. text: i18n('getFailed', 'GiveawayId')
  9712. });
  9713. return false;
  9714. } catch (error) {
  9715. throwError(error, 'Gleam.getGiveawayId');
  9716. return false;
  9717. }
  9718. }
  9719. async #getGleamLink(title) {
  9720. try {
  9721. const logStatus = scripts_echoLog({
  9722. text: i18n('gettingGleamLink')
  9723. });
  9724. const {
  9725. result,
  9726. statusText,
  9727. status,
  9728. data
  9729. } = await tools_httpRequest({
  9730. url: 'https://www.vloot.io/api/v1/giveaways',
  9731. method: 'GET',
  9732. responseType: 'json'
  9733. });
  9734. if (result === 'Success') {
  9735. if (data?.status === 200 && data?.response?.Success === true && data?.response?.Data) {
  9736. const {
  9737. link
  9738. } = data.response.Data.find(giveaway => title.replace(/[\s]/g, '').toLowerCase().includes(giveaway.title.replace(/[\s]/g, '').toLowerCase())) || {};
  9739. if (link) {
  9740. logStatus.success();
  9741. return link;
  9742. }
  9743. logStatus.error(`Error:${i18n('getLinkFailed')}`);
  9744. return false;
  9745. }
  9746. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9747. return false;
  9748. }
  9749. logStatus.error(`${result}:${statusText}(${status})`);
  9750. return false;
  9751. } catch (error) {
  9752. throwError(error, 'Gleam.getGleamLink');
  9753. return false;
  9754. }
  9755. }
  9756. async #checkLeftKey() {
  9757. try {
  9758. if (!globalOptions.other.checkLeftKey) {
  9759. return true;
  9760. }
  9761. const campaignString = $('div.popup-blocks-container').attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  9762. if (!campaignString) {
  9763. return false;
  9764. }
  9765. const {
  9766. campaign,
  9767. incentive
  9768. } = JSON.parse(campaignString);
  9769. const controllerString = $('div.campaign.reward').attr('ng-init')?.match(/initContestant\(([\w\W]+?)\);/)?.[1];
  9770. let ownedKey = false;
  9771. if (controllerString) {
  9772. if (JSON.parse(controllerString).contestant?.claims?.incentives?.[incentive.id]?.length) {
  9773. ownedKey = true;
  9774. }
  9775. }
  9776. if (campaign.banned || campaign.finished && !ownedKey || campaign.paused || new Date().getTime() < campaign.starts_at * 1e3) {
  9777. await external_Swal_default().fire({
  9778. icon: 'warning',
  9779. title: i18n('notice'),
  9780. text: i18n('giveawayNotWork'),
  9781. confirmButtonText: i18n('confirm'),
  9782. cancelButtonText: i18n('cancel'),
  9783. showCancelButton: true
  9784. }).then(({
  9785. value
  9786. }) => {
  9787. if (value) {
  9788. window.close();
  9789. }
  9790. });
  9791. }
  9792. return true;
  9793. } catch (error) {
  9794. throwError(error, 'Gleam.checkLeftKey');
  9795. return false;
  9796. }
  9797. }
  9798. }
  9799. const website_Gleam = Gleam;
  9800. const SweepWidget_defaultOptions = {
  9801. username: '',
  9802. email: ''
  9803. };
  9804. class SweepWidget extends website_Website {
  9805. name = 'SweepWidget';
  9806. options = {
  9807. ...SweepWidget_defaultOptions,
  9808. ...GM_getValue('SweepWidgetOptions')
  9809. };
  9810. buttons = [ 'doTask' ];
  9811. static test() {
  9812. return /^https?:\/\/sweepwidget\.com\/view\/[\d]+/.test(window.location.href);
  9813. }
  9814. async after() {
  9815. try {
  9816. if (!this.#checkLogin()) {
  9817. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9818. }
  9819. } catch (error) {
  9820. throwError(error, 'SweepWidget.after');
  9821. }
  9822. }
  9823. init() {
  9824. try {
  9825. const logStatus = scripts_echoLog({
  9826. text: i18n('initing')
  9827. });
  9828. if (!this.#checkLogin()) {
  9829. logStatus.warning(i18n('needLogin'));
  9830. return false;
  9831. }
  9832. if (!this.#getGiveawayId()) {
  9833. return false;
  9834. }
  9835. this.initialized = true;
  9836. logStatus.success();
  9837. return true;
  9838. } catch (error) {
  9839. throwError(error, 'SweepWidget.init');
  9840. return false;
  9841. }
  9842. }
  9843. classifyTask() {
  9844. return true;
  9845. }
  9846. async doTask() {
  9847. try {
  9848. if ($('#unlock_rewards_main_wrapper').length === 0) {
  9849. if ($('input[name="sw__login_name"]:visible').length > 0) {
  9850. $('input[name="sw__login_name"]').val(this.options.username);
  9851. }
  9852. if ($('input[name="sw__login_email"]:visible').length > 0) {
  9853. $('input[name="sw__login_email"]').val(this.options.email);
  9854. }
  9855. if ($('#sw_login_button:visible').length > 0) {
  9856. $('#sw_login_button')[0].click();
  9857. }
  9858. if (!await this.#checkEnter()) {
  9859. return false;
  9860. }
  9861. }
  9862. const logStatus = scripts_echoLog({
  9863. text: i18n('SweepWidgetNotice')
  9864. });
  9865. const tasks = $('#sw_inner_entry_methods_l2_wrapper>div.sw_entry');
  9866. for (const task of tasks) {
  9867. const $task = $(task);
  9868. if ($task.find('i.fa-check:visible').length > 0) {
  9869. continue;
  9870. }
  9871. const title = $task.find('.sw_text_inner');
  9872. title[0].click();
  9873. const aElement = $task.find('a.sw_link');
  9874. const link = aElement.attr('href');
  9875. aElement.attr('href', '#a').attr('target', '_self');
  9876. aElement[0]?.click();
  9877. await delay(300);
  9878. aElement.attr('href', link).attr('target', '_blank');
  9879. $task.find('input[type="text"]').val('test');
  9880. const verifyBtn = $task.find('input.sw_verify');
  9881. if (verifyBtn.prop('disabled') === true) {
  9882. title[0].click();
  9883. await delay(300);
  9884. title[0].click();
  9885. await delay(300);
  9886. }
  9887. $task.find('input.sw_verify').removeAttr('disabled')[0]?.click();
  9888. await this.#checkFinish($task);
  9889. await delay(parseInt(`${Math.random() * (3e3 - 1e3 + 1) + 1e3}`, 10));
  9890. }
  9891. logStatus.success();
  9892. return true;
  9893. } catch (error) {
  9894. throwError(error, 'SweepWidget.doTask');
  9895. return false;
  9896. }
  9897. }
  9898. #checkLogin() {
  9899. try {
  9900. if ($('#twitter_login_button').length > 0) {
  9901. $('#twitter_login_button')[0].click();
  9902. }
  9903. return true;
  9904. } catch (error) {
  9905. throwError(error, 'SweepWidget.checkLogin');
  9906. return false;
  9907. }
  9908. }
  9909. #getGiveawayId() {
  9910. try {
  9911. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  9912. if (giveawayId) {
  9913. this.giveawayId = giveawayId;
  9914. return true;
  9915. }
  9916. scripts_echoLog({
  9917. text: i18n('getFailed', 'GiveawayId')
  9918. });
  9919. return false;
  9920. } catch (error) {
  9921. throwError(error, 'SweepWidget.getGiveawayId');
  9922. return false;
  9923. }
  9924. }
  9925. async #checkEnter() {
  9926. try {
  9927. return new Promise(resolve => {
  9928. const checker = setInterval(() => {
  9929. if ($('#unlock_rewards_main_wrapper').length > 0) {
  9930. clearInterval(checker);
  9931. resolve(true);
  9932. }
  9933. }, 500);
  9934. });
  9935. } catch (error) {
  9936. throwError(error, 'SweepWidget.checkEnter');
  9937. return false;
  9938. }
  9939. }
  9940. async #checkFinish($task) {
  9941. try {
  9942. return new Promise(resolve => {
  9943. const checker = setInterval(() => {
  9944. if ($task.find('i.fa-check:visible').length > 0 || $task.find('.sw_entry_input:visible').length === 0) {
  9945. clearInterval(checker);
  9946. resolve(true);
  9947. }
  9948. }, 500);
  9949. });
  9950. } catch (error) {
  9951. throwError(error, 'SweepWidget.checkFinish');
  9952. return false;
  9953. }
  9954. }
  9955. }
  9956. const website_SweepWidget = SweepWidget;
  9957. const defaultWhiteList = {
  9958. discord: {
  9959. servers: []
  9960. },
  9961. instagram: {
  9962. users: []
  9963. },
  9964. twitch: {
  9965. channels: []
  9966. },
  9967. twitter: {
  9968. users: [],
  9969. retweets: [],
  9970. likes: []
  9971. },
  9972. vk: {
  9973. names: []
  9974. },
  9975. youtube: {
  9976. channels: [],
  9977. likes: []
  9978. },
  9979. reddit: {
  9980. reddits: []
  9981. },
  9982. steam: {
  9983. groups: [],
  9984. officialGroups: [],
  9985. wishlists: [],
  9986. follows: [],
  9987. forums: [],
  9988. workshops: [],
  9989. curators: [],
  9990. workshopVotes: [],
  9991. curatorLikes: [],
  9992. announcements: [],
  9993. licenses: [],
  9994. playtests: []
  9995. }
  9996. };
  9997. const link2id = async function(type) {
  9998. try {
  9999. const link = $('#socialLink').val();
  10000. let id = '';
  10001. switch (type) {
  10002. case 'discord.servers':
  10003. id = link.match(/invite\/(.+)/)?.[1] || '';
  10004. break;
  10005.  
  10006. case 'instagram.users':
  10007. id = link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1] || '';
  10008. break;
  10009.  
  10010. case 'twitch.channels':
  10011. id = link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2] || '';
  10012. break;
  10013.  
  10014. case 'twitter.users':
  10015. id = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || '';
  10016. break;
  10017.  
  10018. case 'twitter.retweets':
  10019. id = link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1] || '';
  10020. break;
  10021.  
  10022. case 'vk.names':
  10023. id = link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1] || '';
  10024. break;
  10025.  
  10026. case 'youtube.channels':
  10027. id = (await getInfo(link, 'channel'))?.params?.channelId || '';
  10028. break;
  10029.  
  10030. case 'youtube.likes':
  10031. id = (await getInfo(link, 'likeVideo'))?.params?.videoId || '';
  10032. break;
  10033.  
  10034. case 'reddit.reddits':
  10035. id = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1] || link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1] || '';
  10036. break;
  10037.  
  10038. case 'steam.groups':
  10039. id = link.match(/groups\/(.+)\/?/)?.[1] || '';
  10040. break;
  10041.  
  10042. case 'steam.wishlists':
  10043. case 'steam.follows':
  10044. case 'steam.forums':
  10045. id = link.match(/app\/([\d]+)/)?.[1] || '';
  10046. break;
  10047.  
  10048. case 'steam.workshops':
  10049. id = link.match(/\?id=([\d]+)/)?.[1] || '';
  10050. break;
  10051.  
  10052. case 'steam.curators':
  10053. {
  10054. if (link.includes('curator')) {
  10055. id = link.match(/curator\/([\d]+)/)?.[1] || '';
  10056. } else {
  10057. const param = link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3);
  10058. if (!param || param.length !== 2) {
  10059. break;
  10060. }
  10061. const steam = new social_Steam();
  10062. if (await steam.init()) {
  10063. id = await steam.getCuratorId(param[0], param[1]) || '';
  10064. }
  10065. }
  10066. }
  10067. break;
  10068. }
  10069. return id;
  10070. } catch (error) {
  10071. throwError(error, 'link2id');
  10072. return i18n('getFailed', 'id');
  10073. }
  10074. };
  10075. const disabledType = {
  10076. steam: [ 'workshopVotes', 'curatorLikes', 'announcements' ],
  10077. twitter: [ 'likes' ]
  10078. };
  10079. const assignWhiteList = whiteList => {
  10080. try {
  10081. const newWhiteList = {};
  10082. for (const [ key, value ] of Object.entries(defaultWhiteList)) {
  10083. newWhiteList[key] = {
  10084. ...value,
  10085. ...whiteList[key]
  10086. };
  10087. }
  10088. return newWhiteList;
  10089. } catch (error) {
  10090. throwError(error, 'assignWhiteList');
  10091. return defaultWhiteList;
  10092. }
  10093. };
  10094. const whiteListOptions = function(showType) {
  10095. try {
  10096. const whiteList = assignWhiteList(GM_getValue('whiteList') || {});
  10097. let whiteListOptionsForm = `<form id="whiteListForm" class="auto-task-form">
  10098. <table class="auto-task-table"><thead><tr><td>${i18n('website')}</td><td>${i18n('type')}</td><td>${i18n('edit')}</td></tr></thead><tbody>`;
  10099. for (const [ social, types ] of Object.entries(whiteList)) {
  10100. 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('');
  10101. }
  10102. whiteListOptionsForm += '</tbody></table></form>';
  10103. if (showType === 'swal') {
  10104. external_Swal_default().fire({
  10105. title: i18n('whiteListOptions'),
  10106. html: whiteListOptionsForm,
  10107. showConfirmButton: false,
  10108. showCloseButton: true
  10109. });
  10110. } else {
  10111. $('body').append(`<h2>${i18n('whiteList')}</h2>${whiteListOptionsForm}`);
  10112. }
  10113. $('.editWhiteList').on('click', function() {
  10114. const value = $(this).attr('data-value');
  10115. if (!value) {
  10116. return;
  10117. }
  10118. const [ social, type ] = value.split('.');
  10119. if (!whiteList?.[social]?.[type]) {
  10120. scripts_echoLog({}).warning(i18n('whiteListNotFound', value));
  10121. return;
  10122. }
  10123. external_Swal_default().fire({
  10124. title: i18n('changeWhiteListOption', value),
  10125. input: 'textarea',
  10126. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10127. <button id="link2id" data-type="${value}" class="swal2-confirm swal2-styled">获取id</button>
  10128. <p style="margin-bottom:0 !important;">在下方填写白名单,每行一个</p>`,
  10129. inputValue: whiteList[social][type].join('\n'),
  10130. showConfirmButton: true,
  10131. confirmButtonText: i18n('save'),
  10132. showCancelButton: true,
  10133. cancelButtonText: i18n('close'),
  10134. showDenyButton: true,
  10135. denyButtonText: i18n('return')
  10136. }).then(({
  10137. isDenied,
  10138. isConfirmed,
  10139. value
  10140. }) => {
  10141. if (isDenied) {
  10142. if (showType === 'swal') {
  10143. whiteListOptions(showType);
  10144. }
  10145. return;
  10146. } else if (isConfirmed) {
  10147. whiteList[social][type] = value.split('\n');
  10148. GM_setValue('whiteList', whiteList);
  10149. external_Swal_default().fire({
  10150. title: i18n('changeWhiteListSuccess'),
  10151. icon: 'success'
  10152. });
  10153. }
  10154. });
  10155. $('#link2id').on('click', async function() {
  10156. const type = $(this).attr('data-type');
  10157. $('#socialLink').val(await link2id(type));
  10158. });
  10159. });
  10160. } catch (error) {
  10161. throwError(error, 'whiteListOptions');
  10162. }
  10163. };
  10164. const whiteList = whiteListOptions;
  10165. const setGistData = async (token, gistId, fileName, content) => {
  10166. try {
  10167. const logStatus = scripts_echoLog({
  10168. text: i18n('settingData')
  10169. });
  10170. const contentData = JSON.stringify({
  10171. files: {
  10172. [fileName]: {
  10173. content: JSON.stringify(content)
  10174. }
  10175. }
  10176. });
  10177. const {
  10178. result,
  10179. statusText,
  10180. status,
  10181. data
  10182. } = await tools_httpRequest({
  10183. url: `https://api.github.com/gists/${gistId}`,
  10184. headers: {
  10185. Accept: 'application/vnd.github.v3+json',
  10186. Authorization: `token ${token}`
  10187. },
  10188. data: contentData,
  10189. responseType: 'json',
  10190. method: 'POST',
  10191. timeout: 3e4
  10192. });
  10193. if (result === 'Success') {
  10194. if (data?.status === 200 && data.response.files?.[fileName]?.content === JSON.stringify(content)) {
  10195. logStatus.success();
  10196. return true;
  10197. }
  10198. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10199. return false;
  10200. }
  10201. logStatus.error(`${result}:${statusText}(${status})`);
  10202. return false;
  10203. } catch (error) {
  10204. throwError(error, 'setGistData');
  10205. return false;
  10206. }
  10207. };
  10208. const getGistData = async (token, gistId, fileName, test = false) => {
  10209. try {
  10210. const logStatus = scripts_echoLog({
  10211. text: i18n('gettingData')
  10212. });
  10213. const {
  10214. result,
  10215. statusText,
  10216. status,
  10217. data
  10218. } = await tools_httpRequest({
  10219. url: `https://api.github.com/gists/${gistId}`,
  10220. headers: {
  10221. Accept: 'application/vnd.github.v3+json',
  10222. Authorization: `token ${token}`
  10223. },
  10224. responseType: 'json',
  10225. method: 'GET',
  10226. timeout: 3e4
  10227. });
  10228. if (result === 'Success') {
  10229. if (data?.status === 200) {
  10230. const content = data.response?.files?.[fileName]?.content;
  10231. let formatedContent;
  10232. if (!content) {
  10233. logStatus.error(`Error:${i18n('noRemoteData')}`);
  10234. return false;
  10235. }
  10236. if (test) {
  10237. logStatus.success();
  10238. return true;
  10239. }
  10240. try {
  10241. formatedContent = JSON.parse(content);
  10242. } catch (error) {
  10243. logStatus.error(`Error:${i18n('errorRemoteDataFormat')}`);
  10244. return false;
  10245. }
  10246. logStatus.success();
  10247. return formatedContent;
  10248. }
  10249. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10250. return false;
  10251. }
  10252. logStatus.error(`${result}:${statusText}(${status})`);
  10253. return false;
  10254. } catch (error) {
  10255. throwError(error, 'getGistData');
  10256. return false;
  10257. }
  10258. };
  10259. const syncOptions = () => {
  10260. try {
  10261. const {
  10262. TOKEN,
  10263. GIST_ID,
  10264. FILE_NAME,
  10265. SYNC_HISTORY
  10266. } = GM_getValue('gistOptions') || {
  10267. TOKEN: '',
  10268. GIST_ID: '',
  10269. FILE_NAME: '',
  10270. SYNC_HISTORY: true
  10271. };
  10272. external_Swal_default().fire({
  10273. title: i18n('gistOptions'),
  10274. 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;">
  10275. ${i18n('upload2gist')}</button>` + `<button id="download-data" type="button" class="swal2-confirm swal2-styled" style="display: inline-block;">
  10276. ${i18n('downloadFromGist')}</button></p>`,
  10277. focusConfirm: false,
  10278. showLoaderOnConfirm: true,
  10279. 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>`,
  10280. preConfirm: async () => {
  10281. const token = $('#github-token').val();
  10282. const gistId = $('#gist-id').val();
  10283. const fileName = $('#file-name').val();
  10284. const syncHistory = $('#sync-history').prop('checked');
  10285. GM_setValue('gistOptions', {
  10286. TOKEN: token,
  10287. GIST_ID: gistId,
  10288. FILE_NAME: fileName,
  10289. SYNC_HISTORY: syncHistory
  10290. });
  10291. return await getGistData(token, gistId, fileName, true);
  10292. },
  10293. allowOutsideClick: () => !external_Swal_default().isLoading(),
  10294. confirmButtonText: i18n('saveAndTest'),
  10295. showCancelButton: true,
  10296. cancelButtonText: i18n('close')
  10297. }).then(({
  10298. value
  10299. }) => {
  10300. if (value) {
  10301. external_Swal_default().fire({
  10302. icon: 'success',
  10303. title: i18n('testSuccess')
  10304. }).then(syncOptions);
  10305. } else if (value !== undefined) {
  10306. external_Swal_default().fire({
  10307. icon: 'error',
  10308. title: i18n('testFailed')
  10309. }).then(syncOptions);
  10310. }
  10311. });
  10312. $('#upload-data').on('click', async () => {
  10313. const {
  10314. TOKEN,
  10315. GIST_ID,
  10316. FILE_NAME
  10317. } = GM_getValue('gistOptions') || {};
  10318. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10319. return external_Swal_default().fire({
  10320. icon: 'error',
  10321. title: i18n('saveAndTestNotice')
  10322. }).then(syncOptions);
  10323. }
  10324. external_Swal_default().fire({
  10325. icon: 'info',
  10326. title: i18n('processingData')
  10327. });
  10328. const data = {};
  10329. const names = GM_listValues();
  10330. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10331. for (const name of names) {
  10332. if (name === 'gistOptions' || /^[\w]+?Auth$/.test(name)) {
  10333. continue;
  10334. }
  10335. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10336. continue;
  10337. }
  10338. data[name] = GM_getValue(name);
  10339. }
  10340. external_Swal_default().update({
  10341. icon: 'info',
  10342. title: i18n('updatingData')
  10343. });
  10344. if (await setGistData(TOKEN, GIST_ID, FILE_NAME, data)) {
  10345. external_Swal_default().fire({
  10346. icon: 'success',
  10347. title: i18n('syncDataSuccess')
  10348. });
  10349. } else {
  10350. external_Swal_default().fire({
  10351. icon: 'error',
  10352. title: i18n('syncDataFailed')
  10353. });
  10354. }
  10355. });
  10356. $('#download-data').on('click', async () => {
  10357. const {
  10358. TOKEN,
  10359. GIST_ID,
  10360. FILE_NAME
  10361. } = GM_getValue('gistOptions') || {};
  10362. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10363. return external_Swal_default().fire({
  10364. icon: 'error',
  10365. title: i18n('saveAndTestNotice')
  10366. }).then(syncOptions);
  10367. }
  10368. external_Swal_default().fire({
  10369. icon: 'info',
  10370. title: i18n('downloadingData')
  10371. });
  10372. const data = await getGistData(TOKEN, GIST_ID, FILE_NAME);
  10373. if (!data) {
  10374. return external_Swal_default().fire({
  10375. icon: 'error',
  10376. title: i18n('checkedNoData')
  10377. }).then(syncOptions);
  10378. }
  10379. external_Swal_default().update({
  10380. icon: 'info',
  10381. title: i18n('savingData')
  10382. });
  10383. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10384. for (const [ name, value ] of Object.entries(data)) {
  10385. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10386. continue;
  10387. }
  10388. GM_setValue(name, value);
  10389. }
  10390. external_Swal_default().fire({
  10391. icon: 'success',
  10392. title: i18n('syncDataSuccess')
  10393. });
  10394. });
  10395. } catch (error) {
  10396. throwError(error, 'syncOptions');
  10397. }
  10398. };
  10399. const dataSync = syncOptions;
  10400. class Setting {
  10401. name = 'Setting';
  10402. buttons = [ 'saveGlobalOptions', 'syncData', 'tasksHistory' ];
  10403. syncData = dataSync;
  10404. tasksHistory() {
  10405. GM_openInTab('https://auto-task-v4.hclonely.com/history.html', {
  10406. active: true
  10407. });
  10408. }
  10409. static test() {
  10410. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/setting.html';
  10411. }
  10412. before() {
  10413. try {
  10414. $('body').html('').addClass('auto-task-options');
  10415. } catch (error) {
  10416. throwError(error, 'Setting.before');
  10417. }
  10418. }
  10419. after() {
  10420. try {
  10421. this.#environment();
  10422. changeGlobalOptions('page');
  10423. whiteList('page');
  10424. $('input[name="other.twitterVerifyId"]').after(`<button id="getTwitterUserId" type="button">${i18n('getTwitterUserId')}</button>`);
  10425. $('#getTwitterUserId').on('click', () => {
  10426. this.#getId('twitterUser');
  10427. });
  10428. $('input[name="other.youtubeVerifyChannel"]').after(`<button id="getYoutubeChannelId" type="button">${i18n('getYoutubeChannelId')}</button>`);
  10429. $('#getYoutubeChannelId').on('click', () => {
  10430. this.#getId('youtubeChannel');
  10431. });
  10432. $('input[name^="position"]').on('input', function() {
  10433. const type = $(this).attr('name').replace('position.', '');
  10434. const xLabel = 'rightleft';
  10435. const yLabel = 'topbottpm';
  10436. switch (type) {
  10437. case 'buttonSideX':
  10438. case 'buttonSideY':
  10439. case 'buttonDistance':
  10440. {
  10441. const distance = $('input[name="position.buttonDistance"]').val();
  10442. const sideX = $('input[name="position.buttonSideX"]').val();
  10443. const sideY = $('input[name="position.buttonSideY"]').val();
  10444. if (![ 'right', 'left' ].includes(sideX)) {
  10445. break;
  10446. }
  10447. if (![ 'top', 'bottom' ].includes(sideY)) {
  10448. break;
  10449. }
  10450. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10451. break;
  10452. }
  10453. const distanceArr = distance.split(',');
  10454. $('#auto-task-buttons').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10455. break;
  10456. }
  10457.  
  10458. case 'showButtonSideX':
  10459. case 'showButtonSideY':
  10460. case 'showButtonDistance':
  10461. {
  10462. const distance = $('input[name="position.showButtonDistance"]').val();
  10463. const sideX = $('input[name="position.showButtonSideX"]').val();
  10464. const sideY = $('input[name="position.showButtonSideY"]').val();
  10465. if (![ 'right', 'left' ].includes(sideX)) {
  10466. break;
  10467. }
  10468. if (![ 'top', 'bottom' ].includes(sideY)) {
  10469. break;
  10470. }
  10471. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10472. break;
  10473. }
  10474. const distanceArr = distance.split(',');
  10475. $('div.show-button-div').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10476. break;
  10477. }
  10478.  
  10479. case 'logSideX':
  10480. case 'logSideY':
  10481. case 'logDistance':
  10482. {
  10483. const distance = $('input[name="position.logDistance"]').val();
  10484. const sideX = $('input[name="position.logSideX"]').val();
  10485. const sideY = $('input[name="position.logSideY"]').val();
  10486. if (![ 'right', 'left' ].includes(sideX)) {
  10487. break;
  10488. }
  10489. if (![ 'top', 'bottom' ].includes(sideY)) {
  10490. break;
  10491. }
  10492. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  10493. break;
  10494. }
  10495. const distanceArr = distance.split(',');
  10496. $('#auto-task-info').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  10497. break;
  10498. }
  10499.  
  10500. default:
  10501. break;
  10502. }
  10503. });
  10504. $('input[name^="hotKey"]').attr('readonly', 'readonly').off('keydown').on('keydown', function(event) {
  10505. let functionKey = '';
  10506. if (event.altKey) {
  10507. functionKey += 'alt + ';
  10508. } else if (event.ctrlKey) {
  10509. functionKey += 'ctrl + ';
  10510. } else if (event.shiftKey) {
  10511. functionKey += 'shift + ';
  10512. }
  10513. $(this).val(functionKey + (event.key.length === 1 ? event.key.toLowerCase() : ''));
  10514. });
  10515. } catch (error) {
  10516. throwError(error, 'Setting.after');
  10517. }
  10518. }
  10519. saveGlobalOptions() {
  10520. try {
  10521. saveData();
  10522. } catch (error) {
  10523. throwError(error, 'Setting.saveGlobalOptions');
  10524. }
  10525. }
  10526. #getId(social) {
  10527. try {
  10528. external_Swal_default().fire({
  10529. title: i18n('getId', i18n(social)),
  10530. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10531. <button id="link2id" data-type="${social}" class="swal2-confirm swal2-styled">获取id</button>`,
  10532. showCancelButton: true,
  10533. cancelButtonText: i18n('close'),
  10534. showConfirmButton: false
  10535. });
  10536. $('#link2id').on('click', async function() {
  10537. const link = $('#socialLink').val();
  10538. if (!link) {
  10539. return;
  10540. }
  10541. const type = $(this).attr('data-type');
  10542. if (type === 'twitterUser') {
  10543. const name = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || link;
  10544. $('#socialLink').val(await new social_Twitter().userName2id(name) || '');
  10545. } else if (type === 'youtubeChannel') {
  10546. const name = /^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www.youtube.com\/.*/.test(link) ? link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1] : link;
  10547. $('#socialLink').val((await getInfo(name, 'channel'))?.params?.channelId || '');
  10548. }
  10549. });
  10550. } catch (error) {
  10551. throwError(error, 'Setting.getId');
  10552. }
  10553. }
  10554. #environment() {
  10555. try {
  10556. const userAgent = (0, javascript_utils_umd_min.ua)();
  10557. const environmentForm = `<form id="environmentForm" class="auto-task-form">
  10558. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('name')}</td><td>${i18n('version')}</td></tr></thead><tbody>
  10559. <tr><td>${i18n('os')}</td><td>${userAgent.os}</td><td>${userAgent.osVersion}</td></tr>
  10560. <tr><td>${i18n('browser')}</td><td>${userAgent.browserZH}</td><td>${userAgent.browserVersion}</td></tr>
  10561. <tr><td>${i18n('scriptManager')}</td><td>${GM_info.scriptHandler}</td><td>${GM_info.version}</td></tr>
  10562. <tr><td>${i18n('script')}</td><td>${GM_info.script.name}</td><td>${GM_info.script.version}</td></tr>
  10563. </tbody></table></form>`;
  10564. $('body').append(`<h2>${i18n('environment')}</h2>${environmentForm}`);
  10565. } catch (error) {
  10566. throwError(error, 'Setting.environment');
  10567. }
  10568. }
  10569. }
  10570. const website_Setting = Setting;
  10571. class History extends website_Keylol {
  10572. name = 'History';
  10573. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect', 'clearHistory' ];
  10574. static test() {
  10575. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/history.html';
  10576. }
  10577. before() {
  10578. try {
  10579. $('body').html('<div class="container"></div>').addClass('auto-task-history');
  10580. const data = GM_listValues() || [];
  10581. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  10582. for (const item of tasksHistory) {
  10583. this.#addItem(item);
  10584. }
  10585. } catch (error) {
  10586. throwError(error, 'History.before');
  10587. }
  10588. }
  10589. clearHistory() {
  10590. try {
  10591. const data = GM_listValues() || [];
  10592. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  10593. for (const item of tasksHistory) {
  10594. GM_deleteValue(item);
  10595. }
  10596. external_Swal_default().fire({
  10597. title: i18n('clearHistoryFinished'),
  10598. icon: 'success'
  10599. });
  10600. } catch (error) {
  10601. throwError(error, 'History.clearHistory');
  10602. }
  10603. }
  10604. #addItem(item) {
  10605. try {
  10606. const tasksData = GM_getValue(item);
  10607. if (!tasksData?.tasks) {
  10608. return;
  10609. }
  10610. let html = '';
  10611. let title = '';
  10612. let link = '';
  10613. const [ website, id ] = item.split('-');
  10614. switch (website) {
  10615. case 'fawTasks':
  10616. title = `Freeanywhere[${id}]`;
  10617. link = `https://freeanywhere.net/#/giveaway/${id}`;
  10618. break;
  10619.  
  10620. case 'gasTasks':
  10621. title = `Giveawaysu[${id}]`;
  10622. link = `https://giveaway.su/giveaway/view/${id}`;
  10623. break;
  10624.  
  10625. case 'gcTasks':
  10626. title = `GiveeClub[${id}]`;
  10627. link = `https://givee.club/event/${id}`;
  10628. break;
  10629.  
  10630. case 'gkTasks':
  10631. title = `Givekey[${id}]`;
  10632. link = `https://givekey.ru/giveaway/${id}`;
  10633. break;
  10634.  
  10635. case 'gleamTasks':
  10636. title = `Gleam[${id}]`;
  10637. link = `https://gleam.io${id}`;
  10638. break;
  10639.  
  10640. case 'khTasks':
  10641. title = `keyhub[${id}]`;
  10642. link = `https://key-hub.eu/giveaway/${id}`;
  10643. break;
  10644.  
  10645. case 'prysTasks':
  10646. title = `Prys[${id}]`;
  10647. link = `https://prys.revadike.com/giveaway/?id=${id}`;
  10648. break;
  10649.  
  10650. default:
  10651. return;
  10652. }
  10653. for (const [ social, types ] of Object.entries(tasksData.tasks)) {
  10654. for (const [ type, tasks ] of Object.entries(types)) {
  10655. for (const task of tasks) {
  10656. 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>`;
  10657. }
  10658. }
  10659. }
  10660. $('.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>`);
  10661. $('span.delete-task').on('click', function() {
  10662. const itemName = $(this).attr('data-name');
  10663. if (itemName) {
  10664. GM_deleteValue(itemName);
  10665. $(`div.card[data-name="${itemName}"]`).remove();
  10666. external_Swal_default().fire({
  10667. title: i18n('clearTaskFinished'),
  10668. text: itemName,
  10669. icon: 'success'
  10670. });
  10671. } else {
  10672. external_Swal_default().fire({
  10673. title: i18n('clearTaskFailed'),
  10674. icon: 'error'
  10675. });
  10676. }
  10677. });
  10678. } catch (error) {
  10679. throwError(error, 'History.addItem');
  10680. }
  10681. }
  10682. }
  10683. const website_History = History;
  10684. const GiveawayHopper_defaultTasksTemplate = {
  10685. steam: {
  10686. groupLinks: [],
  10687. wishlistLinks: [],
  10688. followLinks: [],
  10689. curatorLinks: [],
  10690. curatorLikeLinks: []
  10691. },
  10692. twitter: {
  10693. userLinks: [],
  10694. retweetLinks: []
  10695. },
  10696. twitch: {
  10697. channelLinks: []
  10698. },
  10699. discord: {
  10700. serverLinks: []
  10701. },
  10702. youtube: {
  10703. channelLinks: []
  10704. },
  10705. extra: {
  10706. giveawayHopper: []
  10707. }
  10708. };
  10709. const GiveawayHopper_defaultTasks = JSON.stringify(GiveawayHopper_defaultTasksTemplate);
  10710. class GiveawayHopper extends website_Website {
  10711. name = 'GiveawayHopper';
  10712. undoneTasks = JSON.parse(GiveawayHopper_defaultTasks);
  10713. socialTasks = JSON.parse(GiveawayHopper_defaultTasks);
  10714. tasks = [];
  10715. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  10716. static test() {
  10717. return window.location.host === 'giveawayhopper.com';
  10718. }
  10719. async after() {
  10720. try {
  10721. if (!this.#checkLogin()) {
  10722. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  10723. }
  10724. this.#getGiveawayId();
  10725. } catch (error) {
  10726. throwError(error, 'GiveawayHopper.after');
  10727. }
  10728. }
  10729. async init() {
  10730. try {
  10731. const logStatus = scripts_echoLog({
  10732. text: i18n('initing')
  10733. });
  10734. if (!await this.#checkLeftKey()) {
  10735. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  10736. }
  10737. this.initialized = true;
  10738. logStatus.success();
  10739. return true;
  10740. } catch (error) {
  10741. throwError(error, 'GiveawayHopper.init');
  10742. return false;
  10743. }
  10744. }
  10745. async classifyTask(action) {
  10746. try {
  10747. if (!this.giveawayId) {
  10748. await this.#getGiveawayId();
  10749. }
  10750. const logStatus = scripts_echoLog({
  10751. text: i18n('getTasksInfo')
  10752. });
  10753. if (action === 'undo') {
  10754. this.socialTasks = GM_getValue(`giveawayHopperTasks-${this.giveawayId}`)?.tasks || JSON.parse(GiveawayHopper_defaultTasks);
  10755. }
  10756. const {
  10757. result,
  10758. statusText,
  10759. status,
  10760. data
  10761. } = await tools_httpRequest({
  10762. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/with-auth`,
  10763. method: 'GET',
  10764. responseType: 'json',
  10765. fetch: true,
  10766. headers: {
  10767. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10768. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10769. }
  10770. });
  10771. if (result === 'Success') {
  10772. if (data?.status === 200 && data?.response?.tasks) {
  10773. this.tasks = data.response.tasks;
  10774. for (const task of data.response.tasks) {
  10775. if (task.isDone) {
  10776. continue;
  10777. }
  10778. await tools_httpRequest({
  10779. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/visited`,
  10780. method: 'GET',
  10781. responseType: 'json',
  10782. fetch: true,
  10783. headers: {
  10784. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10785. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10786. }
  10787. });
  10788. if (task.category === 'Steam' && task.type === 'JoinGroup') {
  10789. const steamGroupLink = await getRedirectLink(`https://steamcommunity.com/gid/${task.group_id}`);
  10790. if (!steamGroupLink) {
  10791. continue;
  10792. }
  10793. if (action === 'undo') {
  10794. this.socialTasks.steam.groupLinks.push(steamGroupLink);
  10795. }
  10796. if (action === 'do') {
  10797. this.undoneTasks.steam.groupLinks.push(steamGroupLink);
  10798. }
  10799. continue;
  10800. }
  10801. if (task.category === 'Discord' && task.type === 'JoinServer') {
  10802. if (action === 'undo') {
  10803. this.socialTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  10804. }
  10805. if (action === 'do') {
  10806. this.undoneTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  10807. }
  10808. continue;
  10809. }
  10810. if ([ 'TikTok', 'YouTube', 'General' ].includes(task.category)) {
  10811. continue;
  10812. }
  10813. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${task.category}-${task.type}`);
  10814. }
  10815. logStatus.success();
  10816. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  10817. this.socialTasks = this.uniqueTasks(this.socialTasks);
  10818. if (window.DEBUG) {
  10819. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  10820. }
  10821. GM_setValue(`giveawayHopperTasks-${this.giveawayId}`, {
  10822. tasks: this.socialTasks,
  10823. time: new Date().getTime()
  10824. });
  10825. return true;
  10826. }
  10827. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10828. return false;
  10829. }
  10830. logStatus.error(`${result}:${statusText}(${status})`);
  10831. return false;
  10832. } catch (error) {
  10833. throwError(error, 'GiveawayHopper.classifyTask');
  10834. return false;
  10835. }
  10836. }
  10837. async verifyTask() {
  10838. try {
  10839. for (const task of this.tasks) {
  10840. if (task.isDone) {
  10841. continue;
  10842. }
  10843. const logStatus = scripts_echoLog({
  10844. text: `${i18n('verifyingTask')}[${task.displayName?.replace(':target', task.targetName) || task.name}]...`
  10845. });
  10846. if (!task.link) {
  10847. if (task.category === 'YouTube' && task.type === 'FollowAccount') {
  10848. task.link = `https://www.youtube.com/@${task.targetName}`;
  10849. } else if (task.category === 'TikTok' && task.type === 'FollowAccount') {
  10850. task.link = `https://www.tiktok.com/@${task.targetName}`;
  10851. } else if (task.category === 'Steam' && task.type === 'JoinGroup') {
  10852. task.link = '';
  10853. } else if (task.category === 'Discord' && task.type === 'JoinServer') {
  10854. task.link = '';
  10855. }
  10856. }
  10857. if (task.link) {
  10858. await tools_httpRequest({
  10859. 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}`,
  10860. method: 'GET',
  10861. fetch: true,
  10862. headers: {
  10863. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10864. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  10865. }
  10866. });
  10867. }
  10868. await delay(1e3);
  10869. const postData = {
  10870. taskcategory: task.category,
  10871. taskname: task.type
  10872. };
  10873. if ([ 'YouTube', 'TikTok' ].includes(task.category)) {
  10874. postData.username = '1';
  10875. }
  10876. const {
  10877. result,
  10878. statusText,
  10879. status,
  10880. data
  10881. } = await tools_httpRequest({
  10882. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/complete`,
  10883. method: 'POST',
  10884. fetch: true,
  10885. headers: {
  10886. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  10887. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1]),
  10888. 'content-type': 'application/json'
  10889. },
  10890. dataType: 'json',
  10891. data: JSON.stringify(postData)
  10892. });
  10893. if (result === 'Success') {
  10894. if (data?.status === 200 && data?.response?.completed) {
  10895. logStatus.success();
  10896. continue;
  10897. }
  10898. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10899. continue;
  10900. }
  10901. logStatus.error(`${result}:${statusText}(${status})`);
  10902. continue;
  10903. }
  10904. } catch (error) {
  10905. throwError(error, 'GiveawayHopper.verifyTask');
  10906. return false;
  10907. }
  10908. }
  10909. #getGiveawayId() {
  10910. try {
  10911. const giveawayId = window.location.pathname.split('/').at(-1);
  10912. if (giveawayId) {
  10913. this.giveawayId = giveawayId;
  10914. return true;
  10915. }
  10916. scripts_echoLog({
  10917. text: i18n('getFailed', 'GiveawayId')
  10918. });
  10919. return false;
  10920. } catch (error) {
  10921. throwError(error, 'GiveawayHopper.getGiveawayId');
  10922. return false;
  10923. }
  10924. }
  10925. #checkLogin() {
  10926. try {
  10927. if (!globalOptions.other.checkLogin) {
  10928. return true;
  10929. }
  10930. if ($('div.widget-connections-edit:contains("Log in")').length > 0) {
  10931. $('div.widget-connections-edit:contains("Log in") a')[0].click();
  10932. }
  10933. return true;
  10934. } catch (error) {
  10935. throwError(error, 'GiveawayHopper.checkLogin');
  10936. return false;
  10937. }
  10938. }
  10939. async #checkLeftKey() {
  10940. try {
  10941. if (!globalOptions.other.checkLeftKey) {
  10942. return true;
  10943. }
  10944. if ($('p.widget-single-prize span').length > 0 && parseInt($('p.widget-single-prize span').text()?.match(/\d+/)?.[0] || '0', 10) > 0) {
  10945. return true;
  10946. }
  10947. await external_Swal_default().fire({
  10948. icon: 'warning',
  10949. title: i18n('notice'),
  10950. text: i18n('noKeysLeft'),
  10951. confirmButtonText: i18n('confirm'),
  10952. cancelButtonText: i18n('cancel'),
  10953. showCancelButton: true
  10954. }).then(({
  10955. value
  10956. }) => {
  10957. if (value) {
  10958. window.close();
  10959. }
  10960. });
  10961. return true;
  10962. } catch (error) {
  10963. throwError(error, 'GiveawayHopper.checkLeftKey');
  10964. return false;
  10965. }
  10966. }
  10967. }
  10968. const website_GiveawayHopper = GiveawayHopper;
  10969. 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 ];
  10970. const websiteOptions = function(website, options) {
  10971. try {
  10972. let websiteOptionsForm = `<form id="websiteOptionsForm" class="auto-task-form">
  10973. <table class="auto-task-table"><thead><tr><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  10974. for (const [ option, value ] of Object.entries(options)) {
  10975. websiteOptionsForm += `<tr><td>${option}</td><td><input class="editOption" type="text" name="${option}" value="${value}"/></td></tr>`;
  10976. }
  10977. websiteOptionsForm += '</tbody></table></form>';
  10978. external_Swal_default().fire({
  10979. title: i18n('websiteOptions'),
  10980. html: websiteOptionsForm,
  10981. showConfirmButton: true,
  10982. confirmButtonText: i18n('save'),
  10983. showCancelButton: true,
  10984. cancelButtonText: i18n('close')
  10985. }).then(({
  10986. isConfirmed
  10987. }) => {
  10988. if (isConfirmed) {
  10989. $('#websiteOptionsForm').serializeArray().map(value => {
  10990. options[value.name] = value.value;
  10991. return value;
  10992. });
  10993. GM_setValue(`${website}Options`, options);
  10994. external_Swal_default().fire({
  10995. title: i18n('changeWebsiteOptionsSuccess'),
  10996. icon: 'success'
  10997. });
  10998. }
  10999. });
  11000. } catch (error) {
  11001. throwError(error, 'websiteOptions');
  11002. }
  11003. };
  11004. const options = websiteOptions;
  11005. const external_keyboardJS_namespaceObject = keyboardJS;
  11006. var external_keyboardJS_default = __webpack_require__.n(external_keyboardJS_namespaceObject);
  11007. const checkUpdate = async (updateLink, auto) => {
  11008. try {
  11009. const checkUrl = `${updateLink}package.json?time=${new Date().getTime()}`;
  11010. const {
  11011. result,
  11012. statusText,
  11013. status,
  11014. data
  11015. } = await tools_httpRequest({
  11016. url: checkUrl,
  11017. responseType: 'json',
  11018. method: 'GET',
  11019. timeout: 3e4
  11020. });
  11021. if (result === 'Success') {
  11022. if (data?.response?.version) {
  11023. return data.response;
  11024. }
  11025. if (!auto) {
  11026. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${data?.statusText}(${data?.status})]`);
  11027. }
  11028. return false;
  11029. }
  11030. if (!auto) {
  11031. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${result}:${statusText}(${status})]`);
  11032. }
  11033. return false;
  11034. } catch (error) {
  11035. throwError(error, 'checkUpdate');
  11036. return false;
  11037. }
  11038. };
  11039. const hasNewVersion = (currentVersion, remoteVersion) => {
  11040. try {
  11041. const [ currentRealVersion ] = currentVersion.split('-');
  11042. const [ remoteRealVersion, isPreview ] = remoteVersion.split('-');
  11043. if (isPreview && !globalOptions.other.receivePreview) {
  11044. return false;
  11045. }
  11046. const [ currentVersion1, currentVersion2, currentVersion3 ] = currentRealVersion.split('.').map(value => parseInt(value, 10));
  11047. const [ remoteVersion1, remoteVersion2, remoteVersion3 ] = remoteRealVersion.split('.').map(value => parseInt(value, 10));
  11048. if (remoteVersion1 > currentVersion1) {
  11049. return true;
  11050. }
  11051. if (remoteVersion1 < currentVersion1) {
  11052. return false;
  11053. }
  11054. if (remoteVersion2 > currentVersion2) {
  11055. return true;
  11056. }
  11057. if (remoteVersion2 < currentVersion2) {
  11058. return false;
  11059. }
  11060. if (remoteVersion3 > currentVersion3) {
  11061. return true;
  11062. }
  11063. return false;
  11064. } catch (error) {
  11065. throwError(error, 'compareVersion');
  11066. return false;
  11067. }
  11068. };
  11069. const updateChecker = async () => {
  11070. try {
  11071. const currentVersion = GM_info.script.version;
  11072. const updateSource = globalOptions.other.autoUpdateSource.toLowerCase();
  11073. const updateLinks = {
  11074. github: 'https://github.com/HCLonely/auto-task-new/raw/main/',
  11075. jsdelivr: 'https://cdn.jsdelivr.net/gh/HCLonely/auto-task-v4@main/',
  11076. standby: 'https://auto-task-v4.hclonely.com/'
  11077. };
  11078. let version;
  11079. let updateLink = '';
  11080. let packageData;
  11081. if ([ 'github', 'jsdelivr', 'standby' ].includes(updateSource)) {
  11082. updateLink = updateLinks[updateSource];
  11083. packageData = await checkUpdate(updateLink, false);
  11084. } else {
  11085. updateLink = updateLinks.github;
  11086. packageData = await checkUpdate(updateLink, true);
  11087. if (!packageData) {
  11088. updateLink = updateLinks.jsdelivr;
  11089. packageData = await checkUpdate(updateLink, true);
  11090. if (!packageData) {
  11091. updateLink = updateLinks.standby;
  11092. packageData = await checkUpdate(updateLink, true);
  11093. }
  11094. }
  11095. }
  11096. if (packageData) {
  11097. version = packageData.version || currentVersion;
  11098. } else {
  11099. version = currentVersion;
  11100. scripts_echoLog({}).error(i18n('checkUpdateFailed'));
  11101. }
  11102. if (packageData && hasNewVersion(currentVersion, version)) {
  11103. scripts_echoLog({
  11104. html: `<li><font>${i18n('newVersionNotice', version, `${updateLink}dist/${GM_info.script.name}.user.js`)}</font></li>`
  11105. });
  11106. scripts_echoLog({
  11107. html: `<li>${i18n('updateText', version)}</li><ol class="update-text">${packageData.change?.map(change => `<li>${change}</li>`).join('')}<li>${i18n('updateHistory')}</li></ol>`
  11108. });
  11109. }
  11110. } catch (error) {
  11111. throwError(error, 'updateChecker');
  11112. }
  11113. };
  11114. const scripts_updateChecker = updateChecker;
  11115. window.STYLE = GM_addStyle(auto_task.A + GM_getResourceText('style'));
  11116. window.DEBUG = !!globalOptions.other?.debug;
  11117. window.TRACE = !!globalOptions.other?.debug && typeof console.trace === 'function';
  11118. const loadScript = async () => {
  11119. if (window.name === 'ATv4_twitchAuth' && window.location.hostname === 'www.twitch.tv') {
  11120. const authToken = external_Cookies_default().get('auth-token');
  11121. const isLogin = !!external_Cookies_default().get('login');
  11122. if (isLogin) {
  11123. GM_setValue('twitchAuth', {
  11124. authToken: authToken,
  11125. clientVersion: __twilightBuildID,
  11126. clientId: commonOptions?.headers?.['Client-ID'],
  11127. deviceId: commonOptions?.headers?.['Device-ID'],
  11128. clientSessionId: window.localStorage.local_storage_app_session_id.replace(/"/g, '')
  11129. });
  11130. window.close();
  11131. external_Swal_default().fire('', i18n('closePageNotice'));
  11132. } else {
  11133. external_Swal_default().fire('', i18n('needLogin'));
  11134. }
  11135. return;
  11136. }
  11137. if (window.name === 'ATv4_redditAuth' && window.location.hostname === 'www.reddit.com') {
  11138. const betaButton = $('#redesign-beta-optin-btn');
  11139. if (betaButton.length > 0) {
  11140. return betaButton[0].click();
  11141. }
  11142. window.close();
  11143. external_Swal_default().fire('', i18n('closePageNotice'));
  11144. return;
  11145. }
  11146. let website;
  11147. for (const Website of Websites) {
  11148. if (Website.test()) {
  11149. website = new Website();
  11150. break;
  11151. }
  11152. }
  11153. if (!website) {
  11154. console.log('%c%s', 'color:#ff0000', 'Auto-Task[Warning]: 脚本停止加载,当前网站不支持!');
  11155. return;
  11156. }
  11157. if (website?.before) {
  11158. await website?.before();
  11159. }
  11160. $('body').append(`
  11161. <div id="auto-task-info"
  11162. style="display:${globalOptions.other.defaultShowLog ? 'block' : 'none'};
  11163. ${globalOptions.position.logSideX}:${globalOptions.position.logDistance.split(',')[0]}px;
  11164. ${globalOptions.position.logSideY}:${globalOptions.position.logDistance.split(',')[1]}px;">
  11165. </div>
  11166. <div id="auto-task-buttons"
  11167. style="display:${globalOptions.other.defaultShowButton ? 'block' : 'none'};
  11168. ${globalOptions.position.buttonSideX}:${globalOptions.position.buttonDistance.split(',')[0]}px;
  11169. ${globalOptions.position.buttonSideY}:${globalOptions.position.buttonDistance.split(',')[1]}px;">
  11170. </div>
  11171. <div class="show-button-div"
  11172. style="display:${globalOptions.other.defaultShowButton ? 'none' : 'block'};
  11173. ${globalOptions.position.showButtonSideX}:${globalOptions.position.showButtonDistance.split(',')[0]}px;
  11174. ${globalOptions.position.showButtonSideY}:${globalOptions.position.showButtonDistance.split(',')[1]}px;">
  11175. <a class="auto-task-website-btn"
  11176. href="javascript:void(0);"
  11177. target="_self"
  11178. title="${i18n('showButton')}"> </a>
  11179. </div>
  11180. `);
  11181. $('div.show-button-div').on('click', () => {
  11182. $('#auto-task-buttons').show();
  11183. $('div.show-button-div').hide();
  11184. });
  11185. const toggleLog = () => {
  11186. const $this = $('#toggle-log');
  11187. const status = $this.attr('data-status');
  11188. if (status === 'show') {
  11189. $('#auto-task-info').hide();
  11190. $this.attr('data-status', 'hide').text(i18n('showLog'));
  11191. } else {
  11192. $('#auto-task-info').show();
  11193. $this.attr('data-status', 'show').text(i18n('hideLog'));
  11194. }
  11195. };
  11196. external_keyboardJS_default().bind(globalOptions.hotKey.doTaskKey, () => {
  11197. if (website.doTask) {
  11198. website.doTask();
  11199. }
  11200. });
  11201. external_keyboardJS_default().bind(globalOptions.hotKey.undoTaskKey, () => {
  11202. if (website.undoTask) {
  11203. website.undoTask();
  11204. }
  11205. });
  11206. external_keyboardJS_default().bind(globalOptions.hotKey.toggleLogKey, toggleLog);
  11207. if (website?.after) {
  11208. await website?.after();
  11209. }
  11210. if (website?.buttons && $('#auto-task-buttons').children().length === 0) {
  11211. $('#auto-task-buttons').addClass(`${website.name}-buttons`);
  11212. for (const button of website.buttons) {
  11213. if (website[button]) {
  11214. const btnElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">${i18n(button)}</a></p>`);
  11215. btnElement.find('a.auto-task-website-btn').on('click', () => {
  11216. website[button]();
  11217. });
  11218. $('#auto-task-buttons').append(btnElement);
  11219. }
  11220. }
  11221. }
  11222. const hideButtonElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">
  11223. ${i18n('hideButton')}</a></p>`);
  11224. hideButtonElement.find('a.auto-task-website-btn').on('click', () => {
  11225. $('#auto-task-buttons').hide();
  11226. $('div.show-button-div').show();
  11227. });
  11228. 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'}">
  11229. ${globalOptions.other.defaultShowLog ? i18n('hideLog') : i18n('showLog')}</a></p>`);
  11230. toggleLogElement.find('a.auto-task-website-btn').on('click', toggleLog);
  11231. $('#auto-task-buttons').append(hideButtonElement).append(toggleLogElement);
  11232. if (website?.options) {
  11233. GM_registerMenuCommand(i18n('changeWebsiteOptions'), () => {
  11234. options(website.name, website.options);
  11235. });
  11236. }
  11237. if (website.name !== 'Setting') {
  11238. GM_registerMenuCommand(i18n('changeGlobalOptions'), () => {
  11239. changeGlobalOptions('swal');
  11240. });
  11241. GM_registerMenuCommand(i18n('settingPage'), () => {
  11242. GM_openInTab('https://auto-task-v4.hclonely.com/setting.html', {
  11243. active: true
  11244. });
  11245. });
  11246. }
  11247. console.log('%c%s', 'color:#1bbe1a', 'Auto-Task[Load]: 脚本加载完成');
  11248. const [ v1, v2 ] = GM_info.version.split('.');
  11249. if (!(parseInt(v1, 10) >= 5 && parseInt(v2, 10) >= 2)) {
  11250. scripts_echoLog({}).error(i18n('versionNotMatched'));
  11251. }
  11252. if (!GM_getValue('notice')) {
  11253. external_Swal_default().fire({
  11254. title: i18n('swalNotice'),
  11255. icon: 'warning'
  11256. }).then(() => {
  11257. GM_openInTab(i18n('noticeLink'), {
  11258. active: true
  11259. });
  11260. GM_setValue('notice', new Date().getTime());
  11261. });
  11262. scripts_echoLog({
  11263. html: `<li><font class="warning">${i18n('echoNotice', i18n('noticeLink'))}</font></li>`
  11264. }).font?.find('a').on('click', () => {
  11265. GM_setValue('notice', new Date().getTime());
  11266. });
  11267. }
  11268. scripts_updateChecker();
  11269. };
  11270. if (window.location.hostname === 'discord.com') {
  11271. const LocalStorage = window.localStorage;
  11272. if (window.name === 'ATv4_discordAuth') {
  11273. window.localStorage.removeItem = () => true;
  11274. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11275. if (discordAuth && discordAuth.length > 0) {
  11276. GM_setValue('discordAuth', {
  11277. auth: discordAuth
  11278. });
  11279. window.close();
  11280. external_Swal_default().fire('', i18n('closePageNotice'));
  11281. } else {
  11282. external_Swal_default().fire({
  11283. text: i18n('getDiscordAuthFailed'),
  11284. icon: 'error'
  11285. });
  11286. }
  11287. } else {
  11288. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11289. if (discordAuth && discordAuth.length > 0) {
  11290. GM_setValue('discordAuth', {
  11291. auth: discordAuth
  11292. });
  11293. }
  11294. }
  11295. } else if (window.location.hostname === 'opquests.com') {
  11296. loadScript();
  11297. } else if ((window.name === 'ATv4_updateStoreAuth' || GM_getValue('ATv4_updateStoreAuth')) && window.location.host === 'store.steampowered.com') {
  11298. $(() => {
  11299. if ($('[data-miniprofile]').length === 0) {
  11300. return;
  11301. }
  11302. const storeSessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11303. if (storeSessionID) {
  11304. GM_deleteValue('ATv4_updateStoreAuth');
  11305. GM_setValue('steamStoreAuth', {
  11306. storeSessionID: storeSessionID
  11307. });
  11308. window.close();
  11309. external_Swal_default().fire('', i18n('closePageNotice'));
  11310. } else {
  11311. external_Swal_default().fire({
  11312. title: 'Error: Get "sessionID" failed',
  11313. icon: 'error'
  11314. });
  11315. }
  11316. });
  11317. } else if ((window.name === 'ATv4_updateCommunityAuth' || GM_getValue('ATv4_updateCommunityAuth')) && window.location.host === 'steamcommunity.com') {
  11318. $(() => {
  11319. const steam64Id = document.body.innerHTML.match(/g_steamID = "(.+?)";/)?.[1];
  11320. const communitySessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11321. if (steam64Id && communitySessionID) {
  11322. GM_deleteValue('ATv4_updateCommunityAuth');
  11323. GM_setValue('steamCommunityAuth', {
  11324. steam64Id: steam64Id,
  11325. communitySessionID: communitySessionID
  11326. });
  11327. window.close();
  11328. external_Swal_default().fire('', i18n('closePageNotice'));
  11329. } else {
  11330. setTimeout(() => {
  11331. external_Swal_default().fire({
  11332. title: 'Error: Get "sessionID" failed',
  11333. icon: 'error'
  11334. });
  11335. }, 3e3);
  11336. }
  11337. });
  11338. } else {
  11339. if (window.location.hostname === 'key-hub.eu') {
  11340. unsafeWindow.keyhubtracker = 1;
  11341. unsafeWindow.gaData = {};
  11342. }
  11343. $(loadScript);
  11344. }
  11345. }();
  11346. })();