auto-task-v4

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

当前为 2025-04-30 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name auto-task-v4
  3. // @namespace auto-task-v4
  4. // @version 4.7.5
  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 abs.twimg.com
  66. // @connect api.twitter.com
  67. // @connect youtube.com
  68. // @connect www.youtube.com
  69. // @connect facebook.com
  70. // @connect instagram.com
  71. // @connect vk.com
  72. // @connect twitch.tv
  73. // @connect www.twitch.tv
  74. // @connect gql.twitch.tv
  75. // @connect github.com
  76. // @connect discordapp.com
  77. // @connect discord.gg
  78. // @connect discord.com
  79. // @connect www.reddit.com
  80. // @connect oauth.reddit.com
  81. // @connect raw.githubusercontent.com
  82. // @connect t.me
  83. // @connect bit.ly
  84. // @connect giveaway.su
  85. // @connect google.com
  86. // @connect www.vloot.io
  87. // @connect givee.club
  88. // @connect gleam.io
  89. // @connect www.indiedb.com
  90. // @connect key-hub.eu
  91. // @connect opquests.com
  92. // @connect itch.io
  93. // @connect auto-task-v4.hclonely.com
  94. // @connect giveawayhopper.com
  95. // @connect *
  96. // @require https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
  97. // @require https://cdn.jsdelivr.net/npm/js-cookie@3.0.1/dist/js.cookie.min.js
  98. // @require https://cdn.jsdelivr.net/npm/regenerator-runtime@0.13.5/runtime.min.js
  99. // @require https://cdn.jsdelivr.net/npm/js-sha1@0.6.0/src/sha1.min.js
  100. // @require https://cdn.jsdelivr.net/npm/js-sha256@0.11.0/src/sha256.min.js
  101. // @require https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js
  102. // @resource style https://cdn.jsdelivr.net/npm/sweetalert2@11.3.5/dist/sweetalert2.min.css
  103. // @require https://cdn.jsdelivr.net/npm/keyboardjs@2.6.4/dist/keyboard.min.js
  104. // @require https://cdn.jsdelivr.net/npm/dayjs@1.10.7/dayjs.min.js
  105. // @require https://bundle.run/buffer@6.0.3
  106.  
  107. // @noframes
  108. // ==/UserScript==
  109.  
  110. console.log('%c%s', 'color:blue', 'Auto-Task[Load]: 脚本开始加载');
  111. (function() {
  112. var __webpack_modules__ = {
  113. 243: function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  114. 'use strict';
  115. __webpack_require__.r(__webpack_exports__);
  116. __webpack_require__.d(__webpack_exports__, {
  117. decodeBase64: function() {
  118. return decodeBase64;
  119. },
  120. encodeBase64: function() {
  121. return encodeBase64;
  122. },
  123. generateTransactionId: function() {
  124. return generateTransactionId;
  125. }
  126. });
  127. const encodeSha256 = async data => {
  128. const encoder = new TextEncoder();
  129. const dataBuffer = encoder.encode(data);
  130. const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer);
  131. return Array.from(new Uint8Array(hashBuffer));
  132. };
  133. const encodeBase64 = data => {
  134. let binary = '';
  135. const bytes = new Uint8Array(data);
  136. const len = bytes.byteLength;
  137. for (let i = 0; i < len; i++) {
  138. binary += String.fromCharCode(bytes[i]);
  139. }
  140. return btoa(binary).replace(/=/g, '');
  141. };
  142. const decodeBase64 = data => {
  143. const binaryString = atob(data);
  144. const len = binaryString.length;
  145. const bytes = new Uint8Array(len);
  146. for (let i = 0; i < len; i++) {
  147. bytes[i] = binaryString.charCodeAt(i);
  148. }
  149. return Array.from(bytes);
  150. };
  151. const generateTransactionId = async (method, path, key, animationKey) => {
  152. const DEFAULT_KEYWORD = 'obfiowerehiring';
  153. const ADDITIONAL_RANDOM_NUMBER = 3;
  154. const timeNow = Math.floor((Date.now() - 1682924400 * 1e3) / 1e3);
  155. const timeNowBytes = [ timeNow & 255, timeNow >> 8 & 255, timeNow >> 16 & 255, timeNow >> 24 & 255 ];
  156. const data = `${method}!${path}!${timeNow}${DEFAULT_KEYWORD}${animationKey}`;
  157. const hashBytes = await encodeSha256(data);
  158. const keyBytes = decodeBase64(key);
  159. const randomNum = Math.floor(Math.random() * 256);
  160. const bytesArr = [ ...keyBytes, ...timeNowBytes, ...hashBytes.slice(0, 16), ADDITIONAL_RANDOM_NUMBER ];
  161. const out = new Uint8Array(bytesArr.length + 1);
  162. out[0] = randomNum;
  163. bytesArr.forEach((item, index) => {
  164. out[index + 1] = item ^ randomNum;
  165. });
  166. return encodeBase64(out);
  167. };
  168. },
  169. 314: function(module) {
  170. 'use strict';
  171. module.exports = function(cssWithMappingToString) {
  172. var list = [];
  173. list.toString = function toString() {
  174. return this.map(function(item) {
  175. var content = '';
  176. var needLayer = typeof item[5] !== 'undefined';
  177. if (item[4]) {
  178. content += '@supports ('.concat(item[4], ') {');
  179. }
  180. if (item[2]) {
  181. content += '@media '.concat(item[2], ' {');
  182. }
  183. if (needLayer) {
  184. content += '@layer'.concat(item[5].length > 0 ? ' '.concat(item[5]) : '', ' {');
  185. }
  186. content += cssWithMappingToString(item);
  187. if (needLayer) {
  188. content += '}';
  189. }
  190. if (item[2]) {
  191. content += '}';
  192. }
  193. if (item[4]) {
  194. content += '}';
  195. }
  196. return content;
  197. }).join('');
  198. };
  199. list.i = function i(modules, media, dedupe, supports, layer) {
  200. if (typeof modules === 'string') {
  201. modules = [ [ null, modules, undefined ] ];
  202. }
  203. var alreadyImportedModules = {};
  204. if (dedupe) {
  205. for (var k = 0; k < this.length; k++) {
  206. var id = this[k][0];
  207. if (id != null) {
  208. alreadyImportedModules[id] = true;
  209. }
  210. }
  211. }
  212. for (var _k = 0; _k < modules.length; _k++) {
  213. var item = [].concat(modules[_k]);
  214. if (dedupe && alreadyImportedModules[item[0]]) {
  215. continue;
  216. }
  217. if (typeof layer !== 'undefined') {
  218. if (typeof item[5] === 'undefined') {
  219. item[5] = layer;
  220. } else {
  221. item[1] = '@layer'.concat(item[5].length > 0 ? ' '.concat(item[5]) : '', ' {').concat(item[1], '}');
  222. item[5] = layer;
  223. }
  224. }
  225. if (media) {
  226. if (!item[2]) {
  227. item[2] = media;
  228. } else {
  229. item[1] = '@media '.concat(item[2], ' {').concat(item[1], '}');
  230. item[2] = media;
  231. }
  232. }
  233. if (supports) {
  234. if (!item[4]) {
  235. item[4] = ''.concat(supports);
  236. } else {
  237. item[1] = '@supports ('.concat(item[4], ') {').concat(item[1], '}');
  238. item[4] = supports;
  239. }
  240. }
  241. list.push(item);
  242. }
  243. };
  244. return list;
  245. };
  246. },
  247. 356: function(module, __unused_webpack_exports, __webpack_require__) {
  248. const {
  249. axiosGM
  250. } = __webpack_require__(945);
  251. const {
  252. getAnimationKey
  253. } = __webpack_require__(702);
  254. const {
  255. generateTransactionId
  256. } = __webpack_require__(243);
  257. const {
  258. decodeBase64
  259. } = __webpack_require__(243);
  260. const {
  261. never
  262. } = __webpack_require__(727);
  263. const {
  264. decodeTransactionId
  265. } = __webpack_require__(791);
  266. const createSession = async () => {
  267. const raw = await axiosGM({
  268. url: 'https://x.com',
  269. method: 'GET',
  270. responseType: 'text'
  271. });
  272. const html = raw.data;
  273. const root = $.parseHTML(`<div>${html}</div>`)[0];
  274. const content = root.querySelector('[name^=tw]')?.getAttribute('content') ?? never('No content');
  275. const verification = decodeBase64(content);
  276. const frames = root.querySelectorAll('[id^=\'loading-x-anim\']');
  277. const svgArray = svgKey(verification, frames);
  278. const indexKey = [ 38, 29, 43, 3 ];
  279. const animationKey = getAnimationKey(svgArray, verification, indexKey);
  280. return {
  281. get: (method, path) => generateTransactionId(method, path, content, animationKey.join(''))
  282. };
  283. };
  284. const svgKey = (verification, frames) => {
  285. const index = verification[5] % 4;
  286. const path = frames[index].children[0].children[1];
  287. const d = path.getAttribute('d') ?? never('No d');
  288. const sub = d.substring(9).split('C');
  289. const res = sub.map(item => {
  290. return item.replace(/[^\d]+/g, ' ').trim().split(' ').map(Number);
  291. });
  292. return res;
  293. };
  294. module.exports = {
  295. createSession: createSession,
  296. generateTransactionId: generateTransactionId,
  297. decodeTransactionId: decodeTransactionId
  298. };
  299. },
  300. 601: function(module) {
  301. 'use strict';
  302. module.exports = function(i) {
  303. return i[1];
  304. };
  305. },
  306. 675: function(module, __webpack_exports__, __webpack_require__) {
  307. 'use strict';
  308. __webpack_require__.d(__webpack_exports__, {
  309. A: function() {
  310. return __WEBPACK_DEFAULT_EXPORT__;
  311. }
  312. });
  313. var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(601);
  314. 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__);
  315. var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(314);
  316. 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__);
  317. 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());
  318. ___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;-webkit-text-decoration:none;text-decoration:none;background:linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);border-radius:30px;background-size:400%;text-transform:capitalize}.colorful-button:hover,#auto-task-buttons a.auto-task-website-btn:hover,.show-button-div a.auto-task-website-btn:hover,body.auto-task-options .auto-task-form table button:hover{transform:scale(1.05);box-shadow:0 6px 20px rgba(0,0,0,.3);cursor:pointer}.colorful-button:hover::before,#auto-task-buttons a.auto-task-website-btn:hover::before,.show-button-div a.auto-task-website-btn:hover::before,body.auto-task-options .auto-task-form table button:hover::before{filter:blur(10px);opacity:1}.colorful-button::before,#auto-task-buttons a.auto-task-website-btn::before,.show-button-div a.auto-task-website-btn::before,body.auto-task-options .auto-task-form table button::before{content:"";position:absolute;top:-5px;left:-5px;right:-5px;bottom:-5px;z-index:-1;background:linear-gradient(90deg, #03a9f4, #f441a5, #ffeb3b, #03a9f4);border-radius:40px;background-size:400%;opacity:-1}#auto-task-info{position:fixed;bottom:10px;right:10px;width:60%;max-width:500px;max-height:60%;overflow-y:auto;color:#000;background-color:#fff;padding-left:5px;z-index:999999999 !important;border:solid 2px #add8e6;border-radius:10px}#auto-task-info li{text-align:left}#auto-task-info li a.high-light{color:#00aeff;font-weight:bold}#auto-task-info .success{color:green}#auto-task-info .error{color:red}#auto-task-info .warning{color:blue}#auto-task-info .info{color:#ff0}#auto-task-info .update-text{color:green;border:solid 2px #8dcb69;margin:5px 10px 5px 20px;border-radius:10px;padding:5px 20px}.auto-task-keylol{display:inline-block;text-transform:capitalize;margin-left:10px;-webkit-text-decoration:none !important;text-decoration:none !important;border:solid 1px;border-radius:5px;padding:0 2px}.auto-task-keylol[selected=selected]{background-color:blue !important;color:#fff !important}.auto-task-form table{font-family:verdana,arial,sans-serif;font-size:11px;color:#333;border-width:1px;border-color:#999;border-collapse:collapse;width:100%}.auto-task-form table thead td{border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9;font-weight:bold;background-color:#fff}.auto-task-form table tbody tr{background-color:#d4e3e5}.auto-task-form table tbody tr:hover{background-color:#ff6 !important}.auto-task-form table tbody tr th{background-color:#c3dde0;border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9;text-transform:capitalize}.auto-task-form table tbody tr td{border-width:1px;padding:8px;border-style:solid;border-color:#a9c6c9}.swal2-modal{width:70% !important;max-width:1000px !important}body.auto-task-options{padding-top:10px;text-align:center}body.auto-task-options .auto-task-form{width:80%;max-width:1000px;margin:0 auto;padding-bottom:20px}body.auto-task-options .auto-task-form table input.editOption{width:80%}body.auto-task-options .auto-task-form table #getTwitterUserId,body.auto-task-options .auto-task-form table #getYoutubeChannelId{margin-top:5px}body.auto-task-options .auto-task-form table button{z-index:1}body.auto-task-options .auto-task-form table input[type=text]{outline-style:none;border:1px solid #ccc;border-radius:3px;padding:5px 10px;font-size:14px}body.auto-task-options .auto-task-form table input[type=text]:focus{border-color:#66afe9;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}body.auto-task-options .auto-task-form table label{position:relative;width:160px;height:80px;cursor:pointer;transform:scale(0.25);margin:-25% 0;top:-30px;display:inline-block}body.auto-task-options .auto-task-form table label input{position:relative;z-index:1;appearance:none}body.auto-task-options .auto-task-form table label input:checked~span{background:#05be05;box-shadow:0 15px 25px rgba(5,190,5,.4)}body.auto-task-options .auto-task-form table label input:checked~span i{left:84px}body.auto-task-options .auto-task-form table label input:checked~span i::before{background:#05be05;box-shadow:35px 0 0 #05be05}body.auto-task-options .auto-task-form table label input:checked~span i::after{bottom:12px;height:15px;border-bottom-left-radius:15px;border-bottom-right-radius:15px;background:#05be05}body.auto-task-options .auto-task-form table label span{position:absolute;top:0;left:0;width:100%;height:100%;background:#fe0000;border-radius:80px;transition:.5s;box-shadow:0 15px 25px rgba(254,0,0,.4)}body.auto-task-options .auto-task-form table label span i{position:absolute;top:4px;left:4px;width:72px;height:72px;background:#fff;border-radius:50%}body.auto-task-options .auto-task-form table label span i::before{content:"";position:absolute;top:22px;left:12px;width:12px;height:12px;border-radius:50%;background:#fe0000;box-shadow:35px 0 0 #fe0000;transition:.5s}body.auto-task-options .auto-task-form table label span i::after{content:"";position:absolute;bottom:15px;left:calc(50% - 15px);width:30px;height:6px;border-radius:6px;background:#fe0000;transition:.5s}body.auto-task-history{font-size:15px;font-weight:400;line-height:1.5}body.auto-task-history .container a{color:#007bff;-webkit-text-decoration:none;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 hsla(0,0%,100%,.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{-webkit-text-decoration:none;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{-webkit-text-decoration:underline;text-decoration:underline}body.auto-task-history .container .card .delete-task{right:10px;width:38px;height:35px;position:absolute;font-size:24px;cursor:pointer;border-radius:10px}body.auto-task-history .container .card .delete-task:hover{background:#fff}body.auto-task-history .container .card .time{right:5px;position:absolute;bottom:0;color:#e83e8c;font-family:'SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace';font-size:15px}#auto-task-buttons,.show-button-div{position:fixed;top:30px;right:15px;width:124px;z-index:999999999 !important;transform:scale(0.85)}#auto-task-buttons p,.show-button-div p{line-height:30px;height:40px;text-align:center;margin:5px !important}#auto-task-buttons a.auto-task-website-btn,.show-button-div a.auto-task-website-btn{width:105px;line-height:27px;font-size:20px;display:block}.show-button-div{width:20px}.auto-task-capitalize{text-transform:capitalize !important}.swal2-file:focus,.swal2-input:focus,.swal2-textarea:focus{box-shadow:inset 0px 0px 4px 1px rgba(100,150,200,.5) !important}.swal2-checkbox-custom{align-items:center;justify-content:center;background:#fff;color:inherit;margin:1em auto}.swal2-checkbox-custom input{flex-shrink:0;margin:0 .4em}.giveaway-actions #getKey{display:none !important}.auto-task-giveaway-status{color:#fff;border-radius:10px;padding:0 5px;margin-left:5px}.auto-task-giveaway-status.active{background-color:#5cb85c}.auto-task-giveaway-status.not-active{background-color:#d9534f}`, '' ]);
  319. const __WEBPACK_DEFAULT_EXPORT__ = ___CSS_LOADER_EXPORT___.toString();
  320. },
  321. 702: function(module) {
  322. const totalTime = 4096;
  323. const calculateScaledValue = (scalingFactor, baseValue, targetValue, roundToInteger) => {
  324. const result = scalingFactor * (targetValue - baseValue) / 255 + baseValue;
  325. return roundToInteger ? Math.floor(result) : Number(result.toFixed(2));
  326. };
  327. function interpolate(from, to, value) {
  328. const out = Array.from(from.length);
  329. for (let i = 0; i < from.length; i++) {
  330. out[i] = interpolateNum(from[i], to[i], value);
  331. }
  332. return out;
  333. }
  334. function interpolateNum(from, to, value) {
  335. return from * (1 - value) + to * value;
  336. }
  337. function convertRotationToMatrix(degrees) {
  338. const radians = degrees * Math.PI / 180;
  339. const c = Math.cos(radians).toFixed(6);
  340. const s = Math.sin(radians).toFixed(6);
  341. return [ c, s, -s, c, 0, 0 ];
  342. }
  343. function cubic(a, b, c, d) {
  344. if (a < 0 || a > 1 || c < 0 || c > 1) {
  345. return function(x) {
  346. return x;
  347. };
  348. }
  349. return function(x) {
  350. if (x <= 0) {
  351. var start_gradient = 0;
  352. if (a > 0) {
  353. start_gradient = b / a;
  354. } else if (!b && c > 0) {
  355. start_gradient = d / c;
  356. }
  357. return start_gradient * x;
  358. }
  359. if (x >= 1) {
  360. var end_gradient = 0;
  361. if (c < 1) {
  362. end_gradient = (d - 1) / (c - 1);
  363. } else if (c == 1 && a < 1) {
  364. end_gradient = (b - 1) / (a - 1);
  365. }
  366. return 1 + end_gradient * (x - 1);
  367. }
  368. var start = 0, end = 1;
  369. function f(a, b, m) {
  370. const _1_m = 1 - m;
  371. return 3 * a * _1_m * _1_m * m + 3 * b * _1_m * m * m + m * m * m;
  372. }
  373. while (start < end) {
  374. var mid = start + (end - start) / 2;
  375. var xEst = f(a, c, mid);
  376. if (Math.abs(x - xEst) < 1e-6) {
  377. return f(b, d, mid);
  378. }
  379. if (xEst < x) {
  380. start = mid;
  381. } else {
  382. end = mid;
  383. }
  384. }
  385. return f(b, d, mid);
  386. };
  387. }
  388. function doAnimation(numArr, frameTime) {
  389. const _cubic = cubic(...numArr.slice(7).map((n, W) => calculateScaledValue(n, W % 2 ? -1 : 0, 1, false)));
  390. const currentTime = Math.round(frameTime / 10) * 10;
  391. const cubicValue = _cubic(currentTime / totalTime);
  392. const frameColor = interpolate([ numArr[0], numArr[1], numArr[2] ], [ numArr[3], numArr[4], numArr[5] ], cubicValue);
  393. const frameRotate = interpolate([ 0 ], [ calculateScaledValue(numArr[6], 60, 360, !0) ], cubicValue);
  394. const frameMatrix = convertRotationToMatrix(frameRotate);
  395. return {
  396. color: frameColor.map(c => Math.round(c)),
  397. transform: frameMatrix.slice(0, 4).map(m => Number(Number(m).toFixed(2)))
  398. };
  399. }
  400. const getAnimationKey = (svgArray, verification, indexKey) => {
  401. const index = verification[indexKey[0]] % 16;
  402. const frameTime = verification[indexKey[1]] % 16 * (verification[indexKey[2]] % 16) * (verification[indexKey[3]] % 16);
  403. const style = doAnimation(svgArray[index], frameTime);
  404. const hexIntArray = Array.from([ style.color.length + style.transform.length + 2 ]);
  405. const hexArray = hexIntArray.map(i => i.toString(16));
  406. hexArray[7] = hexArray[8] = '0';
  407. for (let i = 0; i < 3; i++) {
  408. const numColorValue = style.color[i];
  409. if (numColorValue >= 0 && numColorValue <= 255) {
  410. hexArray[i] = numColorValue.toString(16);
  411. }
  412. if (numColorValue < 0) {
  413. hexArray[i] = '0';
  414. } else {
  415. hexArray[i] = 'ff';
  416. }
  417. }
  418. for (let i = 0; i < 4; i++) {
  419. let numMatrixValue = style.transform[i];
  420. if (numMatrixValue < 0) {
  421. numMatrixValue = -numMatrixValue;
  422. }
  423. if (numMatrixValue > 0 && numMatrixValue < 1) {
  424. hexArray[i + 3] = numMatrixValue.toString(16).replace('.', '');
  425. } else if (numMatrixValue <= 0) {
  426. hexArray[i + 3] = '0';
  427. } else {
  428. hexArray[i + 3] = '1';
  429. }
  430. }
  431. return hexArray;
  432. };
  433. module.exports = {
  434. getAnimationKey: getAnimationKey
  435. };
  436. },
  437. 727: function(module) {
  438. const never = (...args) => {
  439. throw new Error(...args);
  440. };
  441. module.exports = {
  442. never: never
  443. };
  444. },
  445. 791: function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  446. 'use strict';
  447. __webpack_require__.r(__webpack_exports__);
  448. __webpack_require__.d(__webpack_exports__, {
  449. decodeTransactionId: function() {
  450. return decodeTransactionId;
  451. }
  452. });
  453. const decodeTimeFromBytes = timeBytes => {
  454. const reversed = [ ...timeBytes ].reverse();
  455. const timeValue = reversed.reduce((acc, value) => acc << 8 | value, 0);
  456. const baseTime = 1682924400;
  457. return new Date((timeValue + baseTime) * 1e3);
  458. };
  459. const decodeTransactionId = transactionId => {
  460. const padded = transactionId + '='.repeat((4 - transactionId.length % 4) % 4);
  461. const binaryString = atob(padded);
  462. const decoded = new Uint8Array(binaryString.length);
  463. for (let i = 0; i < binaryString.length; i++) {
  464. decoded[i] = binaryString.charCodeAt(i);
  465. }
  466. const rand = decoded[0];
  467. const dataSection = Array.from(decoded.subarray(1)).reverse().map(byte => byte ^ rand).reverse();
  468. const keyBytes = dataSection.slice(0, 48);
  469. const timeNowBytes = dataSection.slice(48, 52);
  470. const hashBytes = dataSection.slice(52, 68);
  471. const additional = dataSection[68];
  472. return {
  473. keyBytes: keyBytes,
  474. time: decodeTimeFromBytes(timeNowBytes),
  475. hashBytes: hashBytes,
  476. additional: additional
  477. };
  478. };
  479. },
  480. 945: function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  481. 'use strict';
  482. __webpack_require__.r(__webpack_exports__);
  483. __webpack_require__.d(__webpack_exports__, {
  484. axiosGM: function() {
  485. return axiosGM;
  486. }
  487. });
  488. const parseResponseHeaders = headerStr => {
  489. const headers = {};
  490. if (!headerStr) {
  491. return headers;
  492. }
  493. headerStr.split('\r\n').forEach(line => {
  494. if (line) {
  495. const parts = line.split(':');
  496. const key = parts.shift()?.trim();
  497. const value = parts.join(':').trim();
  498. if (key) {
  499. if (key.toLowerCase() === 'set-cookie') {
  500. if (headers[key]) {
  501. if (Array.isArray(headers[key])) {
  502. headers[key].push(value);
  503. } else {
  504. headers[key] = [ headers[key], value ];
  505. }
  506. } else {
  507. headers[key] = value;
  508. }
  509. } else {
  510. headers[key] = value;
  511. }
  512. }
  513. }
  514. });
  515. return headers;
  516. };
  517. const axiosGM = function(config) {
  518. const finalConfig = {
  519. ...axiosGM.defaults,
  520. ...config
  521. };
  522. const retries = finalConfig.retry ?? 0;
  523. const retryDelay = finalConfig.retryDelay ?? 0;
  524. const requestAttempt = attempt => new Promise((resolve, reject) => {
  525. GM_xmlhttpRequest({
  526. method: finalConfig.method ? finalConfig.method.toUpperCase() : 'GET',
  527. url: finalConfig.url,
  528. headers: finalConfig.headers,
  529. data: finalConfig.data,
  530. responseType: finalConfig.responseType || 'json',
  531. timeout: finalConfig.timeout,
  532. fetch: finalConfig.fetch ?? true,
  533. onload(response) {
  534. const axiosResponse = {
  535. data: response.response || response.responseText,
  536. status: response.status,
  537. statusText: response.statusText,
  538. headers: parseResponseHeaders(response.responseHeaders),
  539. config: finalConfig,
  540. request: response
  541. };
  542. resolve(axiosResponse);
  543. },
  544. onerror(error) {
  545. if (attempt < retries) {
  546. setTimeout(() => {
  547. requestAttempt(attempt + 1).then(resolve).catch(reject);
  548. }, retryDelay);
  549. } else {
  550. reject(error);
  551. }
  552. },
  553. ontimeout() {
  554. if (attempt < retries) {
  555. setTimeout(() => {
  556. requestAttempt(attempt + 1).then(resolve).catch(reject);
  557. }, retryDelay);
  558. } else {
  559. reject('Error: timeout');
  560. }
  561. }
  562. });
  563. });
  564. return requestAttempt(0);
  565. };
  566. axiosGM.defaults = {};
  567. axiosGM.get = function(url, config = {}) {
  568. return axiosGM({
  569. ...config,
  570. url: url,
  571. method: 'GET'
  572. });
  573. };
  574. axiosGM.post = function(url, data, config = {}) {
  575. return axiosGM({
  576. ...config,
  577. url: url,
  578. data: data,
  579. method: 'POST'
  580. });
  581. };
  582. axiosGM.head = function(url, config = {}) {
  583. return axiosGM({
  584. ...config,
  585. url: url,
  586. method: 'HEAD'
  587. });
  588. };
  589. axiosGM.create = function(instanceDefaults = {}) {
  590. const instance = config => {
  591. const mergedConfig = {
  592. ...axiosGM.defaults,
  593. ...instanceDefaults,
  594. ...config
  595. };
  596. return axiosGM(mergedConfig);
  597. };
  598. instance.defaults = {
  599. ...axiosGM.defaults,
  600. ...instanceDefaults
  601. };
  602. instance.get = function(url, config = {}) {
  603. return instance({
  604. ...config,
  605. url: url,
  606. method: 'GET'
  607. });
  608. };
  609. instance.post = function(url, data, config = {}) {
  610. return instance({
  611. ...config,
  612. url: url,
  613. data: data,
  614. method: 'POST'
  615. });
  616. };
  617. instance.head = function(url, config = {}) {
  618. return instance({
  619. ...config,
  620. url: url,
  621. method: 'HEAD'
  622. });
  623. };
  624. instance.create = axiosGM.create;
  625. return instance;
  626. };
  627. },
  628. 991: function(__unused_webpack_module, exports) {
  629. !function(e, n) {
  630. true ? n(exports) : 0;
  631. }(this, function(e) {
  632. 'use strict';
  633. function l(e) {
  634. return '[object Object]' === o(e);
  635. }
  636. function n(e) {
  637. return /^\d+$/.test(e + '');
  638. }
  639. function t(e) {
  640. return /^\d+\.\d+$/.test(e + '');
  641. }
  642. var o = function(e) {
  643. return Object.prototype.toString.call(e);
  644. };
  645. var r = function() {
  646. return (r = Object.assign || function(e) {
  647. for (var n, t = 1, o = arguments.length; t < o; t++) {
  648. for (var r in n = arguments[t]) {
  649. Object.prototype.hasOwnProperty.call(n, r) && (e[r] = n[r]);
  650. }
  651. }
  652. return e;
  653. }).apply(this, arguments);
  654. };
  655. function i(e, n, t) {
  656. if (t || 2 === arguments.length) {
  657. for (var o, r = 0, i = n.length; r < i; r++) {
  658. !o && r in n || ((o = o || Array.prototype.slice.call(n, 0, r))[r] = n[r]);
  659. }
  660. }
  661. return e.concat(o || Array.prototype.slice.call(n));
  662. }
  663. a.prototype.init = function() {
  664. try {
  665. this.getSystemName(), this.getBrowserName();
  666. } catch (e) {
  667. console.warn('[UA formatter error] '.concat(e));
  668. }
  669. }, a.prototype.getEngine = function() {
  670. var e = this.agent;
  671. return -1 !== e.indexOf('Trident') ? 'Trident' : -1 !== e.indexOf('Firefox') ? 'Gecko' : -1 !== e.indexOf('Presto') ? 'Presto' : 'WebKit';
  672. }, a.prototype.getSystemName = function() {
  673. var e, n = (this.agent.match(/^[a-z]+\/\d+\.\d+\s?\(([a-z\d\s:;./_-]+)\)/i) || [])[1];
  674. try {
  675. var t, o = '';
  676. if (/Windows/i.test(n)) {
  677. var r = (n.match(/NT\s(\d+\.\d+)/) || [])[1];
  678. switch (this.info.os = 'Windows', r) {
  679. case '6.3':
  680. o = '8.1';
  681. break;
  682.  
  683. case '6.2':
  684. o = '8';
  685. break;
  686.  
  687. case '6.1':
  688. o = '7';
  689. break;
  690.  
  691. case '5.2':
  692. case '5.1':
  693. o = 'XP';
  694. break;
  695.  
  696. default:
  697. o = r;
  698. }
  699. this.info.device = 'PC', this.info.osVersion = o;
  700. } else {
  701. /^Macintosh/i.test(n) ? (o = (n.match(/X\s((\d+(_|\.))+\d+)/) || [])[1],
  702. this.info.os = 'Macintosh', this.info.device = 'PC', this.info.osVersion = null != (e = null == o ? void 0 : o.replace(/_/g, '.')) ? e : 'Unknown') : /^iPad/i.test(n) ? (o = (n.match(/((\d+_)+\d+)/) || [])[1],
  703. this.info.os = 'iPad', this.info.device = 'Tablet', this.info.osVersion = o.replace(/_/g, '.')) : /^iPhone/i.test(n) ? (o = (n.match(/((\d+_)+\d+)/) || [])[1],
  704. this.info.os = 'iPhone', this.info.device = 'Mobile', this.info.osVersion = o.replace(/_/g, '.')) : -1 !== n.indexOf('Android') ? (t = (n.match(/Android\s((\d+\.?)+\d?)/) || [])[1],
  705. this.info.device = 'Mobile', this.info.os = 'Android', this.info.osVersion = t) : (/Linux\s[a-z\d_]+/.test(n) ? this.info.os = 'Linux' : this.info.os = 'Unknown',
  706. this.info.osVersion = 'Unknown');
  707. }
  708. } catch (e) {
  709. this.info.os = 'Unknown', this.info.osVersion = 'Unknown';
  710. }
  711. }, a.prototype.getBrowserName = function() {
  712. var e = Object.keys(this.browserNameMap).map(function(e) {
  713. return new RegExp(''.concat(e, '(\\/|\\s)(\\d+\\.)+\\d+'));
  714. }), n = 1 < (n = (this.agent.match(/[a-z\d]+(\/|\s)(\d+\.)+\d+/gi) || []).filter(function(n) {
  715. return -1 !== e.findIndex(function(e) {
  716. return e.test(n);
  717. });
  718. })).length && !/^Safari/.test(n[n.length - 1]) ? n.reverse() : n;
  719. this.info = r(r({}, this.info), this._formatBrowserVersion(n[0]));
  720. }, a.prototype._formatBrowserVersion = function(e) {
  721. var n, t, o, r;
  722. try {
  723. for (var i = null != (t = null == (n = e.match(/(?<name>[a-z\d]+)(\/|\s)(?<version>(\d+\.)+\d+)/i)) ? void 0 : n.groups) ? t : {}, s = i.name, a = i.version, c = {}, u = 0, f = Object.entries(this.browserNameMap); u < f.length; u++) {
  724. var l = f[u], d = l[0], h = l[1];
  725. if (new RegExp(d).test(s)) {
  726. c = h;
  727. break;
  728. }
  729. }
  730. var p = {
  731. browserVersion: null != a ? a : 'Unknown',
  732. browser: null != (o = c.en) ? o : 'Unknown',
  733. browserZH: null != (r = (null == c ? void 0 : c.zh) || c.en) ? r : 'Unknown'
  734. };
  735. return 'Trident' === s && (p.browserVersion = {
  736. '4.0': 8,
  737. '5.0': 9,
  738. '6.0': 10,
  739. '7.0': 11
  740. }[a]), p;
  741. } catch (e) {
  742. return console.warn('[UA formatter error] '.concat(e)), {
  743. browser: 'Unknown',
  744. browserVersion: 'Unknown'
  745. };
  746. }
  747. };
  748. var s = a;
  749. function a(e) {
  750. this.agent = '', this.info = {
  751. browser: '',
  752. browserZH: '',
  753. browserVersion: '',
  754. os: '',
  755. osVersion: '',
  756. device: 'Unknown',
  757. engine: 'WebKit'
  758. }, this.browserNameMap = {
  759. MicroMessenger: {
  760. en: 'MicroMessenger',
  761. zh: '微信'
  762. },
  763. MetaSr: {
  764. en: 'MetaSr',
  765. zh: '搜狗浏览器'
  766. },
  767. 'QQ(Browser)?': {
  768. en: 'QQBrowser',
  769. zh: 'QQ浏览器'
  770. },
  771. UCBrowser: {
  772. en: 'UCBrowser',
  773. zh: 'UC浏览器'
  774. },
  775. '2345Explorer': {
  776. en: '2345Explorer',
  777. zh: '2345极速浏览器'
  778. },
  779. Mb2345Browser: {
  780. en: 'Mb2345Browser',
  781. zh: '2345手机浏览器'
  782. },
  783. Trident: {
  784. en: 'Internet Explorer'
  785. },
  786. 'Edge?': {
  787. en: 'Edge'
  788. },
  789. OPR: {
  790. en: 'Opera'
  791. },
  792. Vivaldi: {
  793. en: 'Vivaldi'
  794. },
  795. Firefox: {
  796. en: 'Firefox'
  797. },
  798. Chrome: {
  799. en: 'Chrome'
  800. },
  801. Safari: {
  802. en: 'Safari'
  803. }
  804. }, this.agent = e, this.init();
  805. var e = this.info, n = e.browser, t = e.browserVersion, e = e.osVersion;
  806. this.info = r(r({}, this.info), {
  807. engine: this.getEngine(),
  808. browserVersion: 'Safari' === n ? e : t
  809. });
  810. }
  811. u.prototype.init = function() {
  812. var t;
  813. 'undefined' != typeof window && (t = {}, document.cookie.split(/;\s/).forEach(function(e) {
  814. var e = e.split(/=/), n = e[0], e = e[1];
  815. t[n] = e;
  816. }), this.cookies = t);
  817. }, u.prototype.getItem = function(e) {
  818. return this.cookies[e];
  819. }, u.prototype.getAllItems = function() {
  820. return this.cookies;
  821. }, u.prototype.setItem = function(e, n, t, o, r, i) {
  822. document.cookie = ''.concat(e, '=').concat(n).concat(t ? '; expires='.concat(t) : '').concat(o ? '; path='.concat(o) : '').concat(r ? '; domain='.concat(r) : '').concat(i ? '; secure' : '');
  823. };
  824. var c = u;
  825. function u() {
  826. this.cookies = {}, this.init();
  827. }
  828. function d(e, n) {
  829. var t = i(i([], n || [], !0), [ '_' ], !1).join('|');
  830. return e.replace(new RegExp('(('.concat(t, ')[a-z])+'), 'g'), function(e, n) {
  831. return n.replace(new RegExp(t), '').toLocaleUpperCase();
  832. });
  833. }
  834. function f(e) {
  835. return e.replace(/(-\w)/g, function(e) {
  836. return e.substr(1, 1).toUpperCase();
  837. }).replace(/^(\w)/, function(e) {
  838. return e.toUpperCase();
  839. });
  840. }
  841. e.countDown = function e(n, t, o, r) {
  842. if (!window) {
  843. throw new Error('window is not defined.');
  844. }
  845. if (0 < n) {
  846. return r && r(), n--, window[t] = window.setTimeout(function() {
  847. e(n, t, o, r);
  848. }, 1e3), function() {
  849. return clearTimeout(window[t]);
  850. };
  851. }
  852. clearTimeout(window[t]), o && o();
  853. }, e.createRandomID = function(e) {
  854. void 0 === e && (e = 12);
  855. for (var n = [], t = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''), o = t.length, r = 0; r < e; r++) {
  856. n.push(t[Math.round(Math.random() * o)]);
  857. }
  858. return n.join('');
  859. }, e.dCookie = function() {
  860. return new c();
  861. }, e.debounce = function(o, r, i) {
  862. var s;
  863. return void 0 === r && (r = 0), void 0 === i && (i = !1), function() {
  864. for (var e = this, n = [], t = 0; t < arguments.length; t++) {
  865. n[t] = arguments[t];
  866. }
  867. i ? o.apply(this, n) : (clearTimeout(s), s = setTimeout(function() {
  868. o.apply(e, n);
  869. }, r));
  870. };
  871. }, e.debounceDecorator = function(r, i) {
  872. var s;
  873. return function(e, n, t) {
  874. var o = t.value;
  875. return t.value = function() {
  876. for (var e = this, n = [], t = 0; t < arguments.length; t++) {
  877. n[t] = arguments[t];
  878. }
  879. i ? o.apply(this, n) : (clearTimeout(s), s = setTimeout(function() {
  880. o.apply(e, n);
  881. }, r));
  882. }, t;
  883. };
  884. }, e.debugWarn = function(e, n) {
  885. console.warn('['.concat(e, ']: ').concat(n));
  886. }, e.deepCopy = function e(n) {
  887. if (l(n) || Array.isArray(n)) {
  888. var t, o = Array.isArray(n) ? [] : {};
  889. for (t in n) {
  890. o[t] = e(n[t]);
  891. }
  892. return o;
  893. }
  894. return n;
  895. }, e.deleteArrayItems = function(n, e, t) {
  896. return 'object' == typeof e[0] ? e.filter(function(e) {
  897. return !n.includes(e[t]);
  898. }) : e.filter(function(e) {
  899. return !n.includes(e);
  900. });
  901. }, e.formatQueryParams = function(e) {
  902. e = null == (e = /\?(?<params>(.*)=.+)/.exec(decodeURIComponent(e))) ? void 0 : e.groups;
  903. if (!e) {
  904. return {};
  905. }
  906. for (var n = e.params.split('&'), o = {}, t = 0; t < n.length; t++) {
  907. n[t].replace(/([^?&]*)=([^?&]*)/, function(e, n, t) {
  908. return o[n] = t, e;
  909. });
  910. }
  911. return o;
  912. }, e.formatThousandth = function(e) {
  913. var e = ''.concat(e).split('.'), n = e[0], e = e[1], e = void 0 === e ? '' : e, n = n.replace(/\d{1,3}(?=(\d{3})+$)/g, '$&,');
  914. return ''.concat(n).concat(e ? '.'.concat(e) : '');
  915. }, e.generateTree = function e(n, t, o, r) {
  916. for (var i = [], s = 0; s < n.length; s++) {
  917. var a = n[s];
  918. a[o] === t && (i.push(a), a.children = e(n, a[null != r ? r : 'id'], o, r));
  919. }
  920. return i;
  921. }, e.isBoolean = function(e) {
  922. return 'boolean' == typeof e;
  923. }, e.isEmpty = function(e) {
  924. return Array.isArray(e) ? 0 === e.length : l(e) ? 0 === Object.keys(e).length : [ '[object Set]', '[object Map]' ].includes(o(e)) ? 0 === e.size : [ null, void 0, '' ].includes(e);
  925. }, e.isFloatNumber = t, e.isFunction = function(e) {
  926. return '[object Function]' === o(e);
  927. }, e.isImageUrl = function(e) {
  928. return /\.((png)|(jpe?g)|(gif)|(svg)|(webp))$/gi.test(e);
  929. }, e.isInteger = n, e.isNumber = function(e) {
  930. return n(e) || t(e);
  931. }, e.isObject = l, e.isPromise = function(e) {
  932. return '[object Promise]' === o(e);
  933. }, e.isRegexp = function(e) {
  934. return '[object RegExp]' === o(e);
  935. }, e.objectKeyToCamelCase = function e(n, t, o) {
  936. if (Array.isArray(n)) {
  937. for (var r = [], i = 0; i < n.length; i++) {
  938. r[i] = e(t && n[i][t] ? n[i][t] : n[i], t, o);
  939. }
  940. } else if (l(n)) {
  941. r = {};
  942. for (var s = t && n[t] ? n[t] : n, a = 0, c = Object.entries(s); a < c.length; a++) {
  943. var u = (f = c[a])[0], f = f[1];
  944. Array.isArray(f) || l(s) ? r[d(u, o)] = e(f, t, o) : r[d(u, o)] = f;
  945. }
  946. } else {
  947. r = n;
  948. }
  949. return r;
  950. }, e.pickLastItem = function(e) {
  951. return e[e.length - 1];
  952. }, e.realType = o, e.searchParams = function(e, n) {
  953. return void 0 === e && (e = null === location || void 0 === location ? void 0 : location.search),
  954. new URLSearchParams(e).get(n);
  955. }, e.throwError = function(e, n) {
  956. throw '['.concat(f(e), ']: ').concat(n);
  957. }, e.toBoolean = function(e) {
  958. return 'true' === e || 'false' !== e && Boolean(e);
  959. }, e.toLowerCamelCase = d, e.toPascalCase = f, e.toUnderline = function(e) {
  960. return e.replace(/([A-Z])/g, function(e) {
  961. return '_'.concat(e.toLocaleLowerCase());
  962. });
  963. }, e.ua = function(e) {
  964. return void 0 === e && (e = navigator.userAgent), new s(e).info;
  965. };
  966. });
  967. }
  968. };
  969. var __webpack_module_cache__ = {};
  970. function __webpack_require__(moduleId) {
  971. var cachedModule = __webpack_module_cache__[moduleId];
  972. if (cachedModule !== undefined) {
  973. return cachedModule.exports;
  974. }
  975. var module = __webpack_module_cache__[moduleId] = {
  976. id: moduleId,
  977. exports: {}
  978. };
  979. __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  980. return module.exports;
  981. }
  982. !function() {
  983. __webpack_require__.n = function(module) {
  984. var getter = module && module.__esModule ? function() {
  985. return module['default'];
  986. } : function() {
  987. return module;
  988. };
  989. __webpack_require__.d(getter, {
  990. a: getter
  991. });
  992. return getter;
  993. };
  994. }();
  995. !function() {
  996. __webpack_require__.d = function(exports, definition) {
  997. for (var key in definition) {
  998. if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  999. Object.defineProperty(exports, key, {
  1000. enumerable: true,
  1001. get: definition[key]
  1002. });
  1003. }
  1004. }
  1005. };
  1006. }();
  1007. !function() {
  1008. __webpack_require__.o = function(obj, prop) {
  1009. return Object.prototype.hasOwnProperty.call(obj, prop);
  1010. };
  1011. }();
  1012. !function() {
  1013. __webpack_require__.r = function(exports) {
  1014. if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  1015. Object.defineProperty(exports, Symbol.toStringTag, {
  1016. value: 'Module'
  1017. });
  1018. }
  1019. Object.defineProperty(exports, '__esModule', {
  1020. value: true
  1021. });
  1022. };
  1023. }();
  1024. var __webpack_exports__ = {};
  1025. !function() {
  1026. 'use strict';
  1027. const external_Swal_namespaceObject = Swal;
  1028. var external_Swal_default = __webpack_require__.n(external_Swal_namespaceObject);
  1029. const external_Cookies_namespaceObject = Cookies;
  1030. var external_Cookies_default = __webpack_require__.n(external_Cookies_namespaceObject);
  1031. var auto_task = __webpack_require__(675);
  1032. var javascript_utils_umd_min = __webpack_require__(991);
  1033. const httpRequest = async (options, times = 0) => {
  1034. if (window.TRACE) {
  1035. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  1036. }
  1037. try {
  1038. const result = await new Promise(resolve => {
  1039. if (options.dataType) {
  1040. options.responseType = options.dataType;
  1041. }
  1042. const requestObj = {
  1043. ...{
  1044. timeout: 3e4,
  1045. ontimeout(data) {
  1046. resolve({
  1047. result: 'Error',
  1048. statusText: 'Timeout',
  1049. status: 601,
  1050. data: data,
  1051. options: options
  1052. });
  1053. },
  1054. onabort() {
  1055. resolve({
  1056. result: 'Error',
  1057. statusText: 'Aborted',
  1058. status: 602,
  1059. data: undefined,
  1060. options: options
  1061. });
  1062. },
  1063. onerror(data) {
  1064. resolve({
  1065. result: 'Error',
  1066. statusText: 'Error',
  1067. status: 603,
  1068. data: data,
  1069. options: options
  1070. });
  1071. },
  1072. onload(data) {
  1073. const headers = {};
  1074. data.responseHeaders?.split('\n').forEach(header => {
  1075. const headerArr = header.trim().split(':');
  1076. const name = headerArr.shift()?.trim() || '';
  1077. const value = headerArr.join(':').trim();
  1078. if (name && value) {
  1079. if (headers[name]) {
  1080. if (Array.isArray(headers[name])) {
  1081. headers[name].push(value);
  1082. } else {
  1083. headers[name] = [ headers[name], value ];
  1084. }
  1085. } else {
  1086. headers[name] = value;
  1087. }
  1088. }
  1089. });
  1090. if (headers['set-cookie'] && !Array.isArray(headers['set-cookie'])) {
  1091. headers['set-cookie'] = [ headers['set-cookie'] ];
  1092. }
  1093. data.responseHeadersText = data.responseHeaders;
  1094. data.responseHeaders = headers;
  1095. data.finalUrl = data.responseHeaders?.location || data.finalUrl;
  1096. if (options.responseType === 'json' && data?.response && typeof data.response !== 'object') {
  1097. try {
  1098. data.response = JSON.parse(data.responseText);
  1099. } catch (error) {}
  1100. }
  1101. resolve({
  1102. result: 'Success',
  1103. statusText: 'Load',
  1104. status: 600,
  1105. data: data,
  1106. options: options
  1107. });
  1108. }
  1109. },
  1110. ...options
  1111. };
  1112. GM_xmlhttpRequest(requestObj);
  1113. });
  1114. if (window.DEBUG) {
  1115. console.log('%cAuto-Task[httpRequest]:', 'color:blue', JSON.stringify(result));
  1116. }
  1117. if (result.status !== 600 && times < 2) {
  1118. return await httpRequest(options, times + 1);
  1119. }
  1120. return result;
  1121. } catch (error) {
  1122. console.log('%cAuto-Task[httpRequest]:', 'color:red', JSON.stringify({
  1123. errorMsg: error,
  1124. options: options
  1125. }));
  1126. throwError(error, 'httpRequest');
  1127. return {
  1128. result: 'JsError',
  1129. statusText: 'Error',
  1130. status: 604,
  1131. error: error,
  1132. options: options
  1133. };
  1134. }
  1135. };
  1136. const tools_httpRequest = httpRequest;
  1137. const echoLog = ({
  1138. type,
  1139. text,
  1140. html,
  1141. id
  1142. }) => {
  1143. const emptyStatus = {
  1144. success: () => emptyStatus,
  1145. error: () => emptyStatus,
  1146. warning: () => emptyStatus,
  1147. info: () => emptyStatus,
  1148. view: () => emptyStatus
  1149. };
  1150. try {
  1151. let ele;
  1152. if (type) {
  1153. switch (type) {
  1154. case 'joiningSteamGroup':
  1155. case 'leavingSteamGroup':
  1156. case 'gettingSteamGroupId':
  1157. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/groups/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1158. break;
  1159.  
  1160. case 'joiningSteamOfficialGroup':
  1161. case 'leavingSteamOfficialGroup':
  1162. case 'gettingSteamOfficialGroupId':
  1163. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/games/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1164. break;
  1165.  
  1166. case 'subscribingForum':
  1167. case 'unsubscribingForum':
  1168. case 'gettingForumId':
  1169. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/app/${text}/discussions/" target="_blank">${text}</a>]...<font></font></li>`);
  1170. break;
  1171.  
  1172. case 'followingCurator':
  1173. case 'unfollowingCurator':
  1174. case 'gettingCuratorId':
  1175. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/${text?.includes('/') ? text : `curator/${text}`}" target="_blank">${text}</a>]...<font></font></li>`);
  1176. break;
  1177.  
  1178. case 'addingToWishlist':
  1179. case 'removingFromWishlist':
  1180. case 'followingGame':
  1181. case 'unfollowingGame':
  1182. case 'gettingSubid':
  1183. case 'addingFreeLicense':
  1184. case 'requestingPlayTestAccess':
  1185. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/app/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1186. break;
  1187.  
  1188. case 'addingFreeLicenseSubid':
  1189. ele = $(`<li>${i18n('addingFreeLicense')}[<a href="https://steamdb.info/sub/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  1190. break;
  1191.  
  1192. case 'favoritingWorkshop':
  1193. case 'unfavoritingWorkshop':
  1194. case 'gettingWorkshopAppId':
  1195. case 'votingUpWorkshop':
  1196. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/sharedfiles/filedetails/?id=${text}" target="_blank">
  1197. ${text}</a>]...<font></font></li>`);
  1198. break;
  1199.  
  1200. case 'gettingAnnouncementParams':
  1201. case 'likingAnnouncement':
  1202. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/news/app/${text}/view/${id}" target="_blank">
  1203. ${id}</a>]...<font></font></li>`);
  1204. break;
  1205.  
  1206. case 'joiningDiscordServer':
  1207. case 'gettingDiscordGuild':
  1208. ele = $(`<li>${i18n(type)}[<a href="https://discord.com/invite/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1209. break;
  1210.  
  1211. case 'leavingDiscordServer':
  1212. ele = $(`<li>${i18n(type)}[<a href="https://discord.com/channels/@me/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1213. break;
  1214.  
  1215. case 'updateDiscordAuth':
  1216. ele = $(`<li style="color:red;">${i18n('updateDiscordAuth')}</li>`);
  1217. break;
  1218.  
  1219. case 'followingTwitchChannel':
  1220. case 'unfollowingTwitchChannel':
  1221. case 'gettingTwitchChannelId':
  1222. ele = $(`<li>${i18n(type)}[<a href="https://www.twitch.tv/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1223. break;
  1224.  
  1225. case 'gettingInsUserId':
  1226. case 'followingIns':
  1227. case 'unfollowingIns':
  1228. ele = $(`<li>${i18n(type)}[<a href="https://www.instagram.com/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  1229. break;
  1230.  
  1231. case 'gettingTwitterUserId':
  1232. case 'followingTwitterUser':
  1233. case 'unfollowingTwitterUser':
  1234. ele = $(`<li>${i18n(type)}[<a href="https://x.com/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1235. break;
  1236.  
  1237. case 'retweetting':
  1238. case 'unretweetting':
  1239. ele = $(`<li>${i18n(type)}${text}...<font></font></li>`);
  1240. break;
  1241.  
  1242. case 'joiningReddit':
  1243. case 'leavingReddit':
  1244. ele = $(`<li>${i18n(type)}[<a href="https://www.reddit.com/r/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  1245. break;
  1246.  
  1247. case 'followingRedditUser':
  1248. case 'unfollowingRedditUser':
  1249. ele = $(`<li>${i18n(type)}[<a href="https://www.reddit.com/user/${text?.replace('u_', '')}" target="_blank">
  1250. ${text?.replace('u_', '')}</a>]...<font></font></li>`);
  1251. break;
  1252.  
  1253. case 'followingYtbChannel':
  1254. case 'unfollowingYtbChannel':
  1255. ele = $(`<li>${i18n(type)}[<a href="https://www.youtube.com/channel/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1256. break;
  1257.  
  1258. case 'likingYtbVideo':
  1259. case 'unlikingYtbVideo':
  1260. ele = $(`<li>${i18n(type)}[<a href="https://www.youtube.com/watch?v=${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1261. break;
  1262.  
  1263. case 'gettingVkId':
  1264. case 'joiningVkGroup':
  1265. case 'leavingVkGroup':
  1266. case 'joiningVkPublic':
  1267. case 'leavingVkPublic':
  1268. case 'sendingVkWall':
  1269. case 'deletingVkWall':
  1270. ele = $(`<li>${i18n(type)}[<a href="https://vk.com/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  1271. break;
  1272.  
  1273. case 'visitingLink':
  1274. ele = $(`<li>${i18n('visitingLink')}[<a href="${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1275. break;
  1276.  
  1277. case 'verifyingInsAuth':
  1278. case 'text':
  1279. ele = $(`<li>${i18n(text)}<font></font></li>`);
  1280. break;
  1281.  
  1282. case 'html':
  1283. ele = $(text || html);
  1284. break;
  1285.  
  1286. case 'whiteList':
  1287. ele = $(`<li><font class="warning">${i18n('skipTask')}[${text}(${id})](${i18n('whiteList')})</font></li>`);
  1288. break;
  1289.  
  1290. case 'globalOptionsSkip':
  1291. ele = $(`<li>${i18n('skipTaskOption')}<font class="warning">${text}</font></li>`);
  1292. break;
  1293.  
  1294. default:
  1295. ele = $(`<li>${i18n('unKnown')}:${type}(${text})...<font></font></li>`);
  1296. break;
  1297. }
  1298. } else if (text) {
  1299. ele = $(`<li>${i18n(text)}<font></font></li>`);
  1300. } else if (html) {
  1301. ele = $(html);
  1302. } else {
  1303. ele = $('<li><font></font></li>');
  1304. }
  1305. ele.addClass('card-text');
  1306. $('#auto-task-info').append(ele);
  1307. ele[0]?.scrollIntoView();
  1308. const font = ele.find('font');
  1309. const status = {
  1310. font: font,
  1311. success(text = 'Success', html = false) {
  1312. this.font?.attr('class', '').addClass('success');
  1313. html ? this.font?.html(text) : this.font?.text(text);
  1314. return this;
  1315. },
  1316. error(text = 'Error', html = false) {
  1317. this.font?.attr('class', '').addClass('error');
  1318. html ? this.font?.html(text) : this.font?.text(text);
  1319. return this;
  1320. },
  1321. warning(text = 'Warning', html = false) {
  1322. this.font?.attr('class', '').addClass('warning');
  1323. html ? this.font?.html(text) : this.font?.text(text);
  1324. return this;
  1325. },
  1326. info(text = 'Info', html = false) {
  1327. this.font?.attr('class', '').addClass('info');
  1328. html ? this.font?.html(text) : this.font?.text(text);
  1329. return this;
  1330. },
  1331. view() {
  1332. this.font?.[0].scrollIntoView();
  1333. return this;
  1334. }
  1335. };
  1336. return status;
  1337. } catch (error) {
  1338. throwError(error, 'echoLog');
  1339. return emptyStatus;
  1340. }
  1341. };
  1342. const scripts_echoLog = echoLog;
  1343. const unique = array => {
  1344. try {
  1345. return [ ...new Set(array) ];
  1346. } catch (error) {
  1347. throwError(error, 'unique');
  1348. return [];
  1349. }
  1350. };
  1351. const delay = (time = 1e3) => new Promise(resolve => {
  1352. setTimeout(() => {
  1353. resolve(true);
  1354. }, time);
  1355. });
  1356. const getRedirectLink = async link => {
  1357. try {
  1358. if (!link) {
  1359. return null;
  1360. }
  1361. const redirectLinksCache = GM_getValue('redirectLinks') || {};
  1362. if (redirectLinksCache[link]) {
  1363. redirectLinksCache[link];
  1364. }
  1365. return await tools_httpRequest({
  1366. url: link,
  1367. method: 'GET'
  1368. }).then(({
  1369. data
  1370. }) => {
  1371. if (data?.finalUrl) {
  1372. redirectLinksCache[link] = data.finalUrl;
  1373. GM_setValue('redirectLinks', redirectLinksCache);
  1374. return data.finalUrl;
  1375. }
  1376. return null;
  1377. });
  1378. } catch (error) {
  1379. throwError(error, 'getRedirectLink');
  1380. return null;
  1381. }
  1382. };
  1383. const visitLink = async (link, options) => {
  1384. try {
  1385. const logStatus = scripts_echoLog({
  1386. type: 'visitLink',
  1387. text: link
  1388. });
  1389. return await tools_httpRequest({
  1390. url: link,
  1391. method: 'GET',
  1392. ...options
  1393. }).then(({
  1394. result,
  1395. statusText,
  1396. status
  1397. }) => {
  1398. if (result === 'Success') {
  1399. logStatus.success();
  1400. return true;
  1401. }
  1402. logStatus.error(`${result}:${statusText}(${status})`);
  1403. return false;
  1404. });
  1405. } catch (error) {
  1406. throwError(error, 'visitLink');
  1407. return false;
  1408. }
  1409. };
  1410. const getUrlQuery = url => {
  1411. try {
  1412. const query = {};
  1413. if (url) {
  1414. if (url.includes('?')) {
  1415. url.split('?')[1].replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  1416. query[key] = value;
  1417. return str;
  1418. });
  1419. }
  1420. } else {
  1421. window.location.search.replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  1422. query[key] = value;
  1423. return str;
  1424. });
  1425. }
  1426. return query;
  1427. } catch (error) {
  1428. throwError(error, 'getUrlQuery');
  1429. return {};
  1430. }
  1431. };
  1432. const getUuid = () => {
  1433. const uuidUrl = URL.createObjectURL(new Blob()).toString();
  1434. return uuidUrl.slice(uuidUrl.lastIndexOf('/') + 1);
  1435. };
  1436. const stringToColour = str => {
  1437. try {
  1438. let hash = 0;
  1439. for (let i = 0; i < str.length; i++) {
  1440. hash = str.charCodeAt(i) + ((hash << 5) - hash);
  1441. }
  1442. let colour = '#';
  1443. for (let i = 0; i < 3; i++) {
  1444. const value = hash >> i * 8 & 255;
  1445. colour += `00${value.toString(16)}`.slice(-2);
  1446. }
  1447. return colour;
  1448. } catch (error) {
  1449. throwError(error, 'stringToColour');
  1450. return '#fff';
  1451. }
  1452. };
  1453. const debug = (log, data) => {
  1454. if (!window.DEBUG) {
  1455. return;
  1456. }
  1457. console.log('%c%s', 'color:#a7a7a7', `Auto-Task[Debug]: ${log}`);
  1458. if (data) {
  1459. console.log('%c%s', 'color:#a7a7a7', 'Auto-Task[Debug]: ', data);
  1460. }
  1461. };
  1462. const defaultGlobalOptions = {
  1463. doTask: {
  1464. discord: {
  1465. servers: true
  1466. },
  1467. instagram: {
  1468. users: true
  1469. },
  1470. twitch: {
  1471. channels: true
  1472. },
  1473. twitter: {
  1474. users: true,
  1475. retweets: true
  1476. },
  1477. vk: {
  1478. names: true
  1479. },
  1480. youtube: {
  1481. channels: true,
  1482. likes: true
  1483. },
  1484. reddit: {
  1485. reddits: true
  1486. },
  1487. steam: {
  1488. groups: true,
  1489. officialGroups: true,
  1490. wishlists: true,
  1491. follows: true,
  1492. forums: true,
  1493. workshops: true,
  1494. curators: true,
  1495. workshopVotes: true,
  1496. announcements: true,
  1497. licenses: true,
  1498. playtests: true
  1499. }
  1500. },
  1501. undoTask: {
  1502. discord: {
  1503. servers: true
  1504. },
  1505. instagram: {
  1506. users: true
  1507. },
  1508. twitch: {
  1509. channels: true
  1510. },
  1511. twitter: {
  1512. users: true,
  1513. retweets: true
  1514. },
  1515. vk: {
  1516. names: true
  1517. },
  1518. youtube: {
  1519. channels: true,
  1520. likes: true
  1521. },
  1522. reddit: {
  1523. reddits: true
  1524. },
  1525. steam: {
  1526. groups: true,
  1527. officialGroups: true,
  1528. wishlists: true,
  1529. follows: true,
  1530. forums: true,
  1531. workshops: true,
  1532. curators: true
  1533. }
  1534. },
  1535. ASF: {
  1536. AsfEnabled: false,
  1537. AsfIpcUrl: '',
  1538. AsfIpcPassword: '',
  1539. AsfBotname: 'asf'
  1540. },
  1541. position: {
  1542. buttonSideX: 'right',
  1543. buttonSideY: 'top',
  1544. buttonDistance: '15,30',
  1545. showButtonSideX: 'right',
  1546. showButtonSideY: 'top',
  1547. showButtonDistance: '15,30',
  1548. logSideX: 'right',
  1549. logSideY: 'bottom',
  1550. logDistance: '10,10'
  1551. },
  1552. hotKey: {
  1553. doTaskKey: 'alt + d',
  1554. undoTaskKey: 'alt + u',
  1555. toggleLogKey: 'alt + l'
  1556. },
  1557. other: {
  1558. twitterVerifyId: '783214',
  1559. youtubeVerifyChannel: 'UCrXUsMBcfTVqwAS7DKg9C0Q',
  1560. autoUpdateSource: 'jsdelivr',
  1561. language: 'zh',
  1562. checkLogin: true,
  1563. checkLeftKey: true,
  1564. defaultShowButton: true,
  1565. defaultShowLog: true,
  1566. debug: false,
  1567. receivePreview: true
  1568. }
  1569. };
  1570. const userDefinedGlobalOptions = GM_getValue('globalOptions') || {};
  1571. const assignObject = (obj1, obj2) => {
  1572. try {
  1573. const newObj = {};
  1574. for (const [ key, value ] of Object.entries(obj1)) {
  1575. if (Object.prototype.toString.call(value) === '[object Object]' && Object.prototype.toString.call(obj2[key]) === '[object Object]') {
  1576. newObj[key] = assignObject(value, obj2[key]);
  1577. } else {
  1578. newObj[key] = obj2[key] ?? value;
  1579. }
  1580. }
  1581. return newObj;
  1582. } catch (error) {
  1583. throwError(error, 'assignObject');
  1584. return defaultGlobalOptions;
  1585. }
  1586. };
  1587. const globalOptions = assignObject(defaultGlobalOptions, userDefinedGlobalOptions);
  1588. const saveData = () => {
  1589. try {
  1590. const data = {};
  1591. $('#globalOptionsForm').serializeArray().map(value => {
  1592. data[value.name] = value.value;
  1593. return value;
  1594. });
  1595. $.makeArray($('#globalOptionsForm input')).map(element => {
  1596. const name = $(element).attr('name');
  1597. const keys = name.split('.');
  1598. if (keys.length === 3) {
  1599. globalOptions[keys[0]][keys[1]][keys[2]] = data[name] ? data[name] === 'on' ? true : data[name] : data[name] ?? false;
  1600. } else if (keys.length === 2) {
  1601. globalOptions[keys[0]][keys[1]] = data[name] ? data[name] === 'on' ? true : data[name] : data[name] ?? false;
  1602. }
  1603. return element;
  1604. });
  1605. GM_setValue('globalOptions', globalOptions);
  1606. external_Swal_default().fire({
  1607. title: i18n('changeGlobalOptionsSuccess'),
  1608. icon: 'success'
  1609. });
  1610. } catch (error) {
  1611. throwError(error, 'saveData');
  1612. }
  1613. };
  1614. const changeGlobalOptions = showType => {
  1615. try {
  1616. let globalOptionsForm = `<form id="globalOptionsForm" class="auto-task-form">
  1617. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  1618. for (const [ type, data1 ] of Object.entries(globalOptions)) {
  1619. for (const [ option, data2 ] of Object.entries(data1)) {
  1620. if ([ 'other', 'position', 'hotKey', 'ASF' ].includes(type)) {
  1621. if (typeof data2 === 'boolean') {
  1622. 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>`;
  1623. } else {
  1624. 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>`;
  1625. }
  1626. } else {
  1627. for (const [ socialType, data3 ] of Object.entries(data2)) {
  1628. 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>`;
  1629. }
  1630. }
  1631. }
  1632. }
  1633. globalOptionsForm += '</tbody></table></form>';
  1634. if (showType === 'swal') {
  1635. external_Swal_default().fire({
  1636. title: i18n('globalOptions'),
  1637. html: globalOptionsForm,
  1638. showConfirmButton: true,
  1639. confirmButtonText: i18n('save'),
  1640. showCancelButton: true,
  1641. cancelButtonText: i18n('close')
  1642. }).then(({
  1643. isConfirmed
  1644. }) => {
  1645. if (isConfirmed) {
  1646. saveData();
  1647. }
  1648. });
  1649. } else {
  1650. $('body').append(`<h2>${i18n('globalOptions')}</h2>${globalOptionsForm}`);
  1651. }
  1652. } catch (error) {
  1653. throwError(error, 'changeGlobalOptions');
  1654. }
  1655. };
  1656. const data = {
  1657. website: '网站',
  1658. type: '类型',
  1659. edit: '编辑',
  1660. whiteList: '白名单',
  1661. skipTask: '跳过撤销任务',
  1662. whiteListOptions: '白名单设置',
  1663. changeWhiteListOption: '设置白名单(%0)',
  1664. whiteListNotFound: '找不到此项白名单: %0',
  1665. changeWhiteListSuccess: '白名单修改成功,刷新生效!',
  1666. changeWebsiteOptions: '网站设置',
  1667. changeGlobalOptions: '全局设置',
  1668. ok: '是',
  1669. save: '保存',
  1670. close: '关闭',
  1671. return: '返回',
  1672. option: '选项',
  1673. value: '值',
  1674. websiteOptions: '当前网站设置',
  1675. changeWebsiteOptionsSuccess: '更改当前网站设置成功,刷新生效!',
  1676. changeGlobalOptionsSuccess: '更改全局设置成功,刷新生效!',
  1677. needLogin: '请先登录!',
  1678. getTasksInfo: '正在获取并处理任务信息...',
  1679. gettingKey: '正在获取Key...',
  1680. verifyingTask: '正在验证任务',
  1681. notice: '自动任务脚本提醒',
  1682. noKeysLeft: '此页面已经没有剩余key了,是否关闭?',
  1683. giveawayEnded: '此活动已结束,是否关闭?',
  1684. giveawayNotWork: '此活动因某些原因(已结束/暂停/未开始...)不可用(如果是脚本误判请及时反馈),是否关闭?',
  1685. confirm: '确定',
  1686. cancel: '取消',
  1687. unKnown: '未知',
  1688. unKnownTaskType: '未识别的任务',
  1689. doing: '正在做任务',
  1690. allTasksComplete: '所有任务已完成!',
  1691. getTaskIdFailed: '获取任务Id失败!',
  1692. initSuccess: '%0 初始化成功!',
  1693. initFailed: '%0 初始化失败!',
  1694. errorLink: '链接错误: %0',
  1695. needInit: '请先初始化',
  1696. verifyingAuth: '正在验证%0凭证...',
  1697. updatingAuth: '正在更新%0凭证...',
  1698. refreshingToken: '正在刷新%0凭证...',
  1699. settingToken: '正在设置%0凭证...',
  1700. steamStoreTab: 'Steam商店(弹窗)',
  1701. steamCommunityTab: 'Steam社区(弹窗)',
  1702. initing: '正在初始化...',
  1703. getFailed: '获取%0失败!',
  1704. checkLoginFailed: '检测登录状态失败!',
  1705. checkLeftKeyFailed: '检测剩余Key失败!',
  1706. userId: '用户Id',
  1707. joiningGiveaway: '正在加入赠Key',
  1708. needJoinGiveaway: '需要先加入赠Key',
  1709. cannotUndo: '此网站不支持取消任务',
  1710. verifyAuth: '正在验证 %0 凭证...',
  1711. closePageNotice: '如果此页面没有自动关闭,请自行关闭本页面。',
  1712. errorReport: '检测到脚本报错,是否前往反馈BUG?',
  1713. visitingLink: '正在访问链接...',
  1714. doTask: '做任务',
  1715. undoTask: '撤销任务',
  1716. verifyTask: '验证任务',
  1717. getKey: '获取Key',
  1718. selectAll: '全选',
  1719. selectNone: '全不选',
  1720. invertSelect: '反选',
  1721. doFreeTask: '加入免费赠品',
  1722. doPointTask: '加入点数赠品',
  1723. skipTaskOption: '设置中已配置跳过任务',
  1724. other: '其他',
  1725. globalOptions: '全局设置',
  1726. checkLogin: '登录检测</br>需要登录的网站自动登录,部分网站支持',
  1727. checkLeftKey: '剩余Key检测</br>赠Key活动结束提示是否关闭,部分网站支持',
  1728. twitterVerifyId: '通过尝试关注该账号验证Twitter凭证</br>默认为Twitter官方帐号 783214</br>不想关注官方账号可以改为自己的帐号',
  1729. youtubeVerifyChannel: '通过尝试订阅该频道验证YouTube凭证</br>默认为YouTube官方频道 UCrXUsMBcfTVqwAS7DKg9C0Q</br>不想关注官方频道可以改为自己的频道',
  1730. autoUpdateSource: '更新源</br>github: 需代理,实时更新</br>jsdelivr: 可不用代理,更新有延迟</br>standby: 备用</br>auto: 依次使用github, jsdelivr, standby源进行尝试更新',
  1731. saveGlobalOptions: '保存设置',
  1732. settingPage: '设置页面',
  1733. name: '名称',
  1734. version: '版本',
  1735. scriptManager: '脚本管理器',
  1736. script: '脚本',
  1737. environment: '环境',
  1738. os: '系统',
  1739. browser: '浏览器',
  1740. getId: '获取 %0 id',
  1741. getTwitterUserId: '获取Twitter用户id(获取id功能仅在设置页面可用)',
  1742. getYoutubeChannelId: '获取Youtube频道id(获取id功能仅在设置页面可用)',
  1743. showButton: '显示按钮',
  1744. hideButton: '隐藏按钮',
  1745. showLog: '显示日志',
  1746. hideLog: '隐藏日志',
  1747. defaultShowButton: '默认显示按钮',
  1748. defaultShowLog: '默认显示日志',
  1749. debug: '输出调试日志,不要开启此选项!',
  1750. receivePreview: '接收预览版更新',
  1751. position: '组件位置',
  1752. buttonSideX: '按钮区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1753. buttonSideY: '按钮区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1754. buttonDistance: '按钮区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1755. showButtonSideX: '显示按钮水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1756. showButtonSideY: '显示按钮垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1757. showButtonDistance: '显示按钮距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1758. logSideX: '日志区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1759. logSideY: '日志区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1760. logDistance: '日志区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1761. hotKey: '快捷键',
  1762. doTaskKey: '做任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1763. undoTaskKey: '撤销任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1764. toggleLogKey: '显示/隐藏日志快捷键</br>(实时预览功能仅在设置页面可用)',
  1765. tasksHistory: '任务历史',
  1766. clearHistory: '清空历史',
  1767. clearHistoryFinished: '已清空任务历史!',
  1768. deleteTask: '删除任务',
  1769. lastChangeTime: '最后一次修改时间',
  1770. clearTaskFinished: '删除以下任务完成!',
  1771. clearTaskFailed: '删除任务失败,没有找到任务名!',
  1772. syncData: '数据同步',
  1773. settingData: '正在上传数据...',
  1774. gettingData: '正在获取数据...',
  1775. help: '帮助',
  1776. fileName: '文件名',
  1777. upload2gist: '同步到Gist',
  1778. downloadFromGist: '从Gist同步',
  1779. saveAndTest: '保存配置并测试',
  1780. testSuccess: '测试成功!',
  1781. testFailed: '测试失败!',
  1782. saveAndTestNotice: '请先保存配置并测试!',
  1783. processingData: '正在处理数据...',
  1784. updatingData: '正在上传数据...',
  1785. syncDataSuccess: '同步数据成功!',
  1786. syncDataFailed: '同步数据失败,请在控制台查看错误信息!',
  1787. downloadingData: '正在下载数据...',
  1788. checkedNoData: '没有检测到远程数据,请确认配置是否正确!',
  1789. savingData: '正在保存数据...',
  1790. syncHistory: '同步任务历史',
  1791. checkUpdateFailed: '检测更新失败',
  1792. newVersionNotice: '检测到新版本V%0, <a class="high-light" href="%1" target="_blank">点此更新</a>',
  1793. language: '语言</br>目前仅支持zh: 中文, en: 英文',
  1794. gistOptions: 'Gist 设置',
  1795. swalNotice: '检测到您第一次安装V4版本脚本,请前往阅读用前必读内容!',
  1796. echoNotice: '检测到您第一次安装V4版本脚本,请<a class="high-light" href="%0" target="_blank">点此前往</a>阅读用前必读内容!',
  1797. noticeLink: 'https://auto-task-doc.js.org/guide/#用前必读',
  1798. toGithub: '前往Github反馈',
  1799. toKeylol: '前往其乐论坛反馈',
  1800. copySuccess: '错误信息已复制到剪切板,是否前往其乐论坛反馈?',
  1801. copyFailed: '请复制下方错误信息后前往Keylol论坛反馈!',
  1802. updateText: '%0 版本更新内容:',
  1803. Active: '进行中',
  1804. Ended: '已结束',
  1805. Banned: '已封禁',
  1806. Paused: '已暂停',
  1807. notStart: '未开始',
  1808. noRemoteData: '检测到远程无数据',
  1809. errorRemoteDataFormat: '远程数据格式错误',
  1810. updateHistory: '历史更新记录<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">点此查看</a>',
  1811. AsfEnabled: '使用ASF做Steam相关任务(需<a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a>插件)',
  1812. AsfIpcUrl: 'ASF IPC 地址',
  1813. AsfIpcPassword: 'ASF IPC 密码',
  1814. versionNotMatched: '脚本管理器版本过低,需TamperMonkey >= 5.2.0或TamperMonkey Beta >= 5.2.6196',
  1815. groups: '组',
  1816. officialGroups: '官方组',
  1817. wishlists: '愿望单',
  1818. follows: '游戏关注',
  1819. forums: '论坛',
  1820. workshops: '创意工坊收藏',
  1821. curators: '鉴赏家',
  1822. workshopVotes: '创意工坊点赞',
  1823. announcements: '社区通知',
  1824. steamCommunity: 'Steam社区',
  1825. steamStore: 'Steam商店',
  1826. licenses: '入库免费游戏',
  1827. playtests: '请求访问权限',
  1828. needLoginSteamStore: '请先<a href="https://store.steampowered.com/login/" target="_blank">登录Steam商店</a>',
  1829. needLoginSteamCommunity: '请先<a href="https://steamcommunity.com/login/home/" target="_blank">登录Steam社区</a>',
  1830. joiningSteamGroup: '正在加入Steam组',
  1831. leavingSteamGroup: '正在退出Steam组',
  1832. gettingSteamGroupId: '正在获取Steam组Id',
  1833. joiningSteamOfficialGroup: '正在加入Steam官方组',
  1834. leavingSteamOfficialGroup: '正在退出Steam官方组',
  1835. gettingSteamOfficialGroupId: '正在获取Steam官方组Id',
  1836. subscribingForum: '正在订阅Steam论坛',
  1837. unsubscribingForum: '正在取消订阅Steam论坛',
  1838. gettingForumId: '正在获取Steam论坛Id',
  1839. followingCurator: '正在关注Steam鉴赏家',
  1840. unfollowingCurator: '正在取关Steam鉴赏家',
  1841. gettingCuratorId: '正在获取Steam鉴赏家Id',
  1842. addingToWishlist: '正在添加游戏到Steam愿望单',
  1843. removingFromWishlist: '正在从Steam愿望单移除游戏',
  1844. followingGame: '正在关注Steam游戏',
  1845. unfollowingGame: '正在取关Steam游戏',
  1846. favoritingWorkshop: '正在收藏Steam创意工坊物品',
  1847. unfavoritingWorkshop: '正在取消收藏Steam创意工坊物品',
  1848. gettingWorkshopAppId: '正在获取Steam创意工坊物品Id',
  1849. votingUpWorkshop: '正在点赞Steam创意工坊物品',
  1850. gettingAnnouncementParams: '正在获取Steam通知信息',
  1851. likingAnnouncement: '正在点赞Steam通知',
  1852. changingArea: '正在更换Steam地区: %0...',
  1853. notNeededChangeArea: '当前地区不需要更换',
  1854. noAnotherArea: '请检测是否开启正确开启代理',
  1855. gettingAreaInfo: '正在获取Steam地区信息...',
  1856. changeAreaNotice: '疑似锁区游戏,尝试换区执行',
  1857. steamFinishNotice: 'Steam任务完成,尝试将购物车地区换回',
  1858. gettingSubid: '正在获取游戏subid',
  1859. addingFreeLicense: '正在入库',
  1860. missParams: '缺少参数',
  1861. gettingLicenses: '正在获取Licenses...',
  1862. requestingPlayTestAccess: '正在请求访问权限',
  1863. tryChangeAreaNotice: '此功能无法检测游戏是否限区,因此会尝试换区后再入库,换区失败也不影响后续入库',
  1864. gettingUserLink: '正在获取Steam用户社区链接...',
  1865. retry: '重试',
  1866. owned: '已拥有',
  1867. redirect: '重定向',
  1868. noSubid: '无法获取,跳过',
  1869. initingASF: '正在初始化ASF...',
  1870. servers: '服务器',
  1871. joiningDiscordServer: '正在加入Discord服务器',
  1872. leavingDiscordServer: '正在退出Discord服务器',
  1873. gettingDiscordGuild: '正在获取Discord服务器Id',
  1874. getDiscordAuthFailed: '获取Discord凭证失败,请检测Discord帐号是否已登录',
  1875. discordImportantNotice: '重要提醒!!!',
  1876. discordImportantNoticeText: '由于Discord网站后台更新,目前使用此脚本加组后可能会导致Discord帐号被强制退出,且需要两步验证才能正常登录,请谨慎使用!!!',
  1877. continue: '继续',
  1878. skipDiscordTask: '跳过Discord任务',
  1879. continueAndDontRemindAgain: '继续且不再提醒',
  1880. users: '用户',
  1881. loginIns: '请先<a href="https://www.instagram.com/accounts/login/" target="_blank">登录Instagram</a>',
  1882. insBanned: '您的Instagram账户已被封禁',
  1883. verifyingInsAuth: '正在验证Instagram凭证...',
  1884. gettingInsUserId: '正在获取Instagram用户Id',
  1885. followingIns: '正在关注Instagram用户',
  1886. unfollowingIns: '正在取关Instagram用户',
  1887. reddits: '社区/用户',
  1888. loginReddit: '请先<a href="https://www.reddit.com/login/" target="_blank">登录Reddit</a>',
  1889. changingRedditVersion: '正在切换Reddit为新版页面...',
  1890. joiningReddit: '正在加入Reddit社区',
  1891. leavingReddit: '正在退出Reddit社区',
  1892. followingRedditUser: '正在关注Reddit用户',
  1893. unfollowingRedditUser: '正在取关Reddit用户',
  1894. channels: '频道',
  1895. followingTwitchChannel: '正在关注Twitch频道',
  1896. unfollowingTwitchChannel: '正在取关Twitch频道',
  1897. gettingTwitchChannelId: '正在获取Twitch频道Id',
  1898. checkingTwitchIntegrity: '正在检查Twitch完整性...',
  1899. twitterUser: '推特用户',
  1900. retweets: '转推',
  1901. gettingTwitterUserId: '正在获取推特用户Id',
  1902. followingTwitterUser: '正在关注推特用户',
  1903. unfollowingTwitterUser: '正在取关推特用户',
  1904. retweetting: '正在转推',
  1905. unretweetting: '正在撤销转推',
  1906. names: '组/社区/动态',
  1907. loginVk: '请先<a href="https://vk.com/login/" target="_blank">登录Vk</a>',
  1908. gettingVkId: '正在获取Vk任务Id',
  1909. joiningVkGroup: '正在加入Vk组',
  1910. leavingVkGroup: '正在退出Vk组',
  1911. joiningVkPublic: '正在加入Vk社区',
  1912. leavingVkPublic: '正在退出Vk社区',
  1913. sendingVkWall: '正在转发Vk动态',
  1914. deletingVkWall: '正在撤销转发Vk动态',
  1915. youtubeChannel: 'YouTube频道',
  1916. likes: '点赞',
  1917. loginYtb: '请先<a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">登录YouTube</a>',
  1918. tryUpdateYtbAuth: '请尝试<a href="https://www.youtube.com/#auth" target="_blank">更新YouTube凭证</a>',
  1919. gettingYtbToken: '正在获取YouTube Token...',
  1920. followingYtbChannel: '正在订阅YouTube频道',
  1921. unfollowingYtbChannel: '正在退订YouTube频道',
  1922. likingYtbVideo: '正在点赞YouTube视频',
  1923. unlikingYtbVideo: '正在取消点赞YouTube视频',
  1924. giveKeyNoticeBefore: '每次验证间隔15s',
  1925. giveKeyNoticeAfter: '如果没有key, 请在<a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>查看',
  1926. noPoints: '点数不够,跳过抽奖',
  1927. getNeedPointsFailed: '获取所需点数失败,跳过抽奖',
  1928. joiningLottery: '正在加入抽奖',
  1929. doingGleamTask: '正在做Gleam任务...',
  1930. gettingGleamLink: '正在获取Gleam任务链接...',
  1931. gleamTaskNotice: '如果此页面长时间未关闭,请完成任一任务后自行关闭!',
  1932. verifiedGleamTasks: '已尝试验证所有任务,验证失败的任务请尝试手动验证或完成!',
  1933. campaign: '检测到人机验证,请完成验证后重新验证任务!',
  1934. gsNotice: '为避免得到"0000-0000-0000"key, 已自动屏蔽"Grab Key"按钮,获取key时请关闭脚本!',
  1935. giveeClubVerifyNotice: '正在验证任务...',
  1936. giveeClubVerifyFinished: '请等待验证完成后自行加入赠Key',
  1937. doingKeyhubTask: '正在做Keyhub任务...',
  1938. SweepWidgetNotice: '正在处理并验证任务,每次验证任务有1~3s间隔防止触发验证过快警告...',
  1939. tasksNotCompleted: '任务未完成',
  1940. notConnect: '社交平台未连接,跳过任务',
  1941. tgTaskNotice: '检测到Telegram任务,需要手动完成',
  1942. confirmingTask: '正在跳过警告页面...'
  1943. };
  1944. const zh_CN = data;
  1945. const en_US_data = {
  1946. website: 'Website',
  1947. type: 'Type',
  1948. edit: 'Edit',
  1949. whiteList: 'Whitelist',
  1950. skipTask: 'Skip undo task',
  1951. whiteListOptions: 'Whitelist options',
  1952. changeWhiteListOption: 'Whitelist option(%0)',
  1953. whiteListNotFound: 'Cannot find this whitelist: %0',
  1954. changeWhiteListSuccess: 'The whitelist is successfully modified, and the page refresh will take effect!',
  1955. changeWebsiteOptions: 'Website options',
  1956. changeGlobalOptions: 'Global options',
  1957. ok: 'OK',
  1958. save: 'Save',
  1959. close: 'Close',
  1960. return: 'Return',
  1961. option: 'Option',
  1962. value: 'Value',
  1963. websiteOptions: 'Current website settings',
  1964. changeWebsiteOptionsSuccess: 'The current website setting is changed successfully, and the page refresh will take effect!',
  1965. changeGlobalOptionsSuccess: 'The global setting is changed successfully, and the refresh will take effect!',
  1966. needLogin: 'Please log in first!',
  1967. getTasksInfo: 'Obtaining and processing task information...',
  1968. gettingKey: 'Getting Key...',
  1969. verifyingTask: 'Verifying task',
  1970. notice: 'Automatic task script notice',
  1971. noKeysLeft: 'There are no more keys left on this page. Do you want to close it?',
  1972. giveawayEnded: 'This event has ended, do you want to close it?',
  1973. 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?',
  1974. confirm: 'Confirm',
  1975. cancel: 'Cancel',
  1976. unKnown: 'Unknown',
  1977. unKnownTaskType: 'Unrecognized task',
  1978. doing: 'Doing a task',
  1979. allTasksComplete: 'All tasks have been completed!',
  1980. getTaskIdFailed: 'Failed to obtain task Id!',
  1981. initSuccess: '%0 was initialized successfully!',
  1982. initFailed: '%0 initialization failed!',
  1983. errorLink: 'Link error: %0',
  1984. needInit: 'Please initialize first',
  1985. verifyingAuth: 'Verifying %0 token...',
  1986. updatingAuth: 'Update %0 token...',
  1987. refreshingToken: 'Refreshing %0 token...',
  1988. settingToken: 'Setting %0 token...',
  1989. steamStoreTab: 'Steam store (new tab)',
  1990. steamCommunityTab: 'Steam community(new tab)',
  1991. initing: 'Initializing...',
  1992. getFailed: 'Failed to get %0!',
  1993. checkLoginFailed: 'Failed to detect login status!',
  1994. checkLeftKeyFailed: 'Failed to detect the remaining keys!',
  1995. userId: 'User Id',
  1996. joiningGiveaway: 'Joining giveaway',
  1997. needJoinGiveaway: 'Need to join the giveaway first',
  1998. cannotUndo: 'This website does not support canceling tasks',
  1999. verifyAuth: 'Verifying %0 token...',
  2000. closePageNotice: 'f this page does not close automatically, please close this page yourself.',
  2001. errorReport: 'A script error is detected, do you want to report the BUG?',
  2002. visitingLink: 'Visiting link ...',
  2003. doTask: 'DoTask',
  2004. undoTask: 'UndoTask',
  2005. verifyTask: 'Verify',
  2006. getKey: 'GetKey',
  2007. selectAll: 'SelectAll',
  2008. selectNone: 'SelectNone',
  2009. invertSelect: 'InvertSelect',
  2010. doFreeTask: 'FreeTask',
  2011. doPointTask: 'PointTask',
  2012. skipTaskOption: 'Skip task has been configured in the settings',
  2013. other: 'Other',
  2014. globalOptions: 'Global Options',
  2015. checkLogin: 'Login detection</br>Need to log in to the website automatically log in, part of this website supports.',
  2016. checkLeftKey: 'Key remaining detection</br>The end of the giveaway event prompts whether to close or not, part of this website supports.',
  2017. 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.',
  2018. 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.',
  2019. 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.',
  2020. saveGlobalOptions: 'SaveSettings',
  2021. settingPage: 'Setting Page',
  2022. name: 'Name',
  2023. version: 'Version',
  2024. scriptManager: 'Script Manager',
  2025. script: 'Script',
  2026. environment: 'Environment',
  2027. os: 'OS',
  2028. browser: 'Browser',
  2029. getId: 'Get %0 id',
  2030. getTwitterUserId: 'Get Twitter user id (Get id function is only available on the settings page).',
  2031. getYoutubeChannelId: 'Get Youtube channel id (Get id function is only available on the settings page).',
  2032. showButton: 'ShowButton',
  2033. hideButton: 'HideButton',
  2034. showLog: 'ShowLog',
  2035. hideLog: 'HideLog',
  2036. defaultShowButton: 'Default display button',
  2037. defaultShowLog: 'Display log by default',
  2038. debug: 'Output debug log, do not enable this option!',
  2039. receivePreview: 'Receive preview updates',
  2040. position: 'Component position',
  2041. buttonSideX: 'Horizontal positioning of the button area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  2042. 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',
  2043. 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',
  2044. showButtonSideX: 'ShowButton horizontal positioning (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  2045. showButtonSideY: 'ShowButton vertical positioning (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  2046. 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',
  2047. logSideX: 'Horizontal positioning of the log area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  2048. logSideY: 'Vertical positioning of the log area (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  2049. 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',
  2050. hotKey: 'Shortcut key',
  2051. doTaskKey: 'DoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  2052. undoTaskKey: 'UndoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  2053. toggleLogKey: 'ShowLog/HideLog shortcut keys</br> (real-time preview function is only available on the settings page).',
  2054. tasksHistory: 'TasksHistory',
  2055. clearHistory: 'Clear history',
  2056. clearHistoryFinished: 'The mission history has been cleared!',
  2057. deleteTask: 'Delete task',
  2058. lastChangeTime: 'Last Change Time',
  2059. clearTaskFinished: 'Delete the following tasks completed!',
  2060. clearTaskFailed: 'Failed to delete the task, the task name was not found!',
  2061. syncData: 'DataSync',
  2062. settingData: 'Uploading data...',
  2063. gettingData: 'Getting data...',
  2064. help: 'Help',
  2065. fileName: 'Filename',
  2066. upload2gist: 'Sync to Gist',
  2067. downloadFromGist: 'Sync from Gist',
  2068. saveAndTest: 'Save configuration and test',
  2069. testSuccess: 'Test success!',
  2070. testFailed: 'Test failed!',
  2071. saveAndTestNotice: 'Please save the configuration and test first!',
  2072. processingData: 'Processing data...',
  2073. updatingData: 'Uploading data...',
  2074. syncDataSuccess: 'Synchronized data successfully!',
  2075. syncDataFailed: 'Failed to synchronize data, please check the error message on the console!',
  2076. downloadingData: 'Downloading data...',
  2077. checkedNoData: 'No remote data is detected, please confirm whether the configuration is correct!',
  2078. savingData: 'Saving data...',
  2079. syncHistory: 'Synchronize tasks history',
  2080. checkUpdateFailed: 'Check update failed',
  2081. newVersionNotice: 'Checked a new version V%0, <a class="high-light" href="%1" target="_blank">click to update</a>',
  2082. language: 'Language</br> Currently only supports zh: Chinese, en: English',
  2083. gistOptions: 'Gist Settings',
  2084. 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!',
  2085. 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!',
  2086. noticeLink: 'https://auto-task-doc.js.org/en/guide/#read-me-first',
  2087. toGithub: 'Feedback(Github)',
  2088. toKeylol: 'Feedback(Keylol)',
  2089. copySuccess: 'The error message has been copied to the clipboard. Do you want to go to the Keylol forum to give feedback?',
  2090. copyFailed: 'Please copy the error information below and report back to the Keylol forum!',
  2091. updateText: 'Updates in version %0:',
  2092. Active: 'Active',
  2093. Ended: 'Ended',
  2094. Banned: 'Banned',
  2095. Paused: 'Paused',
  2096. notStart: 'notStart',
  2097. noRemoteData: 'No data remotely',
  2098. errorRemoteDataFormat: 'Remote data has wrong format',
  2099. updateHistory: '<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">Click here</a>' + ' to view the historical update record.',
  2100. AsfEnabled: 'Use ASF to do Steam related tasks (requires <a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a> plugin)',
  2101. AsfIpcUrl: 'ASF IPC URL',
  2102. AsfIpcPassword: 'ASF IPC Password',
  2103. groups: 'Group',
  2104. officialGroups: 'Official Group',
  2105. wishlists: 'Wishlist',
  2106. follows: 'Follow Game',
  2107. forums: 'Forum',
  2108. workshops: 'Favorite Workshop',
  2109. curators: 'Curator',
  2110. workshopVotes: 'Voteup Workshop',
  2111. announcements: 'Announcement',
  2112. steamCommunity: 'Steam Community',
  2113. steamStore: 'Steam Store',
  2114. licenses: 'Add License',
  2115. playtests: 'Playtest Access',
  2116. needLoginSteamStore: 'Please <a href="https://store.steampowered.com/login/" target="_blank">log in to the Steam Store</a>',
  2117. needLoginSteamCommunity: 'Please <a href="https://steamcommunity.com/login/home/" target="_blank">log in to the Steam Community</a>',
  2118. joiningSteamGroup: 'Joining Steam Group',
  2119. leavingSteamGroup: 'Leaving Steam Group',
  2120. gettingSteamGroupId: 'Getting Steam Group Id',
  2121. joiningSteamOfficialGroup: 'Joining Steam Official Group',
  2122. leavingSteamOfficialGroup: 'Leaving Steam Official Group',
  2123. gettingSteamOfficialGroupId: 'Getting Steam Official Group Id',
  2124. subscribingForum: 'Subscribing the Steam Forum',
  2125. unsubscribingForum: 'Unsubscribing the Steam Forum',
  2126. gettingForumId: 'Getting Steam Forum Id',
  2127. followingCurator: 'Following Steam Curator',
  2128. unfollowingCurator: 'Unfollowing Steam Curator',
  2129. gettingCuratorId: 'Getting Steam Curator Id',
  2130. addingToWishlist: 'Adding the game to the Steam wishlist',
  2131. removingFromWishlist: 'Removing the game from the Steam wishlist',
  2132. followingGame: 'Following Steam games',
  2133. unfollowingGame: 'Unfollowing Steam games',
  2134. favoritingWorkshop: 'Favouring Steam Workshop Items',
  2135. unfavoritingWorkshop: 'Unfavoriting Steam Workshop Items',
  2136. gettingWorkshopAppId: 'Getting Steam Workshop Item Id',
  2137. votingUpWorkshop: 'Liking Steam workshop items',
  2138. gettingAnnouncementParams: 'Getting Steam announcement information',
  2139. likingAnnouncement: 'Liking Steam announcement',
  2140. changingArea: 'Changing Steam area: %0...',
  2141. notNeededChangeArea: 'The current area does not need to be changed',
  2142. noAnotherArea: 'Please check whether the proxy is turned on correctly',
  2143. gettingAreaInfo: 'Getting Steam area information...',
  2144. changeAreaNotice: 'Suspected of a locked zone game, try to change the zone to execute',
  2145. steamFinishNotice: 'Steam task completed, try to change the shopping cart area back to ',
  2146. gettingSubid: 'Getting subid',
  2147. addingFreeLicense: 'Adding free license',
  2148. missParams: 'Missing parameters',
  2149. gettingLicenses: 'Getting licenses...',
  2150. requestingPlayTestAccess: 'Requesting play test access',
  2151. 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.',
  2152. versionNotMatched: 'The script manager version is too low, requiring TamperMonkey >= 5.2.0 or TamperMonkey Beta >= 5.2.6196',
  2153. gettingUserLink: 'Getting steam user community link...',
  2154. retry: 'Retry',
  2155. owned: 'Owned',
  2156. redirect: 'Redirect',
  2157. noSubid: 'skip due to unrecognized',
  2158. initingASF: 'Initing ASF...',
  2159. servers: 'Server',
  2160. joiningDiscordServer: 'Joining Discord Server',
  2161. leavingDiscordServer: 'Leaving Discord Server',
  2162. gettingDiscordGuild: 'Getting Discord server Id',
  2163. getDiscordAuthFailed: 'Failed to get Discord token, please check whether the Discord account is logged in',
  2164. discordImportantNotice: 'Important Reminder! ! !',
  2165. 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! ! !',
  2166. continue: 'Continue',
  2167. skipDiscordTask: 'Skip',
  2168. continueAndDontRemindAgain: 'Continue without Reminders',
  2169. users: 'User',
  2170. loginIns: 'Please <a href="https://www.instagram.com/accounts/login/" target="_blank">log in to Instagram</a>',
  2171. insBanned: 'Your Instagram account has been banned',
  2172. verifyingInsAuth: 'Verifying Instagram token...',
  2173. gettingInsUserId: 'Getting Instagram user Id',
  2174. followingIns: 'Following Instagram user',
  2175. unfollowingIns: 'Unfollowing Instagram user',
  2176. reddits: 'Reddit/User',
  2177. loginReddit: 'Please <a href="https://www.reddit.com/login/" target="_blank">log in to Reddit</a>',
  2178. changingRedditVersion: 'Switching Reddit to a new version page...',
  2179. joiningReddit: 'Joining the Reddit',
  2180. leavingReddit: 'Leaving the Reddit',
  2181. followingRedditUser: 'Following Reddit User',
  2182. unfollowingRedditUser: 'Unfollowing Reddit User',
  2183. channels: 'Channel',
  2184. followingTwitchChannel: 'Following Twitch Channel',
  2185. unfollowingTwitchChannel: 'Unfollowing Twitch Channel',
  2186. gettingTwitchChannelId: 'Getting Twitch Channel Id',
  2187. checkingTwitchIntegrity: 'Checking Twitch integrity...',
  2188. twitterUser: 'Twitter User',
  2189. retweets: 'Retweet',
  2190. gettingTwitterUserId: 'Getting Twitter User Id',
  2191. followingTwitterUser: 'Following Twitter User',
  2192. unfollowingTwitterUser: 'Unfollowing Twitter User',
  2193. retweetting: 'Retweetting',
  2194. unretweetting: 'Unretweetting',
  2195. names: 'Group/Public/Wall',
  2196. loginVk: 'Please <a href="https://vk.com/login/" target="_blank">log in to Vk</a>',
  2197. gettingVkId: 'Getting Vk task Id',
  2198. joiningVkGroup: 'Joining Vk Group',
  2199. leavingVkGroup: 'Leaving Vk Group',
  2200. joiningVkPublic: 'Joining Vk Public',
  2201. leavingVkPublic: 'Leaving Vk Public',
  2202. sendingVkWall: 'Sending Vk Wall',
  2203. deletingVkWall: 'Deleting Vk Wall',
  2204. youtubeChannel: 'YouTube Channel',
  2205. likes: 'Like',
  2206. loginYtb: 'Please <a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">log in to YouTube</a>',
  2207. tryUpdateYtbAuth: 'Please try to <a href="https://www.youtube.com/#auth" target="_blank">update YouTube token</a>',
  2208. gettingYtbToken: 'Getting YouTube Token...',
  2209. followingYtbChannel: 'Subscribing to YouTube channel',
  2210. unfollowingYtbChannel: 'Unsubscribing to YouTube channel',
  2211. likingYtbVideo: 'Liking YouTube video',
  2212. unlikingYtbVideo: 'Unliking YouTube video',
  2213. giveKeyNoticeBefore: 'Each verification interval is 15s',
  2214. giveKeyNoticeAfter: 'If there is no key, please check at <a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>',
  2215. noPoints: 'Not enough points, skip the lottery',
  2216. getNeedPointsFailed: 'ailed to obtain the required points, skip the lottery',
  2217. joiningLottery: 'Joining the lottery',
  2218. doingGleamTask: 'Doing Gleam Task...',
  2219. gettingGleamLink: 'Getting Gleam task link...',
  2220. gleamTaskNotice: 'If this page has not been closed for a long time, please close it yourself after completing any task!',
  2221. verifiedGleamTasks: 'Attempted to verify all tasks. If the verification fails, please try to verify manually or complete it!',
  2222. campaign: 'ReCAPTCHA detected, please complete it and re-verify the tasks!',
  2223. 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!',
  2224. giveeClubVerifyNotice: 'Verifying task...',
  2225. giveeClubVerifyFinished: 'Wait for the verification to complete and join it by yourself',
  2226. doingKeyhubTask: 'Doing Keyhub Task...',
  2227. 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...',
  2228. tasksNotCompleted: 'Tasks Not Completed',
  2229. notConnect: 'Social platform is not connectted, skip',
  2230. tgTaskNotice: 'The telegram task is checked, need to do it yourself!',
  2231. confirmingTask: 'Confirming task...'
  2232. };
  2233. const en_US = en_US_data;
  2234. const languages = {
  2235. zh: zh_CN,
  2236. en: en_US
  2237. };
  2238. const language = [ 'zh', 'en' ].includes(globalOptions.other.language) ? globalOptions.other.language : 'en';
  2239. const I18n = (key, ...argvs) => {
  2240. if (!languages[language]?.[key]) {
  2241. return key;
  2242. }
  2243. return languages[language][key].replace(/%([\d]+)/g, (match, index) => argvs[parseInt(index, 10)]);
  2244. };
  2245. const i18n = I18n;
  2246. function throwError(error, name) {
  2247. if (window.TRACE) {
  2248. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  2249. }
  2250. external_Swal_default().fire({
  2251. title: i18n('errorReport'),
  2252. icon: 'error',
  2253. showCancelButton: true,
  2254. confirmButtonText: i18n('toGithub'),
  2255. showDenyButton: true,
  2256. denyButtonText: i18n('toKeylol'),
  2257. cancelButtonText: i18n('close')
  2258. }).then(({
  2259. isDenied,
  2260. isConfirmed
  2261. }) => {
  2262. if (isConfirmed) {
  2263. 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,
  2264. 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'))}`, {
  2265. active: true
  2266. });
  2267. } else if (isDenied) {
  2268. const text = `错误链接: [url=${window.location.href}]${window.location.href}[/url]
  2269.  
  2270. 环境:
  2271.  
  2272. [code]${JSON.stringify((0, javascript_utils_umd_min.ua)(), null, 4)}[/code]
  2273.  
  2274. 脚本管理器: ${GM_info.scriptHandler} ${GM_info.version}
  2275. 脚本版本: ${GM_info.script.version}
  2276.  
  2277. 报错信息:
  2278. [code]${error.stack}[/code]
  2279.  
  2280. 执行日志:
  2281. [code]${$.makeArray($('#auto-task-info>li')).map(element => element.innerText).join('\n')}[/code]`;
  2282. GM_setClipboard(text);
  2283. external_Swal_default().fire({
  2284. title: i18n('copySuccess'),
  2285. icon: 'success',
  2286. confirmButtonText: i18n('ok')
  2287. }).then(() => {
  2288. GM_openInTab('https://keylol.com/forum.php?mod=post&action=reply&fid=319&tid=777450', {
  2289. active: true
  2290. });
  2291. });
  2292. }
  2293. });
  2294. console.log('%c%s', 'color:white;background:red', `Auto-Task[Error]: ${name}\n${error.stack}`);
  2295. }
  2296. class Social {
  2297. tasks;
  2298. getRealParams(name, links, doTask, link2param) {
  2299. try {
  2300. let realParams = [];
  2301. if (links.length > 0) {
  2302. realParams = [ ...realParams, ...links.map(link => link2param(link)).filter(link => link) ];
  2303. }
  2304. if (!doTask && this.tasks[name].length > 0) {
  2305. realParams = [ ...realParams, ...this.tasks[name] ];
  2306. }
  2307. return unique(realParams);
  2308. } catch (error) {
  2309. throwError(error, 'Social.getRealParams');
  2310. return [];
  2311. }
  2312. }
  2313. }
  2314. const social_Social = Social;
  2315. class Discord extends social_Social {
  2316. tasks;
  2317. whiteList;
  2318. #auth = GM_getValue('discordAuth') || {};
  2319. #cache = GM_getValue('discordCache') || {};
  2320. #initialized = false;
  2321. constructor() {
  2322. super();
  2323. const defaultTasksTemplate = {
  2324. servers: []
  2325. };
  2326. this.tasks = defaultTasksTemplate;
  2327. this.whiteList = {
  2328. ...defaultTasksTemplate,
  2329. ...GM_getValue('whiteList')?.discord || {}
  2330. };
  2331. }
  2332. async init(action) {
  2333. try {
  2334. if (!GM_getValue('dontRemindDiscordAgain')) {
  2335. const result = await external_Swal_default().fire({
  2336. title: i18n('discordImportantNotice'),
  2337. text: i18n('discordImportantNoticeText'),
  2338. showCancelButton: true,
  2339. showDenyButton: true,
  2340. confirmButtonText: i18n('continue'),
  2341. cancelButtonText: i18n('skipDiscordTask'),
  2342. denyButtonText: i18n('continueAndDontRemindAgain')
  2343. }).then(({
  2344. isConfirmed,
  2345. isDenied
  2346. }) => {
  2347. if (isConfirmed) {
  2348. return true;
  2349. }
  2350. if (isDenied) {
  2351. GM_setValue('dontRemindDiscordAgain', true);
  2352. return true;
  2353. }
  2354. return false;
  2355. });
  2356. if (!result) {
  2357. this.#initialized = false;
  2358. return 'skip';
  2359. }
  2360. }
  2361. if (GM_getValue('dontRemindDiscordAgain') || action === 'do' && !globalOptions.doTask.discord.servers || action === 'undo' && !globalOptions.undoTask.discord.servers) {
  2362. this.#initialized = false;
  2363. return 'skip';
  2364. }
  2365. if (this.#initialized) {
  2366. return true;
  2367. }
  2368. if (!this.#auth.auth) {
  2369. if (await this.#updateAuth()) {
  2370. this.#initialized = true;
  2371. return true;
  2372. }
  2373. return false;
  2374. }
  2375. const isVerified = await this.#verifyAuth();
  2376. if (isVerified) {
  2377. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  2378. this.#initialized = true;
  2379. return true;
  2380. }
  2381. GM_setValue('discordAuth', {
  2382. auth: null
  2383. });
  2384. if (await this.#updateAuth()) {
  2385. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  2386. this.#initialized = true;
  2387. return true;
  2388. }
  2389. scripts_echoLog({}).error(i18n('initFailed', 'Discord'));
  2390. return false;
  2391. } catch (error) {
  2392. throwError(error, 'Discord.init');
  2393. return false;
  2394. }
  2395. }
  2396. async #verifyAuth() {
  2397. try {
  2398. const logStatus = scripts_echoLog({
  2399. text: i18n('verifyingAuth', 'Discord')
  2400. });
  2401. const {
  2402. result,
  2403. statusText,
  2404. status,
  2405. data
  2406. } = await tools_httpRequest({
  2407. url: 'https://discord.com/api/v6/users/@me',
  2408. method: 'HEAD',
  2409. headers: {
  2410. authorization: this.#auth.auth
  2411. }
  2412. });
  2413. if (result === 'Success') {
  2414. if (data?.status === 200) {
  2415. logStatus.success();
  2416. return true;
  2417. }
  2418. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2419. return false;
  2420. }
  2421. logStatus.error(`${result}:${statusText}(${status})`);
  2422. return false;
  2423. } catch (error) {
  2424. throwError(error, 'Discord.verifyAuth');
  2425. return false;
  2426. }
  2427. }
  2428. async #updateAuth() {
  2429. try {
  2430. const logStatus = scripts_echoLog({
  2431. text: i18n('updatingAuth', 'Discord')
  2432. });
  2433. return await new Promise(resolve => {
  2434. const newTab = GM_openInTab('https://discord.com/channels/@me', {
  2435. active: true,
  2436. insert: true,
  2437. setParent: true
  2438. });
  2439. newTab.name = 'ATv4_discordAuth';
  2440. newTab.onclose = async () => {
  2441. const auth = GM_getValue('discordAuth')?.auth;
  2442. if (auth) {
  2443. this.#auth = {
  2444. auth: auth
  2445. };
  2446. logStatus.success();
  2447. resolve(await this.#verifyAuth());
  2448. } else {
  2449. logStatus.error('Error: Update discord auth failed!');
  2450. resolve(false);
  2451. }
  2452. };
  2453. });
  2454. } catch (error) {
  2455. throwError(error, 'Discord.updateAuth');
  2456. return false;
  2457. }
  2458. }
  2459. async #joinServer(inviteId) {
  2460. try {
  2461. const logStatus = scripts_echoLog({
  2462. type: 'joiningDiscordServer',
  2463. text: inviteId
  2464. });
  2465. const {
  2466. result,
  2467. statusText,
  2468. status,
  2469. data
  2470. } = await tools_httpRequest({
  2471. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2472. method: 'POST',
  2473. dataType: 'json',
  2474. headers: {
  2475. authorization: this.#auth.auth,
  2476. origin: 'https://discord.com',
  2477. referer: `https://discord.com/invite/${inviteId}`
  2478. }
  2479. });
  2480. if (result === 'Success' && data?.status === 200) {
  2481. logStatus.success();
  2482. const guild = String(data.response?.guild?.id);
  2483. if (guild) {
  2484. this.#setCache(inviteId, guild);
  2485. this.tasks.servers = unique([ ...this.tasks.servers, inviteId ]);
  2486. }
  2487. return true;
  2488. }
  2489. logStatus.error(`${result}:${statusText}(${status})`);
  2490. return false;
  2491. } catch (error) {
  2492. throwError(error, 'Discord.joinServer');
  2493. return false;
  2494. }
  2495. }
  2496. async #leaveServer(inviteId) {
  2497. try {
  2498. if (this.whiteList.servers.includes(inviteId)) {
  2499. scripts_echoLog({
  2500. type: 'whiteList',
  2501. text: 'Discord.leaveServer',
  2502. id: inviteId
  2503. });
  2504. return true;
  2505. }
  2506. const guild = await this.#getGuild(inviteId);
  2507. if (!guild) {
  2508. return false;
  2509. }
  2510. const logStatus = scripts_echoLog({
  2511. type: 'leavingDiscordServer',
  2512. text: guild
  2513. });
  2514. const {
  2515. result,
  2516. statusText,
  2517. status,
  2518. data
  2519. } = await tools_httpRequest({
  2520. url: `https://discord.com/api/v9/users/@me/guilds/${guild}`,
  2521. method: 'DELETE',
  2522. headers: {
  2523. authorization: this.#auth.auth
  2524. }
  2525. });
  2526. if (result === 'Success' && data?.status === 204) {
  2527. logStatus.success();
  2528. return true;
  2529. }
  2530. logStatus.error(`${result}:${statusText}(${status})`);
  2531. return false;
  2532. } catch (error) {
  2533. throwError(error, 'Discord.leaveServer');
  2534. return false;
  2535. }
  2536. }
  2537. async #getGuild(inviteId) {
  2538. try {
  2539. const logStatus = scripts_echoLog({
  2540. type: 'gettingDiscordGuild',
  2541. text: inviteId
  2542. });
  2543. const guild = this.#cache[inviteId];
  2544. if (guild) {
  2545. logStatus.success();
  2546. return guild;
  2547. }
  2548. const {
  2549. result,
  2550. statusText,
  2551. status,
  2552. data
  2553. } = await tools_httpRequest({
  2554. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2555. responseType: 'json',
  2556. method: 'GET'
  2557. });
  2558. if (result === 'Success' && data?.status === 200) {
  2559. const guild = data.response?.guild?.id;
  2560. if (guild) {
  2561. logStatus.success();
  2562. this.#setCache(inviteId, guild);
  2563. return guild;
  2564. }
  2565. logStatus.error(`${result}:${statusText}(${status})`);
  2566. return false;
  2567. }
  2568. logStatus.error(`${result}:${statusText}(${status})`);
  2569. return false;
  2570. } catch (error) {
  2571. throwError(error, 'Discord.getGuild');
  2572. return false;
  2573. }
  2574. }
  2575. async toggle({
  2576. doTask = true,
  2577. serverLinks = []
  2578. }) {
  2579. try {
  2580. if (!this.#initialized) {
  2581. scripts_echoLog({
  2582. text: i18n('needInit')
  2583. });
  2584. return false;
  2585. }
  2586. const prom = [];
  2587. if (doTask && !globalOptions.doTask.discord.servers || !doTask && !globalOptions.undoTask.discord.servers) {
  2588. scripts_echoLog({
  2589. type: 'globalOptionsSkip',
  2590. text: 'discord.servers'
  2591. });
  2592. } else {
  2593. const realServers = this.getRealParams('servers', serverLinks, doTask, link => link.match(/invite\/(.+)/)?.[1]);
  2594. if (realServers.length > 0) {
  2595. for (const server of realServers) {
  2596. if (doTask) {
  2597. prom.push(this.#joinServer(server));
  2598. } else {
  2599. prom.push(this.#leaveServer(server));
  2600. }
  2601. await delay(1e3);
  2602. }
  2603. }
  2604. }
  2605. return await Promise.all(prom).then(() => true);
  2606. } catch (error) {
  2607. throwError(error, 'Discord.toggleServers');
  2608. return false;
  2609. }
  2610. }
  2611. #setCache(inviteId, guild) {
  2612. try {
  2613. this.#cache[inviteId] = guild;
  2614. GM_setValue('discordCache', this.#cache);
  2615. } catch (error) {
  2616. throwError(error, 'Discord.setCache');
  2617. }
  2618. }
  2619. }
  2620. const social_Discord = Discord;
  2621. class Instagram extends social_Social {
  2622. tasks;
  2623. whiteList;
  2624. #cache = GM_getValue('instagramCache') || {};
  2625. #auth = {};
  2626. #initialized = false;
  2627. constructor() {
  2628. super();
  2629. const defaultTasksTemplate = {
  2630. users: []
  2631. };
  2632. this.tasks = defaultTasksTemplate;
  2633. this.whiteList = {
  2634. ...defaultTasksTemplate,
  2635. ...GM_getValue('whiteList')?.instagram || {}
  2636. };
  2637. }
  2638. async init() {
  2639. try {
  2640. if (this.#initialized) {
  2641. return true;
  2642. }
  2643. const isVerified = await this.#getUserInfo();
  2644. if (isVerified) {
  2645. scripts_echoLog({}).success(i18n('initSuccess', 'Instagram'));
  2646. this.#initialized = true;
  2647. return true;
  2648. }
  2649. scripts_echoLog({}).error(i18n('initFailed', 'Instagram'));
  2650. return false;
  2651. } catch (error) {
  2652. throwError(error, 'Instagram.init');
  2653. return false;
  2654. }
  2655. }
  2656. async #getUserInfo(name = 'instagram') {
  2657. try {
  2658. const logStatus = scripts_echoLog({
  2659. type: name === 'instagram' ? 'verifyingInsAuth' : 'gettingInsUserId',
  2660. text: name
  2661. });
  2662. const userId = this.#cache[name];
  2663. if (userId && name !== 'instagram') {
  2664. logStatus.success();
  2665. return userId;
  2666. }
  2667. const {
  2668. result,
  2669. statusText,
  2670. status,
  2671. data
  2672. } = await tools_httpRequest({
  2673. url: `https://www.instagram.com/${name}/`,
  2674. method: 'GET'
  2675. });
  2676. if (result === 'Success') {
  2677. if (data?.finalUrl.includes('accounts/login')) {
  2678. logStatus.error(`Error:${i18n('loginIns')}`, true);
  2679. return false;
  2680. } else if (data?.finalUrl.includes('www.instagram.com/challenge')) {
  2681. logStatus.error(`Error:${i18n('insBanned')}`);
  2682. return false;
  2683. }
  2684. if (data?.status === 200) {
  2685. const csrftoken = data.responseText.match(/"csrf_token":"(.+?)"/)?.[1];
  2686. const hash = data.responseText.match(/"rollout_hash":"(.+?)"/)?.[1];
  2687. if (name === 'instagram') {
  2688. if (csrftoken && hash) {
  2689. this.#auth = {
  2690. csrftoken: csrftoken,
  2691. hash: hash
  2692. };
  2693. return true;
  2694. }
  2695. return false;
  2696. }
  2697. const id = data.responseText.match(/"profilePage_([\d]+?)"/)?.[1];
  2698. if (id) {
  2699. this.#setCache(name, id);
  2700. logStatus.success();
  2701. return id;
  2702. }
  2703. logStatus.error('Error: Get ins data error!');
  2704. return false;
  2705. }
  2706. logStatus.error(`${result}:${statusText}(${status})`);
  2707. return false;
  2708. }
  2709. return false;
  2710. } catch (error) {
  2711. throwError(error, 'Instagram.getUserInfo');
  2712. return false;
  2713. }
  2714. }
  2715. async #followUser(name) {
  2716. try {
  2717. const id = await this.#getUserInfo(name);
  2718. if (!id) {
  2719. return false;
  2720. }
  2721. const logStatus = scripts_echoLog({
  2722. type: 'followingIns',
  2723. text: name
  2724. });
  2725. const {
  2726. result,
  2727. statusText,
  2728. status,
  2729. data
  2730. } = await tools_httpRequest({
  2731. url: `https://www.instagram.com/web/friendships/${id}/follow/`,
  2732. method: 'POST',
  2733. dataType: 'json',
  2734. headers: {
  2735. 'x-csrftoken': this.#auth.csrftoken,
  2736. origin: 'https://www.instagram.com',
  2737. referer: `https://www.instagram.com/${name}/`,
  2738. 'content-type': 'application/x-www-form-urlencoded',
  2739. 'sec-fetch-site': 'same-origin',
  2740. 'x-instagram-ajax': this.#auth.hash
  2741. }
  2742. });
  2743. if (result === 'Success') {
  2744. if (data?.status === 200 && data.response?.result === 'following') {
  2745. logStatus.success();
  2746. this.tasks.users = unique([ ...this.tasks.users, name ]);
  2747. return true;
  2748. }
  2749. logStatus.error(`Error:${data?.response?.feedback_message || `${data?.statusText}(${data?.status})`}`);
  2750. return false;
  2751. }
  2752. logStatus.error(`${result}:${statusText}(${status})`);
  2753. return false;
  2754. } catch (error) {
  2755. throwError(error, 'Instagram.followUser');
  2756. return false;
  2757. }
  2758. }
  2759. async #unfollowUser(name) {
  2760. try {
  2761. if (this.whiteList.users.includes(name)) {
  2762. scripts_echoLog({
  2763. type: 'whiteList',
  2764. text: 'Instagram.unfollowUser',
  2765. id: name
  2766. });
  2767. return true;
  2768. }
  2769. const id = await this.#getUserInfo(name);
  2770. if (!id) {
  2771. return false;
  2772. }
  2773. const logStatus = scripts_echoLog({
  2774. type: 'unfollowingIns',
  2775. text: name
  2776. });
  2777. const {
  2778. result,
  2779. statusText,
  2780. status,
  2781. data
  2782. } = await tools_httpRequest({
  2783. url: `https://www.instagram.com/web/friendships/${id}/unfollow/`,
  2784. method: 'POST',
  2785. dataType: 'json',
  2786. headers: {
  2787. 'x-csrftoken': this.#auth.csrftoken,
  2788. origin: 'https://www.instagram.com',
  2789. referer: `https://www.instagram.com/${name}/`,
  2790. 'content-type': 'application/x-www-form-urlencoded',
  2791. 'sec-fetch-site': 'same-origin',
  2792. 'x-instagram-ajax': this.#auth.hash
  2793. }
  2794. });
  2795. if (result === 'Success') {
  2796. if (data?.status === 200 && data.response?.status === 'ok') {
  2797. logStatus.success();
  2798. return true;
  2799. }
  2800. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2801. return false;
  2802. }
  2803. logStatus.error(`${result}:${statusText}(${status})`);
  2804. return false;
  2805. } catch (error) {
  2806. throwError(error, 'Instagram.unfollowUser');
  2807. return false;
  2808. }
  2809. }
  2810. async toggle({
  2811. doTask = true,
  2812. userLinks = []
  2813. }) {
  2814. try {
  2815. if (!this.#initialized) {
  2816. scripts_echoLog({
  2817. text: i18n('needInit')
  2818. });
  2819. return false;
  2820. }
  2821. const prom = [];
  2822. if (doTask && !globalOptions.doTask.instagram.users || !doTask && !globalOptions.undoTask.instagram.users) {
  2823. scripts_echoLog({
  2824. type: 'globalOptionsSkip',
  2825. text: 'instagram.users'
  2826. });
  2827. } else {
  2828. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1]);
  2829. if (realUsers.length > 0) {
  2830. for (const username of realUsers) {
  2831. if (doTask) {
  2832. prom.push(this.#followUser(username));
  2833. } else {
  2834. prom.push(this.#unfollowUser(username));
  2835. }
  2836. await delay(1e3);
  2837. }
  2838. }
  2839. }
  2840. return await Promise.all(prom).then(() => true);
  2841. } catch (error) {
  2842. throwError(error, 'Instagram.toggleUsers');
  2843. return false;
  2844. }
  2845. }
  2846. #setCache(name, id) {
  2847. try {
  2848. this.#cache[name] = id;
  2849. GM_setValue('instagramCache', this.#cache);
  2850. } catch (error) {
  2851. throwError(error, 'Instagram.setCache');
  2852. }
  2853. }
  2854. }
  2855. const social_Instagram = Instagram;
  2856. class Reddit extends social_Social {
  2857. tasks;
  2858. whiteList;
  2859. #auth;
  2860. #initialized = false;
  2861. constructor() {
  2862. super();
  2863. const defaultTasksTemplate = {
  2864. reddits: []
  2865. };
  2866. this.tasks = defaultTasksTemplate;
  2867. this.whiteList = {
  2868. ...defaultTasksTemplate,
  2869. ...GM_getValue('whiteList')?.reddit || {}
  2870. };
  2871. }
  2872. async init() {
  2873. try {
  2874. if (this.#initialized) {
  2875. return true;
  2876. }
  2877. const isVerified = await this.#updateAuth();
  2878. if (isVerified) {
  2879. scripts_echoLog({}).success(i18n('initSuccess', 'Reddit'));
  2880. this.#initialized = true;
  2881. return true;
  2882. }
  2883. scripts_echoLog({}).error(i18n('initFailed', 'Reddit'));
  2884. return false;
  2885. } catch (error) {
  2886. throwError(error, 'Reddit.init');
  2887. return false;
  2888. }
  2889. }
  2890. async #useBeta() {
  2891. try {
  2892. const logStatus = scripts_echoLog({
  2893. text: i18n('changingRedditVersion')
  2894. });
  2895. return await new Promise(resolve => {
  2896. const newTab = GM_openInTab('https://www.reddit.com/', {
  2897. active: true,
  2898. insert: true,
  2899. setParent: true
  2900. });
  2901. newTab.name = 'ATv4_redditAuth';
  2902. newTab.onclose = async () => {
  2903. logStatus.success();
  2904. resolve(await this.#updateAuth(true));
  2905. };
  2906. });
  2907. } catch (error) {
  2908. throwError(error, 'Reddit.useBeta');
  2909. return false;
  2910. }
  2911. }
  2912. async #updateAuth(beta = false) {
  2913. try {
  2914. const logStatus = scripts_echoLog({
  2915. text: i18n('updatingAuth', 'Reddit')
  2916. });
  2917. const {
  2918. result,
  2919. statusText,
  2920. status,
  2921. data
  2922. } = await tools_httpRequest({
  2923. url: 'https://www.reddit.com/',
  2924. method: 'GET',
  2925. nochche: true,
  2926. headers: {
  2927. 'Cache-Control': 'no-cache'
  2928. }
  2929. });
  2930. if (result === 'Success') {
  2931. if (data?.responseText.includes('www.reddit.com/login/')) {
  2932. logStatus.error(`Error:${i18n('loginReddit')}`, true);
  2933. return false;
  2934. }
  2935. if (data?.status === 200) {
  2936. if (data.responseText.includes('redesign-beta-optin-btn') && !beta) {
  2937. return await this.#useBeta();
  2938. }
  2939. const accessToken = data.responseText.match(/"accessToken":"(.*?)","expires":"(.*?)"/)?.[1];
  2940. if (accessToken) {
  2941. this.#auth = {
  2942. token: accessToken
  2943. };
  2944. logStatus.success();
  2945. return true;
  2946. }
  2947. logStatus.error('Error: Parameter "accessToken" not found!');
  2948. return false;
  2949. }
  2950. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2951. return false;
  2952. }
  2953. logStatus.error(`${result}:${statusText}(${status})`);
  2954. return false;
  2955. } catch (error) {
  2956. throwError(error, 'Reddit.updateAuth');
  2957. return false;
  2958. }
  2959. }
  2960. async #toggleTask({
  2961. name,
  2962. doTask = true
  2963. }) {
  2964. try {
  2965. if (!doTask && this.whiteList.reddits.includes(name)) {
  2966. scripts_echoLog({
  2967. type: 'whiteList',
  2968. text: 'Reddit.undoTask',
  2969. id: name
  2970. });
  2971. return true;
  2972. }
  2973. let type = doTask ? 'joiningReddit' : 'leavingReddit';
  2974. if (/^u_/.test(name)) {
  2975. type = doTask ? 'followingRedditUser' : 'unfollowingRedditUser';
  2976. }
  2977. const logStatus = scripts_echoLog({
  2978. type: type,
  2979. text: name
  2980. });
  2981. const {
  2982. result,
  2983. statusText,
  2984. status,
  2985. data
  2986. } = await tools_httpRequest({
  2987. url: 'https://oauth.reddit.com/api/subscribe?redditWebClient=desktop2x&app=desktop2x-client-production&raw_json=1&gilding_detail=1',
  2988. method: 'POST',
  2989. headers: {
  2990. authorization: `Bearer ${this.#auth.token}`,
  2991. 'content-type': 'application/x-www-form-urlencoded'
  2992. },
  2993. data: $.param({
  2994. action: doTask ? 'sub' : 'unsub',
  2995. sr_name: name,
  2996. api_type: 'json'
  2997. })
  2998. });
  2999. if (result === 'Success') {
  3000. if (data?.status === 200) {
  3001. logStatus.success();
  3002. if (doTask) {
  3003. this.tasks.reddits = unique([ ...this.tasks.reddits, name ]);
  3004. }
  3005. return true;
  3006. }
  3007. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3008. return false;
  3009. }
  3010. logStatus.error(`${result}:${statusText}(${status})`);
  3011. return false;
  3012. } catch (error) {
  3013. throwError(error, 'Reddit.toggleTask');
  3014. return false;
  3015. }
  3016. }
  3017. async toggle({
  3018. doTask = true,
  3019. redditLinks = []
  3020. }) {
  3021. try {
  3022. if (!this.#initialized) {
  3023. scripts_echoLog({
  3024. text: i18n('needInit')
  3025. });
  3026. return false;
  3027. }
  3028. const prom = [];
  3029. if (doTask && !globalOptions.doTask.reddit.reddits || !doTask && !globalOptions.undoTask.reddit.reddits) {
  3030. scripts_echoLog({
  3031. type: 'globalOptionsSkip',
  3032. text: 'reddit.reddits'
  3033. });
  3034. } else {
  3035. const realReddits = this.getRealParams('reddits', redditLinks, doTask, link => {
  3036. const name = link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1];
  3037. const userName = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1];
  3038. if (userName) {
  3039. return name || userName;
  3040. }
  3041. return name;
  3042. });
  3043. if (realReddits.length > 0) {
  3044. for (const name of realReddits) {
  3045. prom.push(this.#toggleTask({
  3046. name: name,
  3047. doTask: doTask
  3048. }));
  3049. await delay(1e3);
  3050. }
  3051. }
  3052. }
  3053. return await Promise.all(prom).then(() => true);
  3054. } catch (error) {
  3055. throwError(error, 'Reddit.toggle');
  3056. return false;
  3057. }
  3058. }
  3059. }
  3060. const social_Reddit = Reddit;
  3061. class Twitch extends social_Social {
  3062. tasks;
  3063. whiteList;
  3064. #auth = GM_getValue('twitchAuth') || {};
  3065. #cache = GM_getValue('twitchCache') || {};
  3066. #initialized = false;
  3067. #integrityToken;
  3068. constructor() {
  3069. super();
  3070. const defaultTasksTemplate = {
  3071. channels: []
  3072. };
  3073. this.tasks = defaultTasksTemplate;
  3074. this.whiteList = {
  3075. ...defaultTasksTemplate,
  3076. ...GM_getValue('whiteList')?.twitch || {}
  3077. };
  3078. }
  3079. async init() {
  3080. try {
  3081. if (this.#initialized) {
  3082. return true;
  3083. }
  3084. if (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId) {
  3085. if (await this.#updateAuth()) {
  3086. this.#initialized = true;
  3087. return true;
  3088. }
  3089. return false;
  3090. }
  3091. const isVerified = await this.#verifyAuth(true);
  3092. if (isVerified) {
  3093. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  3094. this.#initialized = true;
  3095. return true;
  3096. }
  3097. GM_setValue('twitchAuth', null);
  3098. if (await this.#updateAuth()) {
  3099. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  3100. this.#initialized = true;
  3101. return true;
  3102. }
  3103. scripts_echoLog({}).error(i18n('initFailed', 'Twitch'));
  3104. return false;
  3105. } catch (error) {
  3106. throwError(error, 'Twitch.init');
  3107. return false;
  3108. }
  3109. }
  3110. async #verifyAuth(isFirst) {
  3111. try {
  3112. const logStatus = scripts_echoLog({
  3113. text: i18n('verifyingAuth', 'Twitch')
  3114. });
  3115. const {
  3116. result,
  3117. statusText,
  3118. status,
  3119. data
  3120. } = await tools_httpRequest({
  3121. url: 'https://gql.twitch.tv/gql',
  3122. method: 'POST',
  3123. dataType: 'json',
  3124. headers: {
  3125. Authorization: `OAuth ${this.#auth.authToken}`,
  3126. 'Client-Id': this.#auth.clientId
  3127. },
  3128. data: '[{"operationName":"FrontPageNew_User","variables":{"limit":1},"extensions":{"persistedQuery":{"version":1,' + '"sha256Hash":"64bd07a2cbaca80699d62636d966cf6395a5d14a1f0a14282067dcb28b13eb11"}}}]'
  3129. });
  3130. if (result === 'Success') {
  3131. if (data?.status === 200 && data.response?.[0]?.data?.currentUser) {
  3132. await this.#integrity(isFirst);
  3133. logStatus.success();
  3134. return true;
  3135. }
  3136. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3137. return false;
  3138. }
  3139. logStatus.error(`${result}:${statusText}(${status})`);
  3140. return false;
  3141. } catch (error) {
  3142. throwError(error, 'Twitch.verifyAuth');
  3143. return false;
  3144. }
  3145. }
  3146. async #integrity(isFirst = true, ct = '') {
  3147. try {
  3148. const logStatus = scripts_echoLog({
  3149. text: i18n('checkingTwitchIntegrity')
  3150. });
  3151. if (isFirst && (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId)) {
  3152. return await this.#updateAuth(false);
  3153. }
  3154. const {
  3155. result,
  3156. statusText,
  3157. status,
  3158. data
  3159. } = await tools_httpRequest({
  3160. url: 'https://gql.twitch.tv/integrity',
  3161. method: 'POST',
  3162. dataType: 'json',
  3163. anonymous: true,
  3164. headers: {
  3165. Origin: 'https://www.twitch.tv',
  3166. Referer: 'https://www.twitch.tv/',
  3167. Authorization: `OAuth ${this.#auth.authToken}`,
  3168. 'Client-Id': this.#auth.clientId,
  3169. 'Client-Version': this.#auth.clientVersion,
  3170. 'X-Device-Id': this.#auth.deviceId,
  3171. 'Client-Session-Id': this.#auth.clientSessionId,
  3172. 'x-kpsdk-ct': ct
  3173. }
  3174. });
  3175. if (result === 'Success') {
  3176. if (!ct && data?.responseHeaders?.['x-kpsdk-ct']) {
  3177. return await this.#integrity(isFirst, data.responseHeaders['x-kpsdk-ct']);
  3178. }
  3179. if (data?.status === 200 && data.response?.token) {
  3180. this.#integrityToken = data.response.token;
  3181. logStatus.success();
  3182. return true;
  3183. }
  3184. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3185. return false;
  3186. }
  3187. logStatus.error(`${result}:${statusText}(${status})`);
  3188. return false;
  3189. } catch (error) {
  3190. throwError(error, 'Twitch.integrity');
  3191. return false;
  3192. }
  3193. }
  3194. async #updateAuth(isFirst = true) {
  3195. try {
  3196. const logStatus = scripts_echoLog({
  3197. text: i18n('updatingAuth', 'Twitch')
  3198. });
  3199. return await new Promise(resolve => {
  3200. const newTab = GM_openInTab('https://www.twitch.tv/', {
  3201. active: true,
  3202. insert: true,
  3203. setParent: true
  3204. });
  3205. newTab.name = 'ATv4_twitchAuth';
  3206. newTab.onclose = async () => {
  3207. const auth = GM_getValue('twitchAuth');
  3208. if (auth) {
  3209. this.#auth = auth;
  3210. logStatus.success();
  3211. resolve(await this.#verifyAuth(isFirst));
  3212. } else {
  3213. logStatus.error('Error: Update twitch auth failed!');
  3214. resolve(false);
  3215. }
  3216. };
  3217. });
  3218. } catch (error) {
  3219. throwError(error, 'Twitch.updateAuth');
  3220. return false;
  3221. }
  3222. }
  3223. async #toggleChannel({
  3224. name,
  3225. doTask = true
  3226. }) {
  3227. try {
  3228. if (!doTask && this.whiteList.channels.includes(name)) {
  3229. scripts_echoLog({
  3230. type: 'whiteList',
  3231. text: 'Twitch.unfollowChannel',
  3232. id: name
  3233. });
  3234. return true;
  3235. }
  3236. const channelId = await this.#getChannelId(name);
  3237. if (!channelId) {
  3238. return false;
  3239. }
  3240. const logStatus = scripts_echoLog({
  3241. type: `${doTask ? '' : 'un'}followingTwitchChannel`,
  3242. text: name
  3243. });
  3244. const followData = `[{"operationName":"FollowButton_FollowUser","variables":{"input":{"disableNotifications":false,"targetID":"${channelId}` + '"}},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"800e7346bdf7e5278a3c1d3f21b2b56e2639928f86815677a7126b093b2fdd08"}}}]';
  3245. const unfollowData = `[{"operationName":"FollowButton_UnfollowUser","variables":{"input":{"targetID":"${channelId}"}},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"f7dae976ebf41c755ae2d758546bfd176b4eeb856656098bb40e0a672ca0d880"}}}]';
  3246. const {
  3247. result,
  3248. statusText,
  3249. status,
  3250. data
  3251. } = await tools_httpRequest({
  3252. url: 'https://gql.twitch.tv/gql',
  3253. method: 'POST',
  3254. dataType: 'json',
  3255. anonymous: true,
  3256. headers: {
  3257. Origin: 'https://www.twitch.tv',
  3258. Referer: 'https://www.twitch.tv/',
  3259. Authorization: `OAuth ${this.#auth.authToken}`,
  3260. 'Client-Id': this.#auth.clientId,
  3261. 'Client-Version': this.#auth.clientVersion,
  3262. 'X-Device-Id': this.#auth.deviceId,
  3263. 'Client-Session-Id': this.#auth.clientSessionId,
  3264. 'Client-Integrity': this.#integrityToken
  3265. },
  3266. data: doTask ? followData : unfollowData
  3267. });
  3268. if (result === 'Success') {
  3269. if (data?.status === 200 && data.response?.[0] && !data.response[0].errors) {
  3270. logStatus.success();
  3271. if (doTask) {
  3272. this.tasks.channels = unique([ ...this.tasks.channels, name ]);
  3273. }
  3274. return true;
  3275. }
  3276. logStatus.error(`Error:${data?.response?.[0].errors?.[0]?.message || `${data?.statusText}(${data?.status})`}`);
  3277. return false;
  3278. }
  3279. logStatus.error(`${result}:${statusText}(${status})`);
  3280. return false;
  3281. } catch (error) {
  3282. throwError(error, 'Twitch.toggleChannel');
  3283. return false;
  3284. }
  3285. }
  3286. async #getChannelId(name) {
  3287. try {
  3288. const logStatus = scripts_echoLog({
  3289. type: 'gettingTwitchChannelId',
  3290. text: name
  3291. });
  3292. const channelId = this.#cache[name];
  3293. if (channelId) {
  3294. logStatus.success();
  3295. return channelId;
  3296. }
  3297. const {
  3298. result,
  3299. statusText,
  3300. status,
  3301. data
  3302. } = await tools_httpRequest({
  3303. url: 'https://gql.twitch.tv/gql',
  3304. method: 'POST',
  3305. headers: {
  3306. Authorization: `OAuth ${this.#auth.authToken}`,
  3307. 'Client-Id': this.#auth.clientId
  3308. },
  3309. responseType: 'json',
  3310. data: `[{"operationName":"ActiveWatchParty","variables":{"channelLogin":"${name}"},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"4a8156c97b19e3a36e081cf6d6ddb5dbf9f9b02ae60e4d2ff26ed70aebc80a30"}}}]'
  3311. });
  3312. if (result === 'Success') {
  3313. if (data?.status === 200) {
  3314. const channelId = data.response?.[0]?.data?.user?.id;
  3315. if (channelId) {
  3316. this.#setCache(name, String(channelId));
  3317. logStatus.success();
  3318. return channelId;
  3319. }
  3320. logStatus.error(`Error:${data.statusText}(${data.status})`);
  3321. return false;
  3322. }
  3323. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3324. return false;
  3325. }
  3326. logStatus.error(`${result}:${statusText}(${status})`);
  3327. return false;
  3328. } catch (error) {
  3329. throwError(error, 'Twitch.getChannelId');
  3330. return false;
  3331. }
  3332. }
  3333. async toggle({
  3334. doTask = true,
  3335. channelLinks = []
  3336. }) {
  3337. try {
  3338. if (!this.#initialized) {
  3339. scripts_echoLog({
  3340. text: i18n('needInit')
  3341. });
  3342. return false;
  3343. }
  3344. const prom = [];
  3345. if (doTask && !globalOptions.doTask.twitch.channels || !doTask && !globalOptions.undoTask.twitch.channels) {
  3346. scripts_echoLog({
  3347. type: 'globalOptionsSkip',
  3348. text: 'twitch.channels'
  3349. });
  3350. } else {
  3351. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2]);
  3352. if (realChannels.length > 0) {
  3353. for (const channel of realChannels) {
  3354. prom.push(this.#toggleChannel({
  3355. name: channel,
  3356. doTask: doTask
  3357. }));
  3358. await delay(1e3);
  3359. }
  3360. }
  3361. }
  3362. return Promise.all(prom).then(() => true);
  3363. } catch (error) {
  3364. throwError(error, 'Twitch.toggle');
  3365. return false;
  3366. }
  3367. }
  3368. #setCache(name, id) {
  3369. try {
  3370. this.#cache[name] = id;
  3371. GM_setValue('twitchCache', this.#cache);
  3372. } catch (error) {
  3373. throwError(error, 'Twitch.setCache');
  3374. }
  3375. }
  3376. }
  3377. const social_Twitch = Twitch;
  3378. var main = __webpack_require__(356);
  3379. class Twitter extends social_Social {
  3380. tasks;
  3381. whiteList;
  3382. #verifyId = globalOptions.other.twitterVerifyId;
  3383. #auth = GM_getValue('twitterAuth') || {};
  3384. #cache = GM_getValue('twitterCache') || {};
  3385. #initialized = false;
  3386. #session;
  3387. constructor() {
  3388. super();
  3389. const defaultTasksTemplate = {
  3390. users: [],
  3391. retweets: [],
  3392. likes: []
  3393. };
  3394. this.tasks = defaultTasksTemplate;
  3395. this.whiteList = {
  3396. ...defaultTasksTemplate,
  3397. ...GM_getValue('whiteList')?.twitter || {}
  3398. };
  3399. }
  3400. async init() {
  3401. try {
  3402. if (this.#initialized) {
  3403. return true;
  3404. }
  3405. if (!this.#auth.ct0) {
  3406. if (await this.#updateAuth()) {
  3407. this.#initialized = true;
  3408. return true;
  3409. }
  3410. return false;
  3411. }
  3412. this.#session = await (0, main.createSession)();
  3413. const isVerified = await this.#verifyAuth();
  3414. if (isVerified) {
  3415. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  3416. this.#initialized = true;
  3417. return true;
  3418. }
  3419. GM_setValue('twitterAuth', null);
  3420. if (await this.#updateAuth()) {
  3421. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  3422. this.#initialized = true;
  3423. return true;
  3424. }
  3425. scripts_echoLog({}).error(i18n('initFailed', 'Twitter'));
  3426. return false;
  3427. } catch (error) {
  3428. throwError(error, 'Twitter.init');
  3429. return false;
  3430. }
  3431. }
  3432. async #verifyAuth() {
  3433. try {
  3434. return await this.#toggleUser({
  3435. name: 'verify',
  3436. doTask: true,
  3437. verify: true
  3438. });
  3439. } catch (error) {
  3440. throwError(error, 'Twitter.verifyAuth');
  3441. return false;
  3442. }
  3443. }
  3444. async #updateAuth() {
  3445. try {
  3446. const logStatus = scripts_echoLog({
  3447. text: i18n('updatingAuth', 'Twitter')
  3448. });
  3449. return await new Promise(resolve => {
  3450. GM_cookie.list({
  3451. url: 'https://x.com/settings/account'
  3452. }, async (cookies, error) => {
  3453. if (!error) {
  3454. const [ ct0, isLogin ] = cookies.map(cookie => [ 'ct0', 'twid' ].includes(cookie.name) ? cookie.value : null).filter(cookie => cookie);
  3455. if (isLogin && ct0) {
  3456. GM_setValue('twitterAuth', {
  3457. ct0: ct0
  3458. });
  3459. this.#auth = {
  3460. ct0: ct0
  3461. };
  3462. logStatus.success();
  3463. resolve(await this.#verifyAuth());
  3464. } else {
  3465. logStatus.error(i18n('needLogin'));
  3466. resolve(false);
  3467. }
  3468. } else {
  3469. logStatus.error('Error: Update twitter auth failed!');
  3470. resolve(false);
  3471. }
  3472. });
  3473. });
  3474. } catch (error) {
  3475. throwError(error, 'Twitter.updateToken');
  3476. return false;
  3477. }
  3478. }
  3479. async #toggleUser({
  3480. name,
  3481. doTask = true,
  3482. verify = false,
  3483. retry = false
  3484. }) {
  3485. try {
  3486. if (!doTask && !verify && this.whiteList.users.includes(name)) {
  3487. scripts_echoLog({
  3488. type: 'whiteList',
  3489. text: 'Twitter.unfollowUser',
  3490. id: name
  3491. });
  3492. return true;
  3493. }
  3494. const userId = verify ? this.#verifyId : await this.userName2id(name);
  3495. if (!userId) {
  3496. return false;
  3497. }
  3498. const logStatus = verify ? scripts_echoLog({
  3499. text: i18n('verifyingAuth', 'Twitter')
  3500. }) : scripts_echoLog({
  3501. type: `${doTask ? '' : 'un'}followingTwitterUser`,
  3502. text: name
  3503. });
  3504. const {
  3505. result,
  3506. statusText,
  3507. status,
  3508. data
  3509. } = await tools_httpRequest({
  3510. url: `https://x.com/i/api/1.1/friendships/${doTask ? 'create' : 'destroy'}.json`,
  3511. method: 'POST',
  3512. headers: {
  3513. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3514. 'Content-Type': 'application/x-www-form-urlencoded',
  3515. 'x-csrf-token': this.#auth.ct0,
  3516. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3517. 'X-Twitter-Active-User': 'yes',
  3518. 'x-client-transaction-id': await this.#session.get('POST', `/i/api/1.1/friendships/${doTask ? 'create' : 'destroy'}.json`)
  3519. },
  3520. responseType: 'json',
  3521. data: $.param({
  3522. include_profile_interstitial_type: 1,
  3523. include_blocking: 1,
  3524. include_blocked_by: 1,
  3525. include_followed_by: 1,
  3526. include_want_retweets: 1,
  3527. include_mute_edge: 1,
  3528. include_can_dm: 1,
  3529. include_can_media_tag: 1,
  3530. skip_status: 1,
  3531. id: userId
  3532. })
  3533. });
  3534. if (result === 'Success') {
  3535. if (data?.status === 200) {
  3536. logStatus.success();
  3537. if (doTask && !verify) {
  3538. this.tasks.users = unique([ ...this.tasks.users, name ]);
  3539. }
  3540. return true;
  3541. }
  3542. if (verify && data?.status === 403) {
  3543. if (data.response?.errors?.[0]?.code === 158) {
  3544. logStatus.success();
  3545. return true;
  3546. }
  3547. if (data.response?.errors?.[0]?.code === 353 && !retry && data.responseHeaders?.['set-cookie']) {
  3548. this.#auth.ct0 = data.responseHeaders['set-cookie']?.find(cookie => cookie.includes('ct0='))?.split(';')?.at(0)?.split('=')?.at(-1) || this.#auth.ct0;
  3549. logStatus.warning(i18n('retry'));
  3550. return this.#toggleUser({
  3551. name: name,
  3552. doTask: doTask,
  3553. verify: verify,
  3554. retry: true
  3555. });
  3556. }
  3557. }
  3558. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3559. return false;
  3560. }
  3561. logStatus.error(`${result}:${statusText}(${status})`);
  3562. return false;
  3563. } catch (error) {
  3564. throwError(error, 'Twitter.toggleUser');
  3565. return false;
  3566. }
  3567. }
  3568. async userName2id(name) {
  3569. try {
  3570. const logStatus = scripts_echoLog({
  3571. type: 'gettingTwitterUserId',
  3572. text: name
  3573. });
  3574. const userId = this.#cache[name];
  3575. if (userId) {
  3576. logStatus.success();
  3577. return userId;
  3578. }
  3579. const {
  3580. result,
  3581. statusText,
  3582. status,
  3583. data
  3584. } = await tools_httpRequest({
  3585. 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`,
  3586. method: 'GET',
  3587. headers: {
  3588. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3589. 'content-type': 'application/json',
  3590. referer: `https://x.com/${name}`,
  3591. 'x-csrf-token': this.#auth.ct0,
  3592. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3593. 'X-Twitter-Active-User': 'yes',
  3594. 'x-client-transaction-id': await this.#session.get('GET', '/i/api/graphql/mCbpQvZAw6zu_4PvuAUVVQ/UserByScreenName' + `?variables=%7B%22screen_name%22%3A%22${name}%22%2C%22withSafetyModeUserFields%22%3Atrue%2C%22withSuperFollowsUserFields%22%3Atrue%7D`)
  3595. },
  3596. responseType: 'json'
  3597. });
  3598. if (result === 'Success') {
  3599. if (data?.status === 200) {
  3600. let response = data.response || (typeof data.responseText === 'object' ? data.responseText : null);
  3601. if (!response) {
  3602. try {
  3603. response = JSON.parse(data.responseText);
  3604. } catch (error) {
  3605. response = null;
  3606. }
  3607. }
  3608. const userId = String(response?.data?.user?.result?.rest_id);
  3609. if (userId) {
  3610. this.#setCache(name, userId);
  3611. logStatus.success();
  3612. return userId;
  3613. }
  3614. logStatus.error(`Error:${data.statusText}(${data.status})`);
  3615. return false;
  3616. }
  3617. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3618. return false;
  3619. }
  3620. logStatus.error(`${result}:${statusText}(${status})`);
  3621. return false;
  3622. } catch (error) {
  3623. throwError(error, 'Twitter.getUserId');
  3624. return false;
  3625. }
  3626. }
  3627. async #toggleRetweet({
  3628. retweetId,
  3629. doTask = true
  3630. }) {
  3631. try {
  3632. if (!doTask && this.whiteList.retweets.includes(retweetId)) {
  3633. scripts_echoLog({
  3634. type: 'whiteList',
  3635. text: 'Twitter.unretweet',
  3636. id: retweetId
  3637. });
  3638. return true;
  3639. }
  3640. const logStatus = scripts_echoLog({
  3641. type: `${doTask ? '' : 'un'}retweetting`,
  3642. text: retweetId
  3643. });
  3644. const {
  3645. result,
  3646. statusText,
  3647. status,
  3648. data
  3649. } = await tools_httpRequest({
  3650. url: `https://x.com/i/api/graphql/${doTask ? 'ojPdsZsimiJrUGLR1sjUtA/CreateRetweet' : 'iQtK4dl5hBmXewYZuEOKVw/DeleteRetweet'}`,
  3651. method: 'POST',
  3652. headers: {
  3653. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3654. 'Content-Type': 'application/json',
  3655. origin: 'https://x.com',
  3656. referer: 'https://x.com/home',
  3657. 'x-csrf-token': this.#auth.ct0,
  3658. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3659. 'X-Twitter-Active-User': 'yes',
  3660. 'x-client-transaction-id': await this.#session.get('POST', `/i/api/graphql/${doTask ? 'ojPdsZsimiJrUGLR1sjUtA/CreateRetweet' : 'iQtK4dl5hBmXewYZuEOKVw/DeleteRetweet'}`)
  3661. },
  3662. data: `{"variables":{"${doTask ? '' : 'source_'}tweet_id":"${retweetId}","dark_request":false},"queryId":"${doTask ? 'ojPdsZsimiJrUGLR1sjUtA' : 'iQtK4dl5hBmXewYZuEOKVw'}"}`,
  3663. responseType: 'json'
  3664. });
  3665. if (result === 'Success') {
  3666. if (data?.status === 200 || data?.status === 403 && data.response?.errors?.[0]?.code === 327) {
  3667. if (data.response?.errors) {
  3668. logStatus.error(`Error:${data.response?.errors?.[0]?.message}`);
  3669. return false;
  3670. }
  3671. logStatus.success();
  3672. if (doTask) {
  3673. this.tasks.retweets = unique([ ...this.tasks.retweets, retweetId ]);
  3674. }
  3675. return true;
  3676. }
  3677. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3678. return false;
  3679. }
  3680. logStatus.error(`${result}:${statusText}(${status})`);
  3681. return false;
  3682. } catch (error) {
  3683. throwError(error, 'Twitter.toggleRetweet');
  3684. return false;
  3685. }
  3686. }
  3687. async toggle({
  3688. doTask = true,
  3689. userLinks = [],
  3690. retweetLinks = []
  3691. }) {
  3692. try {
  3693. if (!this.#initialized) {
  3694. scripts_echoLog({
  3695. text: i18n('needInit')
  3696. });
  3697. return false;
  3698. }
  3699. const prom = [];
  3700. if (doTask && !globalOptions.doTask.twitter.users || !doTask && !globalOptions.undoTask.twitter.users) {
  3701. scripts_echoLog({
  3702. type: 'globalOptionsSkip',
  3703. text: 'twitter.users'
  3704. });
  3705. } else {
  3706. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/x\.com\/(.+)/)?.[1] || link.match(/https:\/\/twitter\.com\/(.+)/)?.[1]);
  3707. if (realUsers.length > 0) {
  3708. for (const user of realUsers) {
  3709. prom.push(this.#toggleUser({
  3710. name: user,
  3711. doTask: doTask
  3712. }));
  3713. await delay(1e3);
  3714. }
  3715. }
  3716. }
  3717. if (doTask && !globalOptions.doTask.twitter.retweets || !doTask && !globalOptions.undoTask.twitter.retweets) {
  3718. scripts_echoLog({
  3719. type: 'globalOptionsSkip',
  3720. text: 'twitter.retweets'
  3721. });
  3722. } else {
  3723. const realRetweets = this.getRealParams('retweets', retweetLinks, doTask, link => link.match(/https:\/\/x\.com\/.*?\/status\/([\d]+)/)?.[1] || link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1]);
  3724. if (realRetweets.length > 0) {
  3725. for (const retweet of realRetweets) {
  3726. prom.push(this.#toggleRetweet({
  3727. retweetId: retweet,
  3728. doTask: doTask
  3729. }));
  3730. await delay(1e3);
  3731. }
  3732. }
  3733. }
  3734. return Promise.all(prom).then(() => true);
  3735. } catch (error) {
  3736. throwError(error, 'Twitter.toggle');
  3737. return false;
  3738. }
  3739. }
  3740. #setCache(name, id) {
  3741. try {
  3742. this.#cache[name] = id;
  3743. GM_setValue('twitterCache', this.#cache);
  3744. } catch (error) {
  3745. throwError(error, 'Twitter.setCache');
  3746. }
  3747. }
  3748. }
  3749. const social_Twitter = Twitter;
  3750. class Vk extends social_Social {
  3751. tasks;
  3752. whiteList;
  3753. #username = '';
  3754. #cache = GM_getValue('vkCache') || {};
  3755. #initialized = false;
  3756. constructor() {
  3757. super();
  3758. const defaultTasksTemplate = {
  3759. names: []
  3760. };
  3761. this.tasks = defaultTasksTemplate;
  3762. this.whiteList = {
  3763. ...defaultTasksTemplate,
  3764. ...GM_getValue('whiteList')?.vk || {}
  3765. };
  3766. }
  3767. async init() {
  3768. try {
  3769. if (this.#initialized) {
  3770. return true;
  3771. }
  3772. const isVerified = await this.#verifyAuth();
  3773. if (isVerified) {
  3774. scripts_echoLog({}).success(i18n('initSuccess', 'Vk'));
  3775. this.#initialized = true;
  3776. return true;
  3777. }
  3778. scripts_echoLog({}).error(i18n('initFailed', 'Vk'));
  3779. return false;
  3780. } catch (error) {
  3781. throwError(error, 'Vk.init');
  3782. return false;
  3783. }
  3784. }
  3785. async #verifyAuth() {
  3786. try {
  3787. const logStatus = scripts_echoLog({
  3788. text: i18n('verifyAuth', 'Vk')
  3789. });
  3790. const {
  3791. result,
  3792. statusText,
  3793. status,
  3794. data
  3795. } = await tools_httpRequest({
  3796. url: 'https://vk.com/im',
  3797. method: 'GET'
  3798. });
  3799. if (result === 'Success') {
  3800. if (data?.finalUrl.includes('vk.com/login')) {
  3801. logStatus.error(`Error:${i18n('loginVk')}`, true);
  3802. return false;
  3803. }
  3804. if (data?.status === 200) {
  3805. this.#username = data.responseText.match(/TopNavBtn__profileLink" href="\/(.*?)"/)?.[1] || '';
  3806. logStatus.success();
  3807. return true;
  3808. }
  3809. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3810. return false;
  3811. }
  3812. logStatus.error(`${result}:${statusText}(${status})`);
  3813. return false;
  3814. } catch (error) {
  3815. throwError(error, 'Vk.verifyAuth');
  3816. return false;
  3817. }
  3818. }
  3819. async #toggleGroup(name, dataParam, doTask = true) {
  3820. try {
  3821. const logStatus = scripts_echoLog({
  3822. type: doTask ? 'joiningVkGroup' : 'leavingVkGroup',
  3823. text: name
  3824. });
  3825. if (dataParam.groupAct === 'enter' && !doTask || dataParam.groupAct === 'leave' && doTask) {
  3826. logStatus.success();
  3827. return true;
  3828. }
  3829. const reqData = {
  3830. act: doTask ? 'enter' : 'leave',
  3831. al: 1,
  3832. gid: dataParam.groupId,
  3833. hash: dataParam.groupHash
  3834. };
  3835. if (doTask) {
  3836. reqData.context = '_';
  3837. }
  3838. const {
  3839. result,
  3840. statusText,
  3841. status,
  3842. data
  3843. } = await tools_httpRequest({
  3844. url: 'https://vk.com/al_groups.php',
  3845. method: 'POST',
  3846. headers: {
  3847. origin: 'https://vk.com',
  3848. referer: `https://vk.com/${name}`,
  3849. 'content-type': 'application/x-www-form-urlencoded'
  3850. },
  3851. data: $.param(reqData)
  3852. });
  3853. if (result === 'Success') {
  3854. if (data?.status === 200) {
  3855. logStatus.success();
  3856. if (doTask) {
  3857. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3858. }
  3859. return true;
  3860. }
  3861. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3862. return false;
  3863. }
  3864. logStatus.error(`${result}:${statusText}(${status})`);
  3865. return false;
  3866. } catch (error) {
  3867. throwError(error, 'Vk.toggleGroup');
  3868. return false;
  3869. }
  3870. }
  3871. async #togglePublic(name, dataParam, doTask = true) {
  3872. try {
  3873. const logStatus = scripts_echoLog({
  3874. type: doTask ? 'joiningVkPublic' : 'leavingVkPublic',
  3875. text: name
  3876. });
  3877. if (dataParam.publicJoined && doTask || !dataParam.publicJoined && !doTask) {
  3878. logStatus.success();
  3879. return true;
  3880. }
  3881. const {
  3882. result,
  3883. statusText,
  3884. status,
  3885. data
  3886. } = await tools_httpRequest({
  3887. url: 'https://vk.com/al_public.php',
  3888. method: 'POST',
  3889. headers: {
  3890. origin: 'https://vk.com',
  3891. referer: `https://vk.com/${name}`,
  3892. 'content-type': 'application/x-www-form-urlencoded'
  3893. },
  3894. data: $.param({
  3895. act: doTask ? 'a_enter' : 'a_leave',
  3896. al: 1,
  3897. pid: dataParam.publicPid,
  3898. hash: dataParam.publicHash
  3899. })
  3900. });
  3901. if (result === 'Success') {
  3902. if (data?.status === 200) {
  3903. logStatus.success();
  3904. if (doTask) {
  3905. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3906. }
  3907. return true;
  3908. }
  3909. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3910. return false;
  3911. }
  3912. logStatus.error(`${result}:${statusText}(${status})`);
  3913. return false;
  3914. } catch (error) {
  3915. throwError(error, 'Vk.togglePublic');
  3916. return false;
  3917. }
  3918. }
  3919. async #toggleLikeWall(name, dataParam, doTask = true) {
  3920. try {
  3921. const logStatus = scripts_echoLog({
  3922. type: doTask ? 'likingVkPublic' : 'unlikingVkPublic',
  3923. text: name
  3924. });
  3925. const postData = {
  3926. act: 'a_set_reaction',
  3927. al: 1,
  3928. event_subtype: 'post_modal',
  3929. from: 'wall_page',
  3930. hash: dataParam.hash,
  3931. object: dataParam.object,
  3932. track_code: dataParam.trackCode,
  3933. wall: 2
  3934. };
  3935. if (doTask) {
  3936. postData.reaction_id = 0;
  3937. }
  3938. const {
  3939. result: resultR,
  3940. statusText: statusTextR,
  3941. status: statusR,
  3942. data: dataR
  3943. } = await tools_httpRequest({
  3944. url: 'https://vk.com/like.php?act=a_set_reaction',
  3945. method: 'POST',
  3946. headers: {
  3947. origin: 'https://vk.com',
  3948. referer: `https://vk.com/${name}`,
  3949. 'content-type': 'application/x-www-form-urlencoded'
  3950. },
  3951. data: $.param(postData)
  3952. });
  3953. if (resultR === 'Success') {
  3954. if (dataR?.status === 200) {
  3955. if (dataR.response?.payload?.[1]?.[1]?.like_my === true) {
  3956. logStatus.success();
  3957. return true;
  3958. }
  3959. }
  3960. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  3961. return false;
  3962. }
  3963. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  3964. return false;
  3965. } catch (error) {
  3966. throwError(error, 'Vk.sendWall');
  3967. return false;
  3968. }
  3969. }
  3970. async #sendWall(name) {
  3971. try {
  3972. const logStatus = scripts_echoLog({
  3973. type: 'sendingVkWall',
  3974. text: name
  3975. });
  3976. const {
  3977. result,
  3978. statusText,
  3979. status,
  3980. data
  3981. } = await tools_httpRequest({
  3982. url: 'https://vk.com/like.php',
  3983. method: 'POST',
  3984. headers: {
  3985. origin: 'https://vk.com',
  3986. referer: `https://vk.com/${name}`,
  3987. 'content-type': 'application/x-www-form-urlencoded'
  3988. },
  3989. data: $.param({
  3990. act: 'publish_box',
  3991. al: 1,
  3992. object: name
  3993. })
  3994. });
  3995. if (result === 'Success') {
  3996. if (data?.status === 200) {
  3997. const hash = data.responseText.match(/shHash:[\s]*'(.*?)'/)?.[1];
  3998. if (hash) {
  3999. const {
  4000. result: resultR,
  4001. statusText: statusTextR,
  4002. status: statusR,
  4003. data: dataR
  4004. } = await tools_httpRequest({
  4005. url: 'https://vk.com/like.php',
  4006. method: 'POST',
  4007. headers: {
  4008. origin: 'https://vk.com',
  4009. referer: `https://vk.com/${name}`,
  4010. 'content-type': 'application/x-www-form-urlencoded'
  4011. },
  4012. data: $.param({
  4013. Message: '',
  4014. act: 'a_do_publish',
  4015. al: 1,
  4016. close_comments: 0,
  4017. friends_only: 0,
  4018. from: 'box',
  4019. hash: hash,
  4020. list: '',
  4021. mark_as_ads: 0,
  4022. mute_notifications: 0,
  4023. object: name,
  4024. ret_data: 1,
  4025. to: 0
  4026. })
  4027. });
  4028. if (resultR === 'Success') {
  4029. if (dataR?.status === 200) {
  4030. const jsonData = JSON.parse(dataR.responseText?.replace('\x3c!--', '') || '{}');
  4031. if (jsonData?.payload?.[1]?.[1]?.share_my === true) {
  4032. logStatus.success();
  4033. const postId = String(jsonData?.payload?.[1]?.[1]?.post_id);
  4034. const ownerId = String(jsonData?.payload?.[1]?.[1]?.owner_id);
  4035. if (postId && ownerId) {
  4036. this.#setCache(name, `${ownerId}_${postId}`);
  4037. }
  4038. this.tasks.names = unique([ ...this.tasks.names, name ]);
  4039. return true;
  4040. }
  4041. }
  4042. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  4043. return false;
  4044. }
  4045. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  4046. return false;
  4047. }
  4048. logStatus.error('Error: Get "hash" failed');
  4049. return false;
  4050. }
  4051. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4052. return false;
  4053. }
  4054. logStatus.error(`${result}:${statusText}(${status})`);
  4055. return false;
  4056. } catch (error) {
  4057. throwError(error, 'Vk.sendWall');
  4058. return false;
  4059. }
  4060. }
  4061. async #deleteWall(name, dataParams) {
  4062. try {
  4063. const logStatus = scripts_echoLog({
  4064. type: 'deletingVkWall',
  4065. text: name
  4066. });
  4067. const {
  4068. result,
  4069. statusText,
  4070. status,
  4071. data
  4072. } = await tools_httpRequest({
  4073. url: 'https://vk.com/al_wall.php?act=delete',
  4074. method: 'POST',
  4075. headers: {
  4076. origin: 'https://vk.com',
  4077. referer: `https://vk.com/${this.#username}?w=wall${this.#cache[name]}%2Fall`,
  4078. 'content-type': 'application/x-www-form-urlencoded'
  4079. },
  4080. data: $.param({
  4081. act: 'delete',
  4082. al: 1,
  4083. confirm: 0,
  4084. from: 'wkview',
  4085. hash: dataParams.wallHash,
  4086. post: this.#cache[name]
  4087. })
  4088. });
  4089. if (result === 'Success') {
  4090. if (data?.status === 200) {
  4091. const jsonData = JSON.parse(data.responseText?.replace('\x3c!--', '') || '{}');
  4092. if (jsonData?.payload?.[1]?.[1]) {
  4093. logStatus.success();
  4094. return true;
  4095. }
  4096. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4097. return false;
  4098. }
  4099. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4100. return false;
  4101. }
  4102. logStatus.error(`${result}:${statusText}(${status})`);
  4103. return false;
  4104. } catch (error) {
  4105. throwError(error, 'Vk.deleteWall');
  4106. return false;
  4107. }
  4108. }
  4109. async #getId(name, doTask) {
  4110. try {
  4111. let url = `https://vk.com/${name}`;
  4112. if (/^wall-/.test(name)) {
  4113. if (doTask) {
  4114. return {
  4115. type: 'sendWall'
  4116. };
  4117. }
  4118. if (!this.#cache[name]) {
  4119. return {
  4120. type: 'unSupport'
  4121. };
  4122. }
  4123. url = `https://vk.com/${this.#username}?w=wall${this.#cache[name]}`;
  4124. }
  4125. const logStatus = scripts_echoLog({
  4126. type: 'gettingVkId',
  4127. text: name
  4128. });
  4129. const {
  4130. result,
  4131. statusText,
  4132. status,
  4133. data
  4134. } = await tools_httpRequest({
  4135. url: url,
  4136. method: 'GET'
  4137. });
  4138. if (result === 'Success') {
  4139. if (data?.status === 200) {
  4140. const [ , groupAct, groupId, , groupHash ] = data.responseText.match(/Groups.(enter|leave)\(.*?,.*?([\d]+?), (&#39;|')(.*?)(&#39;|')/) || [];
  4141. const publicHash = data.responseText.match(/"enterHash":"(.*?)"/)?.[1];
  4142. const publicPid = data.responseText.match(/"public_id":([\d]+?),/)?.[1];
  4143. const publicJoined = !data.responseText.includes('Public.subscribe');
  4144. if (groupAct && groupId && groupHash) {
  4145. logStatus.success();
  4146. return {
  4147. groupAct: groupAct,
  4148. groupId: groupId,
  4149. groupHash: groupHash,
  4150. type: 'group'
  4151. };
  4152. } else if (publicHash && publicPid) {
  4153. logStatus.success();
  4154. return {
  4155. publicHash: publicHash,
  4156. publicPid: publicPid,
  4157. publicJoined: publicJoined,
  4158. type: 'public'
  4159. };
  4160. } else if (name.includes('action=like')) {
  4161. const hash = data.responseText.match(/data-reaction-hash="(.*?)"/)?.[1];
  4162. const trackCode = data.responseText.match(/data-post-track-code="(.*?)"/)?.[1];
  4163. const object = name.match(/wall-[\w_]+/)?.[0];
  4164. if (hash && trackCode && object) {
  4165. logStatus.success();
  4166. return {
  4167. type: 'likeWall',
  4168. hash: hash,
  4169. trackCode: trackCode,
  4170. object: object
  4171. };
  4172. }
  4173. } else if (data.responseText.includes('wall.deletePost') && !doTask) {
  4174. const wallHash = data.responseText.match(/wall\.deletePost\(this, '.*?', '(.*?)'\)/)?.[1];
  4175. if (wallHash) {
  4176. logStatus.success();
  4177. return {
  4178. type: 'deleteWall',
  4179. wallHash: wallHash
  4180. };
  4181. }
  4182. } else if (name.includes('wall') && doTask) {
  4183. logStatus.success();
  4184. return {
  4185. type: 'sendWall'
  4186. };
  4187. }
  4188. logStatus.error('Error: Parameters not found!');
  4189. return false;
  4190. }
  4191. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4192. return false;
  4193. }
  4194. logStatus.error(`${result}:${statusText}(${status})`);
  4195. return false;
  4196. } catch (error) {
  4197. throwError(error, 'Vk.getId');
  4198. return false;
  4199. }
  4200. }
  4201. async #toggleVk({
  4202. name,
  4203. doTask = true
  4204. }) {
  4205. try {
  4206. if (!doTask && this.whiteList.names.includes(name)) {
  4207. scripts_echoLog({
  4208. type: 'whiteList',
  4209. text: 'Vk.undoTask',
  4210. id: name
  4211. });
  4212. return true;
  4213. }
  4214. const formatName = name.replace(/\/$/, '');
  4215. const data = await this.#getId(formatName, doTask);
  4216. if (!data) {
  4217. return false;
  4218. }
  4219. switch (data.type) {
  4220. case 'group':
  4221. return await this.#toggleGroup(formatName, data, doTask);
  4222.  
  4223. case 'public':
  4224. return await this.#togglePublic(formatName, data, doTask);
  4225.  
  4226. case 'likeWall':
  4227. return await this.#toggleLikeWall(formatName, data, doTask);
  4228.  
  4229. case 'sendWall':
  4230. return doTask ? await this.#sendWall(formatName) : true;
  4231.  
  4232. case 'deleteWall':
  4233. return doTask ? true : await this.#deleteWall(formatName, data);
  4234.  
  4235. default:
  4236. return false;
  4237. }
  4238. } catch (error) {
  4239. throwError(error, 'Vk.toggleVk');
  4240. return false;
  4241. }
  4242. }
  4243. async toggle({
  4244. doTask = true,
  4245. nameLinks = []
  4246. }) {
  4247. try {
  4248. if (!this.#initialized) {
  4249. scripts_echoLog({
  4250. text: i18n('needInit')
  4251. });
  4252. return false;
  4253. }
  4254. const prom = [];
  4255. if (doTask && !globalOptions.doTask.vk.names || !doTask && !globalOptions.undoTask.vk.names) {
  4256. scripts_echoLog({
  4257. type: 'globalOptionsSkip',
  4258. text: 'vk.names'
  4259. });
  4260. } else {
  4261. const realNames = this.getRealParams('names', nameLinks, doTask, link => link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1]);
  4262. if (realNames.length > 0) {
  4263. for (const name of realNames) {
  4264. prom.push(this.#toggleVk({
  4265. name: name,
  4266. doTask: doTask
  4267. }));
  4268. await delay(1e3);
  4269. }
  4270. }
  4271. }
  4272. return Promise.all(prom).then(() => true);
  4273. } catch (error) {
  4274. throwError(error, 'Vk.toggle');
  4275. return false;
  4276. }
  4277. }
  4278. #setCache(name, postId) {
  4279. try {
  4280. this.#cache[name] = postId;
  4281. GM_setValue('vkCache', this.#cache);
  4282. } catch (error) {
  4283. throwError(error, 'Vk.setCache');
  4284. }
  4285. }
  4286. }
  4287. const social_Vk = Vk;
  4288. const getInfo = async function(link, type) {
  4289. try {
  4290. const logStatus = scripts_echoLog({
  4291. text: i18n('gettingYtbToken')
  4292. });
  4293. const {
  4294. result,
  4295. statusText,
  4296. status,
  4297. data
  4298. } = await tools_httpRequest({
  4299. url: link,
  4300. method: 'GET'
  4301. });
  4302. if (result === 'Success') {
  4303. if (data?.status === 200) {
  4304. if (data.responseText.includes('accounts.google.com/ServiceLogin?service=youtube')) {
  4305. logStatus.error(`Error:${i18n('loginYtb')}`, true);
  4306. return {
  4307. needLogin: true
  4308. };
  4309. }
  4310. const apiKey = data.responseText.match(/"INNERTUBE_API_KEY":"(.*?)"/)?.[1];
  4311. const context = (data.responseText.match(/\(\{"INNERTUBE_CONTEXT":([\w\W]*?)\}\)/) || data.responseText.match(/"INNERTUBE_CONTEXT":([\w\W]*?\}),"INNERTUBE/))?.[1] || '{}';
  4312. const {
  4313. client,
  4314. request
  4315. } = JSON.parse(context);
  4316. if (apiKey && client && request) {
  4317. client.hl = 'en';
  4318. if (type === 'channel') {
  4319. const channelId = data.responseText.match(/"channelId":"(.+?)"/)?.[1];
  4320. if (channelId) {
  4321. logStatus.success();
  4322. return {
  4323. params: {
  4324. apiKey: apiKey,
  4325. client: client,
  4326. request: request,
  4327. channelId: channelId
  4328. }
  4329. };
  4330. }
  4331. logStatus.error('Error: Get "channelId" failed!');
  4332. return {};
  4333. } else if (type === 'likeVideo') {
  4334. const videoId = data.responseText.match(/<link rel="shortlinkUrl" href="https:\/\/youtu\.be\/(.*?)">/)?.[1];
  4335. const likeParams = data.responseText.match(/"likeParams":"(.*?)"/)?.[1];
  4336. if (videoId) {
  4337. logStatus.success();
  4338. return {
  4339. params: {
  4340. apiKey: apiKey,
  4341. client: client,
  4342. request: request,
  4343. videoId: videoId,
  4344. likeParams: likeParams
  4345. }
  4346. };
  4347. }
  4348. logStatus.error('Error: Get "videoId" failed!');
  4349. return {};
  4350. }
  4351. logStatus.error('Error: Unknown type');
  4352. return {};
  4353. }
  4354. logStatus.error('Error: Parameter "apiKey" not found!');
  4355. return {};
  4356. }
  4357. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4358. return {};
  4359. }
  4360. logStatus.error(`${result}:${statusText}(${status})`);
  4361. return {};
  4362. } catch (error) {
  4363. throwError(error, 'Youtube.getInfo');
  4364. return {};
  4365. }
  4366. };
  4367. class Youtube extends social_Social {
  4368. tasks;
  4369. whiteList;
  4370. #auth = GM_getValue('youtubeAuth') || {};
  4371. #initialized = false;
  4372. #verifyChannel = `https://www.youtube.com/channel/${globalOptions.other.youtubeVerifyChannel}`;
  4373. constructor() {
  4374. super();
  4375. const defaultTasksTemplate = {
  4376. channels: [],
  4377. likes: []
  4378. };
  4379. this.tasks = defaultTasksTemplate;
  4380. this.whiteList = {
  4381. ...defaultTasksTemplate,
  4382. ...GM_getValue('whiteList')?.youtube || {}
  4383. };
  4384. }
  4385. async init() {
  4386. try {
  4387. if (this.#initialized) {
  4388. return true;
  4389. }
  4390. if (!this.#auth.PAPISID) {
  4391. if (await this.#updateAuth()) {
  4392. this.#initialized = true;
  4393. return true;
  4394. }
  4395. return false;
  4396. }
  4397. const isVerified = await this.#verifyAuth();
  4398. if (isVerified) {
  4399. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  4400. this.#initialized = true;
  4401. return true;
  4402. }
  4403. GM_setValue('youtubeAuth', null);
  4404. if (await this.#updateAuth()) {
  4405. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  4406. this.#initialized = true;
  4407. return true;
  4408. }
  4409. scripts_echoLog({}).error(i18n('initFailed', 'Youtube'));
  4410. return false;
  4411. } catch (error) {
  4412. throwError(error, 'Youtube.init');
  4413. return false;
  4414. }
  4415. }
  4416. async #verifyAuth() {
  4417. try {
  4418. return await this.#toggleChannel({
  4419. link: this.#verifyChannel,
  4420. doTask: true,
  4421. verify: true
  4422. });
  4423. } catch (error) {
  4424. throwError(error, 'Youtube.verifyAuth');
  4425. return false;
  4426. }
  4427. }
  4428. async #updateAuth() {
  4429. try {
  4430. const logStatus = scripts_echoLog({
  4431. text: i18n('updatingAuth', 'Youtube')
  4432. });
  4433. return await new Promise(resolve => {
  4434. GM_cookie.list({
  4435. url: 'https://www.youtube.com/@YouTube'
  4436. }, async (cookies, error) => {
  4437. if (!error) {
  4438. const PAPISID = cookies.find(cookie => cookie.name === '__Secure-3PAPISID')?.value;
  4439. if (PAPISID) {
  4440. GM_setValue('youtubeAuth', {
  4441. PAPISID: PAPISID
  4442. });
  4443. this.#auth = {
  4444. PAPISID: PAPISID
  4445. };
  4446. logStatus.success();
  4447. resolve(await this.#verifyAuth());
  4448. } else {
  4449. logStatus.error(i18n('needLogin'));
  4450. resolve(false);
  4451. }
  4452. } else {
  4453. logStatus.error('Error: Update youtube auth failed!');
  4454. resolve(false);
  4455. }
  4456. });
  4457. });
  4458. } catch (error) {
  4459. throwError(error, 'Youtube.updateAuth');
  4460. return false;
  4461. }
  4462. }
  4463. #getInfo(link, type) {
  4464. return getInfo(link, type);
  4465. }
  4466. async #toggleChannel({
  4467. link,
  4468. doTask = true,
  4469. verify = false
  4470. }) {
  4471. try {
  4472. const {
  4473. params,
  4474. needLogin
  4475. } = await this.#getInfo(link, 'channel');
  4476. const {
  4477. apiKey,
  4478. client,
  4479. request,
  4480. channelId
  4481. } = params || {};
  4482. if (needLogin) {
  4483. scripts_echoLog({
  4484. html: i18n('loginYtb')
  4485. });
  4486. return false;
  4487. }
  4488. if (!(apiKey && client && request && channelId)) {
  4489. scripts_echoLog({
  4490. text: '"getYtbToken" failed'
  4491. });
  4492. return false;
  4493. }
  4494. if (!doTask && !verify && this.whiteList.channels.includes(channelId)) {
  4495. scripts_echoLog({
  4496. type: 'whiteList',
  4497. text: 'Youtube.unfollowChannel',
  4498. id: channelId
  4499. });
  4500. return true;
  4501. }
  4502. const logStatus = verify ? scripts_echoLog({
  4503. text: i18n('verifyingAuth', 'Youtube')
  4504. }) : scripts_echoLog({
  4505. type: doTask ? 'followingYtbChannel' : 'unfollowingYtbChannel',
  4506. text: channelId
  4507. });
  4508. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  4509. const {
  4510. result,
  4511. statusText,
  4512. status,
  4513. data
  4514. } = await tools_httpRequest({
  4515. url: `https://www.youtube.com/youtubei/v1/subscription/${doTask ? '' : 'un'}subscribe?key=${apiKey}&prettyPrint=false`,
  4516. method: 'POST',
  4517. headers: {
  4518. origin: 'https://www.youtube.com',
  4519. referer: `https://www.youtube.com/channel/${channelId}`,
  4520. 'content-type': 'application/json',
  4521. 'x-goog-authuser': '0',
  4522. 'x-goog-visitor-id': client?.visitorData,
  4523. 'x-origin': 'https://www.youtube.com',
  4524. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  4525. },
  4526. data: JSON.stringify({
  4527. context: {
  4528. client: client,
  4529. request: {
  4530. sessionId: request?.sessionId,
  4531. internalExperimentFlags: [],
  4532. consistencyTokenJars: []
  4533. },
  4534. user: {}
  4535. },
  4536. channelIds: [ channelId ],
  4537. params: doTask ? 'EgIIAhgA' : 'CgIIAhgA'
  4538. })
  4539. });
  4540. if (result === 'Success') {
  4541. if (data?.status === 200) {
  4542. if (doTask && (/"subscribed":true/.test(data.responseText) || data.responseText.includes('The subscription already exists')) || !doTask && /"subscribed":false/.test(data.responseText)) {
  4543. logStatus.success();
  4544. if (doTask && !verify) {
  4545. this.tasks.channels = unique([ ...this.tasks.channels, link ]);
  4546. }
  4547. return true;
  4548. }
  4549. if (verify && data.responseText.includes('You may not subscribe to yourself')) {
  4550. logStatus.success();
  4551. return true;
  4552. }
  4553. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4554. return false;
  4555. }
  4556. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4557. return false;
  4558. }
  4559. logStatus.error(`${result}:${statusText}(${status})`);
  4560. return false;
  4561. } catch (error) {
  4562. throwError(error, 'Youtube.toggleChannel');
  4563. return false;
  4564. }
  4565. }
  4566. async #toggleLikeVideo({
  4567. link,
  4568. doTask = true
  4569. }) {
  4570. try {
  4571. const {
  4572. params,
  4573. needLogin
  4574. } = await this.#getInfo(link, 'likeVideo');
  4575. const {
  4576. apiKey,
  4577. client,
  4578. request,
  4579. videoId,
  4580. likeParams
  4581. } = params || {};
  4582. if (needLogin) {
  4583. scripts_echoLog({
  4584. html: `${i18n('loginYtb')}`
  4585. });
  4586. return false;
  4587. }
  4588. if (!(apiKey && client && request && videoId && likeParams)) {
  4589. scripts_echoLog({
  4590. text: '"getYtbToken" failed'
  4591. });
  4592. return false;
  4593. }
  4594. if (!doTask && this.whiteList.likes.includes(videoId)) {
  4595. scripts_echoLog({
  4596. type: 'whiteList',
  4597. text: 'Youtube.unlikeVideo',
  4598. id: videoId
  4599. });
  4600. return true;
  4601. }
  4602. const logStatus = scripts_echoLog({
  4603. type: doTask ? 'likingYtbVideo' : 'unlikingYtbVideo',
  4604. text: videoId
  4605. });
  4606. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  4607. const likeVideoData = {
  4608. context: {
  4609. client: client,
  4610. request: {
  4611. sessionId: request.sessionId,
  4612. internalExperimentFlags: [],
  4613. consistencyTokenJars: []
  4614. },
  4615. user: {}
  4616. },
  4617. target: {
  4618. videoId: videoId
  4619. }
  4620. };
  4621. if (doTask) {
  4622. if (likeParams) {
  4623. likeVideoData.params = likeParams;
  4624. } else {
  4625. logStatus.error('Empty likeParams');
  4626. return false;
  4627. }
  4628. }
  4629. const {
  4630. result,
  4631. statusText,
  4632. status,
  4633. data
  4634. } = await tools_httpRequest({
  4635. url: `https://www.youtube.com/youtubei/v1/like/${doTask ? '' : 'remove'}like?key=${apiKey}`,
  4636. method: 'POST',
  4637. headers: {
  4638. origin: 'https://www.youtube.com',
  4639. referer: `https://www.youtube.com/watch?v=${videoId}`,
  4640. 'content-type': 'application/json',
  4641. 'x-goog-authuser': '0',
  4642. 'x-goog-visitor-id': client.visitorData,
  4643. 'x-origin': 'https://www.youtube.com',
  4644. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  4645. },
  4646. data: JSON.stringify(likeVideoData)
  4647. });
  4648. if (result === 'Success') {
  4649. if (data?.status === 200) {
  4650. if (doTask && data.responseText.includes('Added to Liked videos') || !doTask && (data.responseText.includes('Removed from Liked videos') || data.responseText.includes('Dislike removed'))) {
  4651. logStatus.success();
  4652. if (doTask) {
  4653. this.tasks.likes = unique([ ...this.tasks.likes, link ]);
  4654. }
  4655. return true;
  4656. }
  4657. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4658. return false;
  4659. }
  4660. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4661. return false;
  4662. }
  4663. logStatus.error(`${result}:${statusText}(${status})`);
  4664. return false;
  4665. } catch (error) {
  4666. throwError(error, 'Youtube.toggleLikeVideo');
  4667. return false;
  4668. }
  4669. }
  4670. async toggle({
  4671. doTask = true,
  4672. channelLinks = [],
  4673. videoLinks = []
  4674. }) {
  4675. try {
  4676. if (!this.#initialized) {
  4677. scripts_echoLog({
  4678. text: i18n('needInit')
  4679. });
  4680. return false;
  4681. }
  4682. const prom = [];
  4683. if (doTask && !globalOptions.doTask.youtube.channels || !doTask && !globalOptions.undoTask.youtube.channels) {
  4684. scripts_echoLog({
  4685. type: 'globalOptionsSkip',
  4686. text: 'youtube.channels'
  4687. });
  4688. } else {
  4689. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => {
  4690. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4691. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4692. }
  4693. return link;
  4694. });
  4695. if (realChannels.length > 0) {
  4696. for (const channel of realChannels) {
  4697. prom.push(this.#toggleChannel({
  4698. link: channel,
  4699. doTask: doTask
  4700. }));
  4701. await delay(1e3);
  4702. }
  4703. }
  4704. }
  4705. if (doTask && !globalOptions.doTask.youtube.likes || !doTask && !globalOptions.undoTask.youtube.likes) {
  4706. scripts_echoLog({
  4707. type: 'globalOptionsSkip',
  4708. text: 'youtube.likes'
  4709. });
  4710. } else {
  4711. const realLikes = this.getRealParams('likes', videoLinks, doTask, link => {
  4712. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4713. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4714. }
  4715. return link;
  4716. });
  4717. if (realLikes.length > 0) {
  4718. for (const video of realLikes) {
  4719. prom.push(this.#toggleLikeVideo({
  4720. link: video,
  4721. doTask: doTask
  4722. }));
  4723. await delay(1e3);
  4724. }
  4725. }
  4726. }
  4727. return Promise.all(prom).then(() => true);
  4728. } catch (error) {
  4729. throwError(error, 'Youtube.toggle');
  4730. return false;
  4731. }
  4732. }
  4733. }
  4734. class SteamASF {
  4735. #asfOptions;
  4736. #botName = 'asf';
  4737. #groupInfo;
  4738. async init() {
  4739. try {
  4740. const asfCommandsUrl = new URL('/Api/Command/', globalOptions.ASF.AsfIpcUrl);
  4741. this.#asfOptions = {
  4742. url: asfCommandsUrl.href,
  4743. method: 'POST',
  4744. responseType: 'json',
  4745. headers: {
  4746. accept: 'application/json',
  4747. 'Content-Type': 'application/json',
  4748. Host: asfCommandsUrl.host,
  4749. Origin: asfCommandsUrl.origin,
  4750. Referer: asfCommandsUrl.href,
  4751. Authentication: globalOptions.ASF.AsfIpcPassword
  4752. }
  4753. };
  4754. if (globalOptions.ASF.AsfBotname) {
  4755. this.#botName = globalOptions.ASF.AsfBotname;
  4756. }
  4757. const logStatus = scripts_echoLog({
  4758. text: i18n('initingASF')
  4759. });
  4760. const {
  4761. result,
  4762. statusText,
  4763. status,
  4764. data
  4765. } = await tools_httpRequest({
  4766. ...this.#asfOptions,
  4767. data: '{"Command":"!stats"}'
  4768. });
  4769. if (result === 'Success') {
  4770. if (data?.response?.Success === true && data.response.Message === 'OK' && data.response.Result) {
  4771. logStatus.success();
  4772. return true;
  4773. }
  4774. if (data?.response?.Result || data?.response?.Message) {
  4775. logStatus.error(data?.response?.Result || data.response.Message);
  4776. return false;
  4777. }
  4778. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4779. return false;
  4780. }
  4781. logStatus.error(`${result}:${statusText}(${status})`);
  4782. return false;
  4783. } catch (error) {
  4784. throwError(error, 'SteamASF.init');
  4785. return false;
  4786. }
  4787. }
  4788. async joinGroup(groupName) {
  4789. try {
  4790. const logStatus = scripts_echoLog({
  4791. type: 'joiningSteamGroup',
  4792. text: groupName
  4793. });
  4794. const {
  4795. result,
  4796. statusText,
  4797. status,
  4798. data
  4799. } = await tools_httpRequest({
  4800. ...this.#asfOptions,
  4801. data: JSON.stringify({
  4802. Command: `!JOINGROUP ${this.#botName} ${groupName}`
  4803. })
  4804. });
  4805. if (result === 'Success') {
  4806. if (data?.status === 200 && [ '已加入', '已申请', 'Joined', 'Applied', 'Присоединился', 'costs' ].find(text => data.response?.Result?.includes(text))) {
  4807. logStatus.success();
  4808. return true;
  4809. }
  4810. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4811. return false;
  4812. }
  4813. logStatus.error(`${result}:${statusText}(${status})`);
  4814. return false;
  4815. } catch (error) {
  4816. throwError(error, 'SteamASF.joinGroup');
  4817. return false;
  4818. }
  4819. }
  4820. async leaveGroup(groupName) {
  4821. try {
  4822. if (!this.#groupInfo) {
  4823. if (!await this.#getGroupId()) {
  4824. return false;
  4825. }
  4826. }
  4827. const groupId = await this.#groupInfo[groupName];
  4828. if (!groupId) {
  4829. return false;
  4830. }
  4831. const logStatus = scripts_echoLog({
  4832. type: 'leavingSteamGroup',
  4833. text: groupName
  4834. });
  4835. const {
  4836. result,
  4837. statusText,
  4838. status,
  4839. data
  4840. } = await tools_httpRequest({
  4841. ...this.#asfOptions,
  4842. data: JSON.stringify({
  4843. Command: `!LEAVEGROUP ${this.#botName} ${groupId}`
  4844. })
  4845. });
  4846. if (result === 'Success') {
  4847. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4848. logStatus.success();
  4849. return true;
  4850. }
  4851. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4852. return false;
  4853. }
  4854. logStatus.error(`${result}:${statusText}(${status})`);
  4855. return false;
  4856. } catch (error) {
  4857. throwError(error, 'SteamASF.leaveGroup');
  4858. return false;
  4859. }
  4860. }
  4861. async #getGroupId() {
  4862. try {
  4863. const logStatus = scripts_echoLog({
  4864. type: 'gettingSteamGroupId',
  4865. text: 'All'
  4866. });
  4867. const {
  4868. result,
  4869. statusText,
  4870. status,
  4871. data
  4872. } = await tools_httpRequest({
  4873. ...this.#asfOptions,
  4874. data: JSON.stringify({
  4875. Command: `!GROUPLIST ${this.#botName}`
  4876. })
  4877. });
  4878. if (result === 'Success') {
  4879. if (data?.status === 200 && data.response?.Result?.includes('|')) {
  4880. this.#groupInfo = Object.fromEntries(data.response.Result.split('\n').map(line => {
  4881. const [ , name, id ] = line.trim().split('|');
  4882. if (name && id) {
  4883. return [ name, id ];
  4884. }
  4885. return null;
  4886. }).filter(ele => ele));
  4887. logStatus.success();
  4888. return true;
  4889. }
  4890. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4891. return false;
  4892. }
  4893. logStatus.error(`${result}:${statusText}(${status})`);
  4894. return false;
  4895. } catch (error) {
  4896. throwError(error, 'SteamASF.getGroupID');
  4897. return false;
  4898. }
  4899. }
  4900. async addToWishlist(gameId) {
  4901. try {
  4902. const logStatus = scripts_echoLog({
  4903. type: 'addingToWishlist',
  4904. text: gameId
  4905. });
  4906. if ((await this.#checkGame(gameId)).wishlist === true) {
  4907. logStatus.success();
  4908. return true;
  4909. }
  4910. const {
  4911. result,
  4912. statusText,
  4913. status,
  4914. data
  4915. } = await tools_httpRequest({
  4916. ...this.#asfOptions,
  4917. data: JSON.stringify({
  4918. Command: `!ADDWISHLIST ${this.#botName} ${gameId}`
  4919. })
  4920. });
  4921. if (result === 'Success') {
  4922. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4923. logStatus.success();
  4924. return true;
  4925. }
  4926. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4927. return false;
  4928. }
  4929. logStatus.error(`${result}:${statusText}(${status})`);
  4930. return false;
  4931. } catch (error) {
  4932. throwError(error, 'SteamASF.addToWishlist');
  4933. return false;
  4934. }
  4935. }
  4936. async removeFromWishlist(gameId) {
  4937. try {
  4938. const logStatus = scripts_echoLog({
  4939. type: 'removingFromWishlist',
  4940. text: gameId
  4941. });
  4942. if ((await this.#checkGame(gameId)).wishlist === false) {
  4943. logStatus.success();
  4944. return true;
  4945. }
  4946. const {
  4947. result,
  4948. statusText,
  4949. status,
  4950. data
  4951. } = await tools_httpRequest({
  4952. ...this.#asfOptions,
  4953. data: JSON.stringify({
  4954. Command: `!REMOVEWISHLIST ${this.#botName} ${gameId}`
  4955. })
  4956. });
  4957. if (result === 'Success') {
  4958. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4959. logStatus.success();
  4960. return true;
  4961. }
  4962. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4963. return false;
  4964. }
  4965. logStatus.error(`${result}:${statusText}(${status})`);
  4966. return false;
  4967. } catch (error) {
  4968. throwError(error, 'SteamASF.removeFromWishlist');
  4969. return false;
  4970. }
  4971. }
  4972. async toggleFollowGame(gameId, doTask) {
  4973. try {
  4974. const logStatus = scripts_echoLog({
  4975. type: `${doTask ? '' : 'un'}followingGame`,
  4976. text: gameId
  4977. });
  4978. if (doTask && (await this.#checkGame(gameId)).followed === true || !doTask && (await this.#checkGame(gameId)).followed === false) {
  4979. logStatus.success();
  4980. return true;
  4981. }
  4982. const {
  4983. result,
  4984. statusText,
  4985. status,
  4986. data
  4987. } = await tools_httpRequest({
  4988. ...this.#asfOptions,
  4989. data: JSON.stringify({
  4990. Command: `!${doTask ? '' : 'UN'}FOLLOWGAME ${this.#botName} ${gameId}`
  4991. })
  4992. });
  4993. if (result === 'Success') {
  4994. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4995. logStatus.success();
  4996. return true;
  4997. }
  4998. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4999. return false;
  5000. }
  5001. logStatus.error(`${result}:${statusText}(${status})`);
  5002. return false;
  5003. } catch (error) {
  5004. throwError(error, 'SteamASF.toggleFollowGame');
  5005. return false;
  5006. }
  5007. }
  5008. async #checkGame(gameId) {
  5009. try {
  5010. const {
  5011. result,
  5012. data
  5013. } = await tools_httpRequest({
  5014. ...this.#asfOptions,
  5015. data: JSON.stringify({
  5016. Command: `!CHECK ${this.#botName} ${gameId}`
  5017. })
  5018. });
  5019. if (result === 'Success') {
  5020. if (data?.status === 200 && data.response?.Result?.includes(gameId)) {
  5021. const matchedResult = data.response.Result.split('\n').find(result => result.includes(gameId))?.split('|');
  5022. if (matchedResult?.length > 3) {
  5023. return {
  5024. wishlist: matchedResult.at(-3).trim() === '√' || matchedResult.at(-2).trim() === '√',
  5025. followed: matchedResult.at(-1).trim() === '√'
  5026. };
  5027. }
  5028. return {};
  5029. }
  5030. return {};
  5031. }
  5032. return {};
  5033. } catch (error) {
  5034. throwError(error, 'SteamASF.checkGame');
  5035. return {};
  5036. }
  5037. }
  5038. async toggleCurator(curatorId, doTask = true) {
  5039. try {
  5040. const logStatus = scripts_echoLog({
  5041. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  5042. text: curatorId
  5043. });
  5044. const {
  5045. result,
  5046. statusText,
  5047. status,
  5048. data
  5049. } = await tools_httpRequest({
  5050. ...this.#asfOptions,
  5051. data: JSON.stringify({
  5052. Command: `!${doTask ? '' : 'UN'}FOLLOWCURATOR ${this.#botName} ${curatorId}`
  5053. })
  5054. });
  5055. if (result === 'Success') {
  5056. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  5057. logStatus.success();
  5058. return true;
  5059. }
  5060. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5061. return false;
  5062. }
  5063. logStatus.error(`${result}:${statusText}(${status})`);
  5064. return false;
  5065. } catch (error) {
  5066. throwError(error, 'Steam.toggleCurator');
  5067. return false;
  5068. }
  5069. }
  5070. async addLicense(id) {
  5071. try {
  5072. const [ type, ids ] = id.split('-');
  5073. if (type === 'appid') {
  5074. const logStatus = scripts_echoLog({
  5075. type: 'addingFreeLicense',
  5076. text: ids
  5077. });
  5078. const {
  5079. result,
  5080. statusText,
  5081. status,
  5082. data
  5083. } = await tools_httpRequest({
  5084. ...this.#asfOptions,
  5085. data: JSON.stringify({
  5086. Command: `!addlicense ${this.#botName} app/${ids}`
  5087. })
  5088. });
  5089. if (result === 'Success') {
  5090. if (data?.status === 200 && [ 'AlreadyPurchased', 'OK' ].find(text => data.response?.Result?.includes(text))) {
  5091. logStatus.success();
  5092. return true;
  5093. }
  5094. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5095. return false;
  5096. }
  5097. logStatus.error(`${result}:${statusText}(${status})`);
  5098. return false;
  5099. } else if (type === 'subid') {
  5100. const idsArr = ids.split(',');
  5101. const logStatus = scripts_echoLog({
  5102. type: 'addingFreeLicenseSubid',
  5103. text: ids
  5104. });
  5105. const {
  5106. result,
  5107. statusText,
  5108. status,
  5109. data
  5110. } = await tools_httpRequest({
  5111. ...this.#asfOptions,
  5112. data: JSON.stringify({
  5113. Command: `!addlicense ${this.#botName} ${idsArr.map(id => `sub/${id}`).join(',')}`
  5114. })
  5115. });
  5116. if (result === 'Success') {
  5117. if (data?.status === 200 && data.response?.Result) {
  5118. const resultLines = data.response.Result.split('\n');
  5119. idsArr.forEach(subid => {
  5120. const targetLine = resultLines.find(text => text.includes(subid));
  5121. if (targetLine && [ '成功', 'Success', 'Успех' ].find(text => targetLine.includes(text))) {
  5122. scripts_echoLog({}).success(targetLine);
  5123. } else {
  5124. scripts_echoLog({}).error(targetLine);
  5125. }
  5126. });
  5127. return true;
  5128. }
  5129. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5130. return false;
  5131. }
  5132. logStatus.error(`${result}:${statusText}(${status})`);
  5133. return false;
  5134. }
  5135. return false;
  5136. } catch (error) {
  5137. throwError(error, 'SteamASF.addLicense');
  5138. return false;
  5139. }
  5140. }
  5141. async requestPlayTestAccess(id) {
  5142. try {
  5143. const logStatus = scripts_echoLog({
  5144. type: 'requestingPlayTestAccess',
  5145. text: id
  5146. });
  5147. const {
  5148. result,
  5149. statusText,
  5150. status,
  5151. data
  5152. } = await tools_httpRequest({
  5153. ...this.#asfOptions,
  5154. data: JSON.stringify({
  5155. Command: `!REQUESTACCESS ${this.#botName} ${id}`
  5156. })
  5157. });
  5158. if (result === 'Success') {
  5159. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  5160. logStatus.success();
  5161. return true;
  5162. }
  5163. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5164. return false;
  5165. }
  5166. logStatus.error(`${result}:${statusText}(${status})`);
  5167. return false;
  5168. } catch (error) {
  5169. throwError(error, 'Steam.requestPlayTestAccess');
  5170. return false;
  5171. }
  5172. }
  5173. }
  5174. const social_SteamASF = SteamASF;
  5175. class Steam extends social_Social {
  5176. tasks;
  5177. whiteList;
  5178. #cache = {
  5179. ...{
  5180. group: {},
  5181. officialGroup: {},
  5182. forum: {},
  5183. workshop: {},
  5184. curator: {}
  5185. },
  5186. ...GM_getValue('steamCache')
  5187. };
  5188. #auth = {};
  5189. #storeInitialized = false;
  5190. #communityInitialized = false;
  5191. #area = 'CN';
  5192. #oldArea;
  5193. #areaStatus = 'end';
  5194. #ASF;
  5195. constructor() {
  5196. super();
  5197. const defaultTasksTemplate = {
  5198. groups: [],
  5199. officialGroups: [],
  5200. wishlists: [],
  5201. follows: [],
  5202. forums: [],
  5203. workshops: [],
  5204. workshopVotes: [],
  5205. curators: [],
  5206. curatorLikes: [],
  5207. announcements: [],
  5208. licenses: [],
  5209. playtests: []
  5210. };
  5211. this.tasks = defaultTasksTemplate;
  5212. this.whiteList = {
  5213. ...defaultTasksTemplate,
  5214. ...GM_getValue('whiteList')?.steam || {}
  5215. };
  5216. }
  5217. async init(type = 'all') {
  5218. try {
  5219. if (globalOptions.ASF.AsfEnabled && globalOptions.ASF.AsfIpcUrl && globalOptions.ASF.AsfIpcPassword) {
  5220. this.#ASF = new social_SteamASF();
  5221. if (await this.#ASF.init()) {
  5222. this.#storeInitialized = true;
  5223. this.#communityInitialized = true;
  5224. return true;
  5225. }
  5226. return false;
  5227. }
  5228. if (type === 'store') {
  5229. if (this.#storeInitialized) {
  5230. return true;
  5231. }
  5232. let storeInitialized = await this.#updateStoreAuth();
  5233. if (!storeInitialized) {
  5234. storeInitialized = await this.#updateStoreAuthTab();
  5235. }
  5236. this.#storeInitialized = storeInitialized;
  5237. if (!this.#storeInitialized) {
  5238. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  5239. return false;
  5240. }
  5241. scripts_echoLog({}).success(i18n('initSuccess', 'SteamStore'));
  5242. return true;
  5243. }
  5244. if (type === 'community') {
  5245. if (this.#communityInitialized) {
  5246. return true;
  5247. }
  5248. let communityInitialized = await this.#updateCommunityAuth();
  5249. if (!communityInitialized) {
  5250. communityInitialized = await this.#updateCommunityAuthTab();
  5251. GM_setValue('steamCommunityAuth', null);
  5252. }
  5253. this.#communityInitialized = communityInitialized;
  5254. if (!this.#communityInitialized) {
  5255. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  5256. return false;
  5257. }
  5258. scripts_echoLog({}).success(i18n('initSuccess', 'SteamCommunity'));
  5259. return true;
  5260. }
  5261. if (this.#storeInitialized && this.#communityInitialized) {
  5262. scripts_echoLog({}).success(i18n('initSuccess', 'Steam'));
  5263. return true;
  5264. }
  5265. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  5266. return false;
  5267. } catch (error) {
  5268. throwError(error, 'Steam.init');
  5269. return false;
  5270. }
  5271. }
  5272. async #refreshToken(type = 'steamStore') {
  5273. try {
  5274. const host = {
  5275. steamStore: 'store.steampowered.com',
  5276. steamCommunity: 'steamcommunity.com'
  5277. };
  5278. const logStatus = scripts_echoLog({
  5279. text: i18n('refreshingToken', i18n(type))
  5280. });
  5281. const formData = new FormData();
  5282. formData.append('redir', `https://${host[type]}/`);
  5283. const {
  5284. result,
  5285. statusText,
  5286. status,
  5287. data
  5288. } = await tools_httpRequest({
  5289. url: 'https://login.steampowered.com/jwt/ajaxrefresh',
  5290. method: 'POST',
  5291. responseType: 'json',
  5292. headers: {
  5293. Host: 'login.steampowered.com',
  5294. Origin: `https://${host[type]}`,
  5295. Referer: `https://${host[type]}/`
  5296. },
  5297. data: formData
  5298. });
  5299. if (result === 'Success') {
  5300. if (data?.response?.success) {
  5301. if (await this.#setStoreToken(data.response, type)) {
  5302. logStatus.success();
  5303. return true;
  5304. }
  5305. logStatus.error('Error');
  5306. return false;
  5307. }
  5308. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5309. return false;
  5310. }
  5311. logStatus.error(`${result}:${statusText}(${status})`);
  5312. return false;
  5313. } catch (error) {
  5314. throwError(error, 'Steam.refreshToken');
  5315. return false;
  5316. }
  5317. }
  5318. async #setStoreToken(param, type) {
  5319. try {
  5320. const host = {
  5321. steamStore: 'store.steampowered.com',
  5322. steamCommunity: 'steamcommunity.com'
  5323. };
  5324. const logStatus = scripts_echoLog({
  5325. text: i18n('settingToken', i18n(type))
  5326. });
  5327. const formData = new FormData();
  5328. formData.append('steamID', param.steamID);
  5329. formData.append('nonce', param.nonce);
  5330. formData.append('redir', param.redir);
  5331. formData.append('auth', param.auth);
  5332. const {
  5333. result,
  5334. statusText,
  5335. status,
  5336. data
  5337. } = await tools_httpRequest({
  5338. url: `https://${host[type]}/login/settoken`,
  5339. method: 'POST',
  5340. headers: {
  5341. Accept: 'application/json, text/plain, */*',
  5342. Host: host[type],
  5343. Origin: `https://${host[type]}`
  5344. },
  5345. data: formData
  5346. });
  5347. if (result === 'Success') {
  5348. if (data?.status === 200) {
  5349. logStatus.success();
  5350. return true;
  5351. }
  5352. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5353. return false;
  5354. }
  5355. logStatus.error(`${result}:${statusText}(${status})`);
  5356. return false;
  5357. } catch (error) {
  5358. throwError(error, 'Steam.setStoreToken');
  5359. return false;
  5360. }
  5361. }
  5362. async #updateStoreAuth(retry = false) {
  5363. try {
  5364. const logStatus = scripts_echoLog({
  5365. text: i18n('updatingAuth', i18n('steamStore'))
  5366. });
  5367. const {
  5368. result,
  5369. statusText,
  5370. status,
  5371. data
  5372. } = await tools_httpRequest({
  5373. url: 'https://store.steampowered.com/',
  5374. method: 'GET',
  5375. headers: {
  5376. 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',
  5377. 'Sec-Fetch-Dest': 'document',
  5378. 'Sec-Fetch-Mode': 'navigate',
  5379. 'Upgrade-Insecure-Requests': '1'
  5380. },
  5381. fetch: false,
  5382. redirect: 'manual'
  5383. });
  5384. if (data?.status === 200) {
  5385. if (!data.responseText.includes('data-miniprofile=')) {
  5386. if (await this.#refreshToken('steamStore')) {
  5387. logStatus.warning(i18n('retry'));
  5388. if (retry) {
  5389. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  5390. return false;
  5391. }
  5392. return this.#updateStoreAuth(true);
  5393. }
  5394. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  5395. return false;
  5396. }
  5397. const storeSessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  5398. if (storeSessionID) {
  5399. this.#auth.storeSessionID = storeSessionID;
  5400. logStatus.success();
  5401. return true;
  5402. }
  5403. logStatus.error('Error: Get "sessionID" failed');
  5404. return false;
  5405. }
  5406. if ([ 301, 302 ].includes(data?.status)) {
  5407. if (await this.#refreshToken('steamStore')) {
  5408. logStatus.warning(i18n('retry'));
  5409. if (retry) {
  5410. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  5411. return false;
  5412. }
  5413. return this.#updateStoreAuth(true);
  5414. }
  5415. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  5416. return false;
  5417. }
  5418. logStatus.error(`${result}:${statusText}(${status})`);
  5419. return false;
  5420. } catch (error) {
  5421. throwError(error, 'Steam.updateStoreAuth');
  5422. return false;
  5423. }
  5424. }
  5425. async #updateStoreAuthTab() {
  5426. try {
  5427. const logStatus = scripts_echoLog({
  5428. text: i18n('updatingAuth', i18n('steamStoreTab'))
  5429. });
  5430. return await new Promise(resolve => {
  5431. GM_deleteValue('steamStoreAuth');
  5432. GM_setValue('ATv4_updateStoreAuth', true);
  5433. const newTab = GM_openInTab('https://store.steampowered.com/', {
  5434. active: true,
  5435. setParent: true
  5436. });
  5437. newTab.name = 'ATv4_updateStoreAuth';
  5438. const listenerId = GM_addValueChangeListener('steamStoreAuth', (key, oldValue, newValue) => {
  5439. GM_removeValueChangeListener(listenerId);
  5440. GM_deleteValue('ATv4_updateStoreAuth');
  5441. newTab?.close();
  5442. window.focus();
  5443. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  5444. this.#auth.storeSessionID = newValue.storeSessionID;
  5445. logStatus.success();
  5446. resolve(true);
  5447. return;
  5448. }
  5449. logStatus.error('Failed');
  5450. resolve(false);
  5451. });
  5452. newTab.onclose = () => {
  5453. GM_deleteValue('ATv4_updateStoreAuth');
  5454. };
  5455. });
  5456. } catch (error) {
  5457. throwError(error, 'Steam.updateStoreAuthTab');
  5458. return false;
  5459. }
  5460. }
  5461. async #updateCommunityAuthTab() {
  5462. try {
  5463. const logStatus = scripts_echoLog({
  5464. text: i18n('updatingAuth', i18n('steamCommunityTab'))
  5465. });
  5466. return await new Promise(resolve => {
  5467. GM_deleteValue('steamCommunityAuth');
  5468. GM_setValue('ATv4_updateCommunityAuth', true);
  5469. const newTab = GM_openInTab('https://steamcommunity.com/my', {
  5470. active: true,
  5471. setParent: true
  5472. });
  5473. newTab.name = 'ATv4_updateCommunityAuth';
  5474. const listenerId = GM_addValueChangeListener('steamCommunityAuth', (key, oldValue, newValue) => {
  5475. GM_removeValueChangeListener(listenerId);
  5476. GM_deleteValue('ATv4_updateCommunityAuth');
  5477. newTab?.close();
  5478. window.focus();
  5479. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  5480. this.#auth.steam64Id = newValue.steam64Id;
  5481. this.#auth.communitySessionID = newValue.communitySessionID;
  5482. logStatus.success();
  5483. resolve(true);
  5484. return;
  5485. }
  5486. logStatus.error('Failed');
  5487. resolve(false);
  5488. });
  5489. newTab.onclose = () => {
  5490. GM_deleteValue('ATv4_updateCommunityAuth');
  5491. };
  5492. });
  5493. } catch (error) {
  5494. throwError(error, 'Steam.updateCommunityAuthTab');
  5495. return false;
  5496. }
  5497. }
  5498. async #updateCommunityAuth() {
  5499. try {
  5500. const logStatus = scripts_echoLog({
  5501. text: i18n('gettingUserLink')
  5502. });
  5503. const {
  5504. result,
  5505. statusText,
  5506. status,
  5507. data
  5508. } = await tools_httpRequest({
  5509. url: 'https://steamcommunity.com/my',
  5510. method: 'GET',
  5511. headers: {
  5512. 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',
  5513. Host: 'steamcommunity.com',
  5514. 'Sec-Fetch-Dest': 'document',
  5515. 'Sec-Fetch-Mode': 'navigate'
  5516. },
  5517. fetch: false
  5518. });
  5519. if (data?.status === 200) {
  5520. if (data.finalUrl.includes('https://steamcommunity.com/login/home')) {
  5521. logStatus.error(`Error:${i18n('needLoginSteamCommunity')}`, true);
  5522. return false;
  5523. }
  5524. const steam64Id = data.responseText.match(/g_steamID = "(.+?)";/)?.[1];
  5525. const communitySessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  5526. if (steam64Id && communitySessionID) {
  5527. this.#auth.steam64Id = steam64Id;
  5528. this.#auth.communitySessionID = communitySessionID;
  5529. logStatus.success();
  5530. return true;
  5531. }
  5532. logStatus.error('Error: Get "sessionID" failed');
  5533. return false;
  5534. }
  5535. logStatus.error(`${result}:${statusText}(${status})`);
  5536. return false;
  5537. } catch (error) {
  5538. throwError(error, 'Steam.updateCommunityAuth');
  5539. return false;
  5540. }
  5541. }
  5542. async #getAreaInfo() {
  5543. try {
  5544. const logStatus = scripts_echoLog({
  5545. text: i18n('gettingAreaInfo')
  5546. });
  5547. const {
  5548. result,
  5549. statusText,
  5550. status,
  5551. data
  5552. } = await tools_httpRequest({
  5553. url: 'https://store.steampowered.com/cart/',
  5554. method: 'GET'
  5555. });
  5556. if (result === 'Success') {
  5557. if (data?.status === 200) {
  5558. const cartConfigRaw = data.responseText.match(/data-cart_config="(.*?)"/)?.[1];
  5559. const temp = document.createElement('div');
  5560. temp.innerHTML = cartConfigRaw || '{}';
  5561. const cartConfigStr = temp.textContent || temp.innerText;
  5562. let cartConfig;
  5563. try {
  5564. cartConfig = JSON.parse(cartConfigStr);
  5565. } catch (error) {
  5566. logStatus.error('Error: get country info filed');
  5567. console.error(error);
  5568. return {};
  5569. }
  5570. if (!cartConfig.rgUserCountryOptions) {
  5571. logStatus.warning('Warning: Area cannot be changed');
  5572. return {};
  5573. }
  5574. const userInfoRaw = data.responseText.match(/data-userinfo="(.*?)"/)?.[1];
  5575. const temp1 = document.createElement('div');
  5576. temp1.innerHTML = userInfoRaw || '{}';
  5577. const userInfoStr = temp1.textContent || temp1.innerText;
  5578. let userInfo;
  5579. try {
  5580. userInfo = JSON.parse(userInfoStr);
  5581. } catch (error) {
  5582. logStatus.error('Error: get country info filed');
  5583. console.error(error);
  5584. return {};
  5585. }
  5586. const currentArea = userInfo.country_code;
  5587. const areas = Object.keys(cartConfig.rgUserCountryOptions).filter(area => area !== 'help');
  5588. if (currentArea && areas.length > 0) {
  5589. this.#area = currentArea;
  5590. logStatus.success();
  5591. return {
  5592. currentArea: currentArea,
  5593. areas: areas
  5594. };
  5595. }
  5596. logStatus.error('Error: get country info filed');
  5597. return {};
  5598. }
  5599. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5600. return {};
  5601. }
  5602. logStatus.error(`${result}:${statusText}(${status})`);
  5603. return {};
  5604. } catch (error) {
  5605. throwError(error, 'Steam.getAreaInfo');
  5606. return {};
  5607. }
  5608. }
  5609. async #changeArea(area) {
  5610. try {
  5611. if (this.#areaStatus === 'waiting') {
  5612. await new Promise(resolve => {
  5613. const checker = setInterval(() => {
  5614. if (this.#areaStatus !== 'waiting') {
  5615. clearInterval(checker);
  5616. resolve(true);
  5617. }
  5618. });
  5619. });
  5620. }
  5621. if (this.#area === area || !area && this.#area !== 'CN') {
  5622. return true;
  5623. }
  5624. this.#areaStatus = 'waiting';
  5625. let aimedArea = area;
  5626. if (!aimedArea) {
  5627. const {
  5628. currentArea,
  5629. areas
  5630. } = await this.#getAreaInfo();
  5631. if (!currentArea || !areas) {
  5632. this.#areaStatus = 'error';
  5633. return false;
  5634. }
  5635. if (currentArea !== 'CN') {
  5636. this.#areaStatus = 'skip';
  5637. scripts_echoLog({
  5638. text: 'notNeededChangeArea'
  5639. });
  5640. return 'skip';
  5641. }
  5642. const anotherArea = areas.filter(area => area && area !== 'CN');
  5643. if (!anotherArea || anotherArea.length === 0) {
  5644. this.#areaStatus = 'noAnotherArea';
  5645. scripts_echoLog({
  5646. text: 'noAnotherArea'
  5647. });
  5648. return false;
  5649. }
  5650. [ aimedArea ] = anotherArea;
  5651. }
  5652. const logStatus = scripts_echoLog({
  5653. text: i18n('changingArea', aimedArea)
  5654. });
  5655. const {
  5656. result,
  5657. statusText,
  5658. status,
  5659. data
  5660. } = await tools_httpRequest({
  5661. url: 'https://store.steampowered.com/country/setcountry',
  5662. method: 'POST',
  5663. headers: {
  5664. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5665. },
  5666. data: $.param({
  5667. cc: aimedArea,
  5668. sessionid: this.#auth.storeSessionID
  5669. })
  5670. });
  5671. if (result === 'Success') {
  5672. if (data?.status === 200 && data.responseText === 'true') {
  5673. const {
  5674. currentArea
  5675. } = await this.#getAreaInfo();
  5676. if (currentArea) {
  5677. this.#area = currentArea;
  5678. if (!this.#oldArea) {
  5679. this.#oldArea = currentArea;
  5680. }
  5681. }
  5682. if (currentArea === aimedArea) {
  5683. this.#areaStatus = 'success';
  5684. logStatus.success();
  5685. return currentArea;
  5686. }
  5687. this.#areaStatus = 'error';
  5688. logStatus.error('Error: change country filed');
  5689. return 'CN';
  5690. }
  5691. this.#areaStatus = 'error';
  5692. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5693. return 'CN';
  5694. }
  5695. this.#areaStatus = 'error';
  5696. logStatus.error(`${result}:${statusText}(${status})`);
  5697. return 'CN';
  5698. } catch (error) {
  5699. this.#areaStatus = 'error';
  5700. throwError(error, 'Steam.changeArea');
  5701. return false;
  5702. }
  5703. }
  5704. async #joinGroup(groupName) {
  5705. try {
  5706. if (this.#ASF) {
  5707. if (await this.#ASF.joinGroup(groupName)) {
  5708. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5709. return true;
  5710. }
  5711. return false;
  5712. }
  5713. const logStatus = scripts_echoLog({
  5714. type: 'joiningSteamGroup',
  5715. text: groupName
  5716. });
  5717. const {
  5718. result,
  5719. statusText,
  5720. status,
  5721. data
  5722. } = await tools_httpRequest({
  5723. url: `https://steamcommunity.com/groups/${groupName}`,
  5724. method: 'POST',
  5725. headers: {
  5726. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5727. },
  5728. data: $.param({
  5729. action: 'join',
  5730. sessionID: this.#auth.communitySessionID
  5731. })
  5732. });
  5733. if (result === 'Success') {
  5734. if (data?.status === 200 && !data.responseText.includes('grouppage_join_area')) {
  5735. logStatus.success();
  5736. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5737. return true;
  5738. }
  5739. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5740. return false;
  5741. }
  5742. logStatus.error(`${result}:${statusText}(${status})`);
  5743. return false;
  5744. } catch (error) {
  5745. throwError(error, 'Steam.joinGroup');
  5746. return false;
  5747. }
  5748. }
  5749. async #leaveGroup(groupName) {
  5750. try {
  5751. if (this.whiteList.groups.includes(groupName)) {
  5752. scripts_echoLog({
  5753. type: 'whiteList',
  5754. text: 'Steam.leaveGroup',
  5755. id: groupName
  5756. });
  5757. return true;
  5758. }
  5759. if (this.#ASF) {
  5760. return await this.#ASF.leaveGroup(groupName);
  5761. }
  5762. const groupId = await this.#getGroupId(groupName);
  5763. if (!groupId) {
  5764. return false;
  5765. }
  5766. const logStatus = scripts_echoLog({
  5767. type: 'leavingSteamGroup',
  5768. text: groupName
  5769. });
  5770. const {
  5771. result,
  5772. statusText,
  5773. status,
  5774. data
  5775. } = await tools_httpRequest({
  5776. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5777. method: 'POST',
  5778. headers: {
  5779. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5780. },
  5781. data: $.param({
  5782. sessionID: this.#auth.communitySessionID,
  5783. action: 'leaveGroup',
  5784. groupId: groupId
  5785. })
  5786. });
  5787. if (result === 'Success') {
  5788. 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) {
  5789. logStatus.success();
  5790. return true;
  5791. }
  5792. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5793. return false;
  5794. }
  5795. logStatus.error(`${result}:${statusText}(${status})`);
  5796. return false;
  5797. } catch (error) {
  5798. throwError(error, 'Steam.leaveGroup');
  5799. return false;
  5800. }
  5801. }
  5802. async #getGroupId(groupName) {
  5803. try {
  5804. const logStatus = scripts_echoLog({
  5805. type: 'gettingSteamGroupId',
  5806. text: groupName
  5807. });
  5808. const groupId = this.#cache.group[groupName];
  5809. if (groupId) {
  5810. logStatus.success();
  5811. return groupId;
  5812. }
  5813. const {
  5814. result,
  5815. statusText,
  5816. status,
  5817. data
  5818. } = await tools_httpRequest({
  5819. url: `https://steamcommunity.com/groups/${groupName}`,
  5820. method: 'GET',
  5821. headers: {
  5822. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5823. }
  5824. });
  5825. if (result === 'Success') {
  5826. if (data?.status === 200) {
  5827. const groupId = data.responseText.match(/OpenGroupChat\( '([0-9]+)'/)?.[1];
  5828. if (groupId) {
  5829. this.#setCache('group', groupName, groupId);
  5830. logStatus.success();
  5831. return groupId;
  5832. }
  5833. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5834. return false;
  5835. }
  5836. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5837. return false;
  5838. }
  5839. logStatus.error(`${result}:${statusText}(${status})`);
  5840. return false;
  5841. } catch (error) {
  5842. throwError(error, 'Steam.getGroupID');
  5843. return false;
  5844. }
  5845. }
  5846. async #joinOfficialGroup(gameId) {
  5847. try {
  5848. if (this.#ASF) {
  5849. if (await this.#ASF.joinGroup(gameId)) {
  5850. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5851. return true;
  5852. }
  5853. return false;
  5854. }
  5855. const logStatus = scripts_echoLog({
  5856. type: 'joiningSteamOfficialGroup',
  5857. text: gameId
  5858. });
  5859. const {
  5860. result,
  5861. statusText,
  5862. status,
  5863. data
  5864. } = await tools_httpRequest({
  5865. url: `https://steamcommunity.com/games/${gameId}?action=join&sessionID=${this.#auth.communitySessionID}`,
  5866. method: 'GET',
  5867. headers: {
  5868. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5869. }
  5870. });
  5871. if (result === 'Success') {
  5872. if (data?.status === 200 && !data.responseText.includes('id="publicGroupJoin"')) {
  5873. logStatus.success();
  5874. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5875. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5876. if (groupId) {
  5877. this.#setCache('officialGroup', gameId, groupId);
  5878. }
  5879. return true;
  5880. }
  5881. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5882. return false;
  5883. }
  5884. logStatus.error(`${result}:${statusText}(${status})`);
  5885. return false;
  5886. } catch (error) {
  5887. throwError(error, 'Steam.joinOfficialGroup');
  5888. return false;
  5889. }
  5890. }
  5891. async #leaveOfficialGroup(gameId) {
  5892. try {
  5893. if (this.whiteList.officialGroups.includes(gameId)) {
  5894. scripts_echoLog({
  5895. type: 'whiteList',
  5896. text: 'Steam.leaveOfficialGroup',
  5897. id: gameId
  5898. });
  5899. return true;
  5900. }
  5901. if (this.#ASF) {
  5902. return await this.#ASF.leaveGroup(gameId);
  5903. }
  5904. const groupId = await this.#getOfficialGroupId(gameId);
  5905. if (!groupId) {
  5906. return false;
  5907. }
  5908. const logStatus = scripts_echoLog({
  5909. type: 'leavingSteamOfficialGroup',
  5910. text: gameId
  5911. });
  5912. const {
  5913. result,
  5914. statusText,
  5915. status,
  5916. data
  5917. } = await tools_httpRequest({
  5918. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5919. method: 'POST',
  5920. headers: {
  5921. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5922. },
  5923. data: $.param({
  5924. sessionID: this.#auth.communitySessionID,
  5925. action: 'leaveGroup',
  5926. groupId: groupId
  5927. })
  5928. });
  5929. if (result === 'Success') {
  5930. if (data?.status === 200) {
  5931. const {
  5932. result: resultR,
  5933. statusText: statusTextR,
  5934. status: statusR,
  5935. data: dataR
  5936. } = await tools_httpRequest({
  5937. url: `https://steamcommunity.com/games/${gameId}`,
  5938. method: 'GET',
  5939. headers: {
  5940. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5941. }
  5942. });
  5943. if (resultR === 'Success') {
  5944. if (dataR?.status === 200 && dataR.responseText.includes('id="publicGroupJoin"')) {
  5945. logStatus.success();
  5946. return true;
  5947. }
  5948. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5949. return false;
  5950. }
  5951. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5952. return false;
  5953. }
  5954. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5955. return false;
  5956. }
  5957. logStatus.error(`${result}:${statusText}(${status})`);
  5958. return false;
  5959. } catch (error) {
  5960. throwError(error, 'Steam.leaveOfficialGroup');
  5961. return false;
  5962. }
  5963. }
  5964. async #getOfficialGroupId(gameId) {
  5965. try {
  5966. const logStatus = scripts_echoLog({
  5967. type: 'gettingSteamOfficialGroupId',
  5968. text: gameId
  5969. });
  5970. const groupId = this.#cache.officialGroup[gameId];
  5971. if (groupId) {
  5972. logStatus.success();
  5973. return groupId;
  5974. }
  5975. const {
  5976. result,
  5977. statusText,
  5978. status,
  5979. data
  5980. } = await tools_httpRequest({
  5981. url: `https://steamcommunity.com/games/${gameId}`,
  5982. method: 'GET',
  5983. headers: {
  5984. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5985. }
  5986. });
  5987. if (result === 'Success') {
  5988. if (data?.status === 200) {
  5989. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5990. if (groupId) {
  5991. this.#setCache('officialGroup', gameId, groupId);
  5992. logStatus.success();
  5993. return groupId;
  5994. }
  5995. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5996. return false;
  5997. }
  5998. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5999. return false;
  6000. }
  6001. logStatus.error(`${result}:${statusText}(${status})`);
  6002. return false;
  6003. } catch (error) {
  6004. throwError(error, 'Steam.getGroupID');
  6005. return false;
  6006. }
  6007. }
  6008. async #addToWishlist(gameId) {
  6009. try {
  6010. if (this.#ASF) {
  6011. if (await this.#ASF.addToWishlist(gameId)) {
  6012. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  6013. return true;
  6014. }
  6015. return false;
  6016. }
  6017. const logStatus = scripts_echoLog({
  6018. type: 'addingToWishlist',
  6019. text: gameId
  6020. });
  6021. const {
  6022. result,
  6023. data
  6024. } = await tools_httpRequest({
  6025. url: 'https://store.steampowered.com/api/addtowishlist',
  6026. method: 'POST',
  6027. headers: {
  6028. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6029. },
  6030. data: $.param({
  6031. sessionid: this.#auth.storeSessionID,
  6032. appid: gameId
  6033. }),
  6034. dataType: 'json'
  6035. });
  6036. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  6037. logStatus.success();
  6038. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  6039. return true;
  6040. }
  6041. const {
  6042. result: resultR,
  6043. statusText: statusTextR,
  6044. status: statusR,
  6045. data: dataR
  6046. } = await tools_httpRequest({
  6047. url: `https://store.steampowered.com/app/${gameId}`,
  6048. method: 'GET'
  6049. });
  6050. if (resultR === 'Success') {
  6051. if (dataR?.status === 200) {
  6052. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  6053. logStatus.warning(i18n('changeAreaNotice'));
  6054. if (!await this.#changeArea()) {
  6055. return false;
  6056. }
  6057. return await this.#addToWishlist(gameId);
  6058. }
  6059. if (dataR.responseText.includes('class="queue_actions_ctn"') && dataR.responseText.includes('class="already_in_library"')) {
  6060. logStatus.success();
  6061. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  6062. return true;
  6063. } 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"')) {
  6064. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  6065. return false;
  6066. }
  6067. logStatus.success();
  6068. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  6069. return true;
  6070. }
  6071. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  6072. return false;
  6073. }
  6074. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  6075. return false;
  6076. } catch (error) {
  6077. throwError(error, 'Steam.addToWishlist');
  6078. return false;
  6079. }
  6080. }
  6081. async #removeFromWishlist(gameId) {
  6082. try {
  6083. if (this.whiteList.wishlists.includes(gameId)) {
  6084. scripts_echoLog({
  6085. type: 'whiteList',
  6086. text: 'Steam.removeFromWishlist',
  6087. id: gameId
  6088. });
  6089. return true;
  6090. }
  6091. if (this.#ASF) {
  6092. return await this.#ASF.removeFromWishlist(gameId);
  6093. }
  6094. const logStatus = scripts_echoLog({
  6095. type: 'removingFromWishlist',
  6096. text: gameId
  6097. });
  6098. const {
  6099. result,
  6100. data
  6101. } = await tools_httpRequest({
  6102. url: 'https://store.steampowered.com/api/removefromwishlist',
  6103. method: 'POST',
  6104. headers: {
  6105. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6106. },
  6107. data: $.param({
  6108. sessionid: this.#auth.storeSessionID,
  6109. appid: gameId
  6110. }),
  6111. dataType: 'json'
  6112. });
  6113. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  6114. logStatus.success();
  6115. return true;
  6116. }
  6117. const {
  6118. result: resultR,
  6119. statusText: statusTextR,
  6120. status: statusR,
  6121. data: dataR
  6122. } = await tools_httpRequest({
  6123. url: `https://store.steampowered.com/app/${gameId}`,
  6124. method: 'GET'
  6125. });
  6126. if (resultR === 'Success') {
  6127. if (dataR?.status === 200) {
  6128. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  6129. logStatus.warning(i18n('changeAreaNotice'));
  6130. const result = await this.#changeArea();
  6131. if (!result || result === 'CN' || result === 'skip') {
  6132. return false;
  6133. }
  6134. return await this.#removeFromWishlist(gameId);
  6135. }
  6136. if (dataR.responseText.includes('class="queue_actions_ctn"') && (dataR.responseText.includes('ds_owned_flag ds_flag') || dataR.responseText.includes('add_to_wishlist_area'))) {
  6137. logStatus.success();
  6138. return true;
  6139. }
  6140. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  6141. return false;
  6142. }
  6143. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  6144. return false;
  6145. }
  6146. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  6147. return false;
  6148. } catch (error) {
  6149. throwError(error, 'Steam.removeFromWishlist');
  6150. return false;
  6151. }
  6152. }
  6153. async #toggleFollowGame(gameId, doTask) {
  6154. try {
  6155. if (!doTask && this.whiteList.follows.includes(gameId)) {
  6156. scripts_echoLog({
  6157. type: 'whiteList',
  6158. text: 'Steam.unfollowGame',
  6159. id: gameId
  6160. });
  6161. return true;
  6162. }
  6163. if (this.#ASF) {
  6164. if (await this.#ASF.toggleFollowGame(gameId, doTask)) {
  6165. if (doTask) {
  6166. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  6167. }
  6168. return true;
  6169. }
  6170. return false;
  6171. }
  6172. const logStatus = scripts_echoLog({
  6173. type: `${doTask ? '' : 'un'}followingGame`,
  6174. text: gameId
  6175. });
  6176. const requestData = {
  6177. sessionid: this.#auth.storeSessionID,
  6178. appid: gameId
  6179. };
  6180. if (!doTask) {
  6181. requestData.unfollow = '1';
  6182. }
  6183. const {
  6184. result,
  6185. data
  6186. } = await tools_httpRequest({
  6187. url: 'https://store.steampowered.com/explore/followgame/',
  6188. method: 'POST',
  6189. headers: {
  6190. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6191. },
  6192. data: $.param(requestData)
  6193. });
  6194. if (result === 'Success' && data?.status === 200 && data.responseText === 'true') {
  6195. logStatus.success();
  6196. return true;
  6197. }
  6198. const followed = await this.#isFollowedGame(gameId);
  6199. if (this.#area === 'CN' && followed === 'areaLocked') {
  6200. logStatus.warning(i18n('changeAreaNotice'));
  6201. if (!await this.#changeArea()) {
  6202. return false;
  6203. }
  6204. return await this.#toggleFollowGame(gameId, doTask);
  6205. }
  6206. if (doTask === followed) {
  6207. logStatus.success();
  6208. if (doTask) {
  6209. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  6210. }
  6211. return true;
  6212. }
  6213. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6214. return false;
  6215. } catch (error) {
  6216. throwError(error, 'Steam.toggleFollowGame');
  6217. return false;
  6218. }
  6219. }
  6220. async #isFollowedGame(gameId) {
  6221. try {
  6222. const {
  6223. result,
  6224. data
  6225. } = await tools_httpRequest({
  6226. url: `https://store.steampowered.com/app/${gameId}`,
  6227. method: 'GET'
  6228. });
  6229. if (result === 'Success') {
  6230. if (data?.status === 200) {
  6231. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6232. return 'areaLocked';
  6233. }
  6234. if ($(data.responseText.replace(/<img.*?>/g, '')).find('.queue_control_button.queue_btn_follow>.btnv6_blue_hoverfade.btn_medium.queue_btn_active').css('display') !== 'none') {
  6235. return true;
  6236. }
  6237. return false;
  6238. }
  6239. return false;
  6240. }
  6241. return false;
  6242. } catch (error) {
  6243. throwError(error, 'Steam.isFollowedGame');
  6244. return false;
  6245. }
  6246. }
  6247. async #toggleForum(gameId, doTask = true) {
  6248. try {
  6249. if (!doTask && this.whiteList.forums.includes(gameId)) {
  6250. scripts_echoLog({
  6251. type: 'whiteList',
  6252. text: 'Steam.unsubscribeForum',
  6253. id: gameId
  6254. });
  6255. return true;
  6256. }
  6257. const forumId = await this.#getForumId(gameId);
  6258. if (!forumId) {
  6259. return false;
  6260. }
  6261. const logStatus = scripts_echoLog({
  6262. type: `${doTask ? '' : 'un'}subscribingForum`,
  6263. text: gameId
  6264. });
  6265. const [ id, feature ] = forumId.split('_');
  6266. const {
  6267. result,
  6268. statusText,
  6269. status,
  6270. data
  6271. } = await tools_httpRequest({
  6272. url: `https://steamcommunity.com/forum/${id}/General/${doTask ? '' : 'un'}subscribe/${feature || '0'}/`,
  6273. method: 'POST',
  6274. responseType: 'json',
  6275. headers: {
  6276. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6277. },
  6278. data: $.param({
  6279. sessionid: this.#auth.communitySessionID
  6280. })
  6281. });
  6282. if (result === 'Success') {
  6283. if (data?.status === 200 && (data.response?.success === 1 || data.response?.success === 29)) {
  6284. if (doTask) {
  6285. this.tasks.forums = unique([ ...this.tasks.forums, gameId ]);
  6286. }
  6287. logStatus.success();
  6288. return true;
  6289. }
  6290. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6291. return true;
  6292. }
  6293. logStatus.error(`${result}:${statusText}(${status})`);
  6294. return true;
  6295. } catch (error) {
  6296. throwError(error, 'Steam.toggleForum');
  6297. return true;
  6298. }
  6299. }
  6300. async #getForumId(gameId) {
  6301. try {
  6302. const logStatus = scripts_echoLog({
  6303. type: 'gettingForumId',
  6304. text: gameId
  6305. });
  6306. const forumId = this.#cache.forum[gameId];
  6307. if (forumId) {
  6308. logStatus.success();
  6309. return forumId;
  6310. }
  6311. const {
  6312. result,
  6313. statusText,
  6314. status,
  6315. data
  6316. } = await tools_httpRequest({
  6317. url: `https://steamcommunity.com/app/${gameId}/discussions/`,
  6318. method: 'GET'
  6319. });
  6320. if (result === 'Success') {
  6321. if (data?.status === 200) {
  6322. const forumId = data.responseText?.match(/General_([\d]+(_[\d]+)?)/)?.[1];
  6323. if (forumId) {
  6324. this.#setCache('forum', gameId, forumId);
  6325. logStatus.success();
  6326. return forumId;
  6327. }
  6328. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6329. return false;
  6330. }
  6331. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6332. return false;
  6333. }
  6334. logStatus.error(`${result}:${statusText}(${status})`);
  6335. return false;
  6336. } catch (error) {
  6337. throwError(error, 'Steam.getForumId');
  6338. return false;
  6339. }
  6340. }
  6341. async #toggleFavoriteWorkshop(id, doTask = true) {
  6342. try {
  6343. if (!doTask && this.whiteList.workshops.includes(id)) {
  6344. scripts_echoLog({
  6345. type: 'whiteList',
  6346. text: 'Steam.unfavoriteWorkshop',
  6347. id: id
  6348. });
  6349. return true;
  6350. }
  6351. const appid = await this.#getWorkshopAppId(id);
  6352. if (!appid) {
  6353. return false;
  6354. }
  6355. const logStatus = scripts_echoLog({
  6356. type: doTask ? 'favoritingWorkshop' : 'unfavoritingWorkshop',
  6357. text: id
  6358. });
  6359. const {
  6360. result,
  6361. statusText,
  6362. status,
  6363. data
  6364. } = await tools_httpRequest({
  6365. url: `https://steamcommunity.com/sharedfiles/${doTask ? '' : 'un'}favorite`,
  6366. method: 'POST',
  6367. headers: {
  6368. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6369. },
  6370. data: $.param({
  6371. id: id,
  6372. appid: appid,
  6373. sessionid: this.#auth.communitySessionID
  6374. })
  6375. });
  6376. if (result === 'Success') {
  6377. if (data?.status === 200 && !data.responseText) {
  6378. if (doTask) {
  6379. this.tasks.workshops = unique([ ...this.tasks.workshops, id ]);
  6380. }
  6381. logStatus.success();
  6382. return true;
  6383. }
  6384. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6385. return false;
  6386. }
  6387. logStatus.error(`${result}:${statusText}(${status})`);
  6388. return false;
  6389. } catch (error) {
  6390. throwError(error, 'Steam.toggleFavoriteWorkshop');
  6391. return false;
  6392. }
  6393. }
  6394. async #getWorkshopAppId(id) {
  6395. try {
  6396. const logStatus = scripts_echoLog({
  6397. type: 'gettingWorkshopAppId',
  6398. text: id
  6399. });
  6400. const appId = this.#cache.workshop[id];
  6401. if (appId) {
  6402. logStatus.success();
  6403. return appId;
  6404. }
  6405. const {
  6406. result,
  6407. statusText,
  6408. status,
  6409. data
  6410. } = await tools_httpRequest({
  6411. url: `https://steamcommunity.com/sharedfiles/filedetails/?id=${id}`,
  6412. method: 'GET'
  6413. });
  6414. if (result === 'Success') {
  6415. if (data?.status === 200) {
  6416. const appId = data.responseText.match(/<input type="hidden" name="appid" value="([\d]+?)" \/>/)?.[1];
  6417. if (appId) {
  6418. this.#setCache('workshop', id, appId);
  6419. logStatus.success();
  6420. return appId;
  6421. }
  6422. logStatus.error('Error: getWorkshopAppId failed');
  6423. return false;
  6424. }
  6425. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6426. return false;
  6427. }
  6428. logStatus.error(`${result}:${statusText}(${status})`);
  6429. return false;
  6430. } catch (error) {
  6431. throwError(error, 'Steam.getWorkshopAppId');
  6432. return false;
  6433. }
  6434. }
  6435. async #voteUpWorkshop(id) {
  6436. try {
  6437. const logStatus = scripts_echoLog({
  6438. type: 'votingUpWorkshop',
  6439. text: id
  6440. });
  6441. const {
  6442. result,
  6443. statusText,
  6444. status,
  6445. data
  6446. } = await tools_httpRequest({
  6447. url: 'https://steamcommunity.com/sharedfiles/voteup',
  6448. method: 'POST',
  6449. responseType: 'json',
  6450. headers: {
  6451. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6452. },
  6453. data: $.param({
  6454. id: id,
  6455. sessionid: this.#auth.communitySessionID
  6456. })
  6457. });
  6458. if (result === 'Success') {
  6459. if (data?.status === 200 && data.response?.success === 1) {
  6460. logStatus.success();
  6461. return true;
  6462. }
  6463. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6464. return true;
  6465. }
  6466. logStatus.error(`${result}:${statusText}(${status})`);
  6467. return true;
  6468. } catch (error) {
  6469. throwError(error, 'Steam.voteupWorkshop');
  6470. return true;
  6471. }
  6472. }
  6473. async #toggleCurator(curatorId, doTask = true) {
  6474. try {
  6475. if (!doTask && this.whiteList.curators.includes(curatorId)) {
  6476. scripts_echoLog({
  6477. type: 'whiteList',
  6478. text: 'Steam.unfollowCurator',
  6479. id: curatorId
  6480. });
  6481. return true;
  6482. }
  6483. if (this.#ASF) {
  6484. return await this.#ASF.toggleCurator(curatorId, doTask);
  6485. }
  6486. const logStatus = scripts_echoLog({
  6487. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  6488. text: curatorId
  6489. });
  6490. const {
  6491. result,
  6492. statusText,
  6493. status,
  6494. data
  6495. } = await tools_httpRequest({
  6496. url: 'https://store.steampowered.com/curators/ajaxfollow',
  6497. method: 'POST',
  6498. headers: {
  6499. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6500. },
  6501. data: $.param({
  6502. clanid: curatorId,
  6503. sessionid: this.#auth.storeSessionID,
  6504. follow: doTask
  6505. }),
  6506. dataType: 'json'
  6507. });
  6508. if (result === 'Success') {
  6509. if (data?.status === 200 && data.response?.success?.success === 1) {
  6510. logStatus.success();
  6511. return true;
  6512. }
  6513. logStatus.error(`Error:${data?.statusText}(${data?.response?.success}` || `${data?.status})`);
  6514. return false;
  6515. }
  6516. logStatus.error(`${result}:${statusText}(${status})`);
  6517. return false;
  6518. } catch (error) {
  6519. throwError(error, 'Steam.toggleCurator');
  6520. return false;
  6521. }
  6522. }
  6523. async getCuratorId(path, name) {
  6524. try {
  6525. const logStatus = scripts_echoLog({
  6526. type: 'gettingCuratorId',
  6527. text: `${path}/${name}`
  6528. });
  6529. const curatorId = this.#cache.curator[`${path}/${name}`];
  6530. if (curatorId) {
  6531. logStatus.success();
  6532. return curatorId;
  6533. }
  6534. const {
  6535. result,
  6536. statusText,
  6537. status,
  6538. data
  6539. } = await tools_httpRequest({
  6540. url: `https://store.steampowered.com/${path}/${name}`,
  6541. method: 'GET',
  6542. headers: {
  6543. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6544. }
  6545. });
  6546. if (result === 'Success') {
  6547. if (data?.status === 200) {
  6548. const curatorId = data.responseText.match(/g_pagingData.*?"clanid":([\d]+)/)?.[1];
  6549. if (curatorId) {
  6550. this.#setCache('curator', `${path}/${name}`, curatorId);
  6551. logStatus.success();
  6552. return curatorId;
  6553. }
  6554. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6555. return false;
  6556. }
  6557. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6558. return false;
  6559. }
  6560. logStatus.error(`${result}:${statusText}(${status})`);
  6561. return false;
  6562. } catch (error) {
  6563. throwError(error, 'Steam.getCuratorID');
  6564. return false;
  6565. }
  6566. }
  6567. async #toggleCuratorLike(link, doTask = true) {
  6568. try {
  6569. const [ path, name ] = link.split('/');
  6570. if (!(path && name)) {
  6571. scripts_echoLog({
  6572. text: i18n('errorLink', link)
  6573. });
  6574. return false;
  6575. }
  6576. const curatorId = await this.getCuratorId(path, name);
  6577. if (curatorId) {
  6578. return await this.#toggleCurator(curatorId, doTask);
  6579. }
  6580. return false;
  6581. } catch (error) {
  6582. throwError(error, 'Steam.toggleCuratorLike');
  6583. return false;
  6584. }
  6585. }
  6586. async #getAnnouncementParams(appId, viewId) {
  6587. try {
  6588. const logStatus = scripts_echoLog({
  6589. type: 'gettingAnnouncementParams',
  6590. text: appId,
  6591. id: viewId
  6592. });
  6593. const {
  6594. result,
  6595. statusText,
  6596. status,
  6597. data
  6598. } = await tools_httpRequest({
  6599. 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`,
  6600. method: 'GET',
  6601. responseType: 'json',
  6602. headers: {
  6603. Host: 'store.steampowered.com',
  6604. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6605. }
  6606. });
  6607. if (result === 'Success') {
  6608. if (data?.status === 200 && data?.response?.success === 1) {
  6609. const {
  6610. clanid,
  6611. gid
  6612. } = data.response.event?.announcement_body || {};
  6613. if (clanid) {
  6614. logStatus.success();
  6615. return {
  6616. clanId: clanid,
  6617. gid: gid
  6618. };
  6619. }
  6620. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6621. return {};
  6622. }
  6623. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6624. return {};
  6625. }
  6626. logStatus.error(`${result}:${statusText}(${status})`);
  6627. return {};
  6628. } catch (error) {
  6629. throwError(error, 'Steam.likeAnnouncement');
  6630. return {};
  6631. }
  6632. }
  6633. async #likeAnnouncement(id) {
  6634. try {
  6635. const [ appId, viewId ] = id.split('/');
  6636. if (!(appId && viewId)) {
  6637. scripts_echoLog({}).error(`${i18n('missParams')}(id)`);
  6638. return false;
  6639. }
  6640. const {
  6641. clanId,
  6642. gid
  6643. } = await this.#getAnnouncementParams(appId, viewId);
  6644. if (!clanId) {
  6645. return false;
  6646. }
  6647. const logStatus = scripts_echoLog({
  6648. type: 'likingAnnouncement',
  6649. text: appId,
  6650. id: viewId
  6651. });
  6652. const {
  6653. result,
  6654. statusText,
  6655. status,
  6656. data
  6657. } = await tools_httpRequest({
  6658. url: `https://store.steampowered.com/updated/ajaxrateupdate/${gid || viewId}`,
  6659. method: 'POST',
  6660. headers: {
  6661. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6662. Host: 'store.steampowered.com',
  6663. Origin: 'https://store.steampowered.com',
  6664. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6665. },
  6666. data: $.param({
  6667. sessionid: this.#auth.storeSessionID,
  6668. voteup: 1,
  6669. clanid: clanId,
  6670. ajax: 1
  6671. }),
  6672. dataType: 'json'
  6673. });
  6674. if (result === 'Success') {
  6675. if (data?.status === 200 && data.response.success === 1) {
  6676. logStatus.success();
  6677. return true;
  6678. }
  6679. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6680. return false;
  6681. }
  6682. logStatus.error(`${result}:${statusText}(${status})`);
  6683. return false;
  6684. } catch (error) {
  6685. throwError(error, 'Steam.likeAnnouncement');
  6686. return false;
  6687. }
  6688. }
  6689. async #appid2subid(id) {
  6690. try {
  6691. const logStatus = scripts_echoLog({
  6692. type: 'gettingSubid',
  6693. text: id
  6694. });
  6695. const {
  6696. result,
  6697. statusText,
  6698. status,
  6699. data
  6700. } = await tools_httpRequest({
  6701. url: `https://store.steampowered.com/app/${id}`,
  6702. method: 'GET',
  6703. headers: {
  6704. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6705. }
  6706. });
  6707. if (result === 'Success') {
  6708. if (data?.status === 200) {
  6709. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6710. logStatus.success(i18n('owned'));
  6711. return false;
  6712. }
  6713. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6714. logStatus.warning(i18n('changeAreaNotice'));
  6715. const result = await this.#changeArea();
  6716. if (!result || result === 'CN' || result === 'skip') {
  6717. return false;
  6718. }
  6719. return await this.#appid2subid(id);
  6720. }
  6721. let subid = data.responseText.match(/name="subid" value="([\d]+?)"/)?.[1];
  6722. if (subid) {
  6723. logStatus.success();
  6724. return subid;
  6725. }
  6726. subid = data.responseText.match(/AddFreeLicense\(\s*(\d+)/)?.[1];
  6727. if (subid) {
  6728. logStatus.success();
  6729. return subid;
  6730. }
  6731. logStatus.error(`Error:${i18n('noSubid')}`);
  6732. return false;
  6733. }
  6734. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6735. return false;
  6736. }
  6737. logStatus.error(`${result}:${statusText}(${status})`);
  6738. return false;
  6739. } catch (error) {
  6740. throwError(error, 'Steam.appid2subid');
  6741. return false;
  6742. }
  6743. }
  6744. async #getLicenses() {
  6745. try {
  6746. const logStatus = scripts_echoLog({
  6747. text: i18n('gettingLicenses')
  6748. });
  6749. const {
  6750. result,
  6751. statusText,
  6752. status,
  6753. data
  6754. } = await tools_httpRequest({
  6755. url: `https://store.steampowered.com/dynamicstore/userdata/?t=${new Date().getTime()}`,
  6756. method: 'GET',
  6757. responseType: 'json'
  6758. });
  6759. if (result === 'Success') {
  6760. if (data?.status === 200) {
  6761. logStatus.success();
  6762. return data.response?.rgOwnedPackages;
  6763. }
  6764. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6765. return false;
  6766. }
  6767. logStatus.error(`${result}:${statusText}(${status})`);
  6768. return false;
  6769. } catch (error) {
  6770. throwError(error, 'Steam.getLicenses');
  6771. return false;
  6772. }
  6773. }
  6774. async #addLicense(id) {
  6775. try {
  6776. if (this.#ASF) {
  6777. return await this.#ASF.addLicense(id);
  6778. }
  6779. const [ type, ids ] = id.split('-');
  6780. if (type === 'appid') {
  6781. const subid = await this.#appid2subid(ids);
  6782. if (!subid) {
  6783. return false;
  6784. }
  6785. const logStatus = scripts_echoLog({
  6786. type: 'addingFreeLicense',
  6787. text: ids
  6788. });
  6789. if (!await this.#addFreeLicense(subid, logStatus)) {
  6790. return false;
  6791. }
  6792. const {
  6793. result,
  6794. statusText,
  6795. status,
  6796. data
  6797. } = await tools_httpRequest({
  6798. url: `https://store.steampowered.com/app/${ids}`,
  6799. method: 'GET'
  6800. });
  6801. if (result === 'Success') {
  6802. if (data?.status === 200) {
  6803. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6804. logStatus.success();
  6805. return true;
  6806. }
  6807. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6808. return false;
  6809. }
  6810. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6811. return false;
  6812. }
  6813. logStatus.error(`${result}:${statusText}(${status})`);
  6814. return false;
  6815. } else if (type === 'subid') {
  6816. if (this.#area === 'CN') {
  6817. scripts_echoLog({}).success(i18n('tryChangeAreaNotice'));
  6818. await this.#changeArea();
  6819. }
  6820. const logStatusArr = {};
  6821. const idsArr = ids.split(',');
  6822. for (const subid of idsArr) {
  6823. const logStatus = scripts_echoLog({
  6824. type: 'addingFreeLicenseSubid',
  6825. text: subid
  6826. });
  6827. if (!await this.#addFreeLicense(subid, logStatus)) {
  6828. return false;
  6829. }
  6830. logStatusArr[subid] = logStatus;
  6831. }
  6832. const licenses = await this.#getLicenses();
  6833. if (!licenses) {
  6834. return false;
  6835. }
  6836. for (const subid of idsArr) {
  6837. if (licenses.includes(parseInt(subid, 10))) {
  6838. logStatusArr[subid].success();
  6839. } else {
  6840. logStatusArr[subid].error();
  6841. }
  6842. }
  6843. return true;
  6844. }
  6845. return false;
  6846. } catch (error) {
  6847. throwError(error, 'Steam.addLicense');
  6848. return false;
  6849. }
  6850. }
  6851. async #addFreeLicense(id, logStatusPre) {
  6852. try {
  6853. const logStatus = logStatusPre || scripts_echoLog({
  6854. type: 'addingFreeLicenseSubid',
  6855. text: id
  6856. });
  6857. const {
  6858. result,
  6859. statusText,
  6860. status,
  6861. data
  6862. } = await tools_httpRequest({
  6863. url: `https://store.steampowered.com/freelicense/addfreelicense/${id}`,
  6864. method: 'POST',
  6865. headers: {
  6866. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6867. Host: 'store.steampowered.com',
  6868. Origin: 'https://store.steampowered.com',
  6869. Referer: 'https://store.steampowered.com/account/licenses/'
  6870. },
  6871. data: $.param({
  6872. ajax: true,
  6873. sessionid: this.#auth.storeSessionID
  6874. }),
  6875. dataType: 'json'
  6876. });
  6877. if (result === 'Success') {
  6878. if (data?.status === 200) {
  6879. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6880. logStatus.warning(i18n('changeAreaNotice'));
  6881. const result = await this.#changeArea();
  6882. if (!result || [ 'CN', 'skip' ].includes(result)) {
  6883. return false;
  6884. }
  6885. return await this.#addFreeLicense(id);
  6886. }
  6887. logStatus.success();
  6888. return true;
  6889. }
  6890. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6891. return false;
  6892. }
  6893. logStatus.error(`${result}:${statusText}(${status})`);
  6894. return false;
  6895. } catch (error) {
  6896. throwError(error, 'Steam.addFreeLicense');
  6897. return false;
  6898. }
  6899. }
  6900. async #requestPlayTestAccess(id) {
  6901. try {
  6902. if (this.#ASF) {
  6903. return await this.#ASF.requestPlayTestAccess(id);
  6904. }
  6905. const logStatus = scripts_echoLog({
  6906. type: 'requestingPlayTestAccess',
  6907. text: id
  6908. });
  6909. const {
  6910. result,
  6911. statusText,
  6912. status,
  6913. data
  6914. } = await tools_httpRequest({
  6915. url: `https://store.steampowered.com/ajaxrequestplaytestaccess/${id}`,
  6916. method: 'POST',
  6917. headers: {
  6918. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6919. Host: 'store.steampowered.com',
  6920. Origin: 'https://store.steampowered.com',
  6921. Referer: `https://store.steampowered.com/app/${id}`
  6922. },
  6923. data: $.param({
  6924. sessionid: this.#auth.storeSessionID
  6925. }),
  6926. dataType: 'json'
  6927. });
  6928. if (result === 'Success') {
  6929. if (data?.status === 200 && data?.response?.success === 1) {
  6930. logStatus.success();
  6931. return true;
  6932. }
  6933. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6934. return false;
  6935. }
  6936. logStatus.error(`${result}:${statusText}(${status})`);
  6937. return false;
  6938. } catch (error) {
  6939. throwError(error, 'Steam.requestPlayTestAccess');
  6940. return false;
  6941. }
  6942. }
  6943. async toggle({
  6944. doTask = true,
  6945. groupLinks = [],
  6946. officialGroupLinks = [],
  6947. wishlistLinks = [],
  6948. followLinks = [],
  6949. forumLinks = [],
  6950. workshopLinks = [],
  6951. workshopVoteLinks = [],
  6952. curatorLinks = [],
  6953. curatorLikeLinks = [],
  6954. announcementLinks = [],
  6955. licenseLinks = [],
  6956. playtestLinks = []
  6957. }) {
  6958. try {
  6959. if ([ ...groupLinks, ...officialGroupLinks, ...forumLinks, ...workshopLinks, ...workshopVoteLinks ].length > 0 && !this.#communityInitialized) {
  6960. scripts_echoLog({
  6961. text: i18n('needInit')
  6962. });
  6963. return false;
  6964. }
  6965. if ([ ...wishlistLinks, ...followLinks, ...curatorLinks, ...curatorLikeLinks, ...announcementLinks, ...licenseLinks, ...playtestLinks ].length > 0 && !this.#storeInitialized) {
  6966. scripts_echoLog({
  6967. text: i18n('needInit')
  6968. });
  6969. return false;
  6970. }
  6971. const prom = [];
  6972. if (doTask && !globalOptions.doTask.steam.groups || !doTask && !globalOptions.undoTask.steam.groups) {
  6973. scripts_echoLog({
  6974. type: 'globalOptionsSkip',
  6975. text: 'steam.groups'
  6976. });
  6977. } else {
  6978. const realGroups = this.getRealParams('groups', groupLinks, doTask, link => link.match(/groups\/(.+)\/?/)?.[1]);
  6979. if (realGroups.length > 0) {
  6980. for (const group of realGroups) {
  6981. if (doTask) {
  6982. prom.push(this.#joinGroup(group));
  6983. } else {
  6984. prom.push(this.#leaveGroup(group));
  6985. }
  6986. await delay(1e3);
  6987. }
  6988. }
  6989. }
  6990. if (doTask && !globalOptions.doTask.steam.officialGroups || !doTask && !globalOptions.undoTask.steam.officialGroups) {
  6991. scripts_echoLog({
  6992. type: 'globalOptionsSkip',
  6993. text: 'steam.officialGroups'
  6994. });
  6995. } else {
  6996. const realOfficialGroups = this.getRealParams('officialGroups', officialGroupLinks, doTask, link => link.match(/games\/(.+)\/?/)?.[1]);
  6997. if (realOfficialGroups.length > 0) {
  6998. for (const officialGroup of realOfficialGroups) {
  6999. if (doTask) {
  7000. prom.push(this.#joinOfficialGroup(officialGroup));
  7001. } else {
  7002. prom.push(this.#leaveOfficialGroup(officialGroup));
  7003. }
  7004. await delay(1e3);
  7005. }
  7006. }
  7007. }
  7008. if (doTask && !globalOptions.doTask.steam.wishlists || !doTask && !globalOptions.undoTask.steam.wishlists) {
  7009. scripts_echoLog({
  7010. type: 'globalOptionsSkip',
  7011. text: 'steam.wishlists'
  7012. });
  7013. } else {
  7014. const realWishlists = this.getRealParams('wishlists', wishlistLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  7015. if (realWishlists.length > 0) {
  7016. for (const game of realWishlists) {
  7017. if (doTask) {
  7018. prom.push(this.#addToWishlist(game));
  7019. } else {
  7020. prom.push(this.#removeFromWishlist(game));
  7021. }
  7022. await delay(1e3);
  7023. }
  7024. }
  7025. }
  7026. if (doTask && !globalOptions.doTask.steam.follows || !doTask && !globalOptions.undoTask.steam.follows) {
  7027. scripts_echoLog({
  7028. type: 'globalOptionsSkip',
  7029. text: 'steam.follows'
  7030. });
  7031. } else {
  7032. const realFollows = this.getRealParams('follows', followLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  7033. if (realFollows.length > 0) {
  7034. for (const game of realFollows) {
  7035. prom.push(this.#toggleFollowGame(game, doTask));
  7036. await delay(1e3);
  7037. }
  7038. }
  7039. }
  7040. if (doTask && !globalOptions.doTask.steam.forums || !doTask && !globalOptions.undoTask.steam.forums) {
  7041. scripts_echoLog({
  7042. type: 'globalOptionsSkip',
  7043. text: 'steam.forums'
  7044. });
  7045. } else {
  7046. const realForums = this.getRealParams('forums', forumLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  7047. if (realForums.length > 0) {
  7048. for (const forum of realForums) {
  7049. prom.push(this.#toggleForum(forum, doTask));
  7050. await delay(1e3);
  7051. }
  7052. }
  7053. }
  7054. if (doTask && !globalOptions.doTask.steam.workshops || !doTask && !globalOptions.undoTask.steam.workshops) {
  7055. scripts_echoLog({
  7056. type: 'globalOptionsSkip',
  7057. text: 'steam.workshops'
  7058. });
  7059. } else {
  7060. const realWorkshops = this.getRealParams('workshops', workshopLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  7061. if (realWorkshops.length > 0) {
  7062. for (const workshop of realWorkshops) {
  7063. prom.push(this.#toggleFavoriteWorkshop(workshop, doTask));
  7064. await delay(1e3);
  7065. }
  7066. }
  7067. }
  7068. if (doTask && !globalOptions.doTask.steam.workshopVotes) {
  7069. scripts_echoLog({
  7070. type: 'globalOptionsSkip',
  7071. text: 'steam.workshopVotes'
  7072. });
  7073. } else {
  7074. const realworkshopVotes = this.getRealParams('workshopVotes', workshopVoteLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  7075. if (doTask && realworkshopVotes.length > 0) {
  7076. for (const workshop of realworkshopVotes) {
  7077. prom.push(this.#voteUpWorkshop(workshop));
  7078. await delay(1e3);
  7079. }
  7080. }
  7081. }
  7082. if (doTask && !globalOptions.doTask.steam.curators || !doTask && !globalOptions.undoTask.steam.curators) {
  7083. scripts_echoLog({
  7084. type: 'globalOptionsSkip',
  7085. text: 'steam.curators'
  7086. });
  7087. } else {
  7088. const realCurators = this.getRealParams('curators', curatorLinks, doTask, link => link.match(/curator\/([\d]+)/)?.[1]);
  7089. const realCuratorLikes = this.getRealParams('curatorLikes', curatorLikeLinks, doTask, link => link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3).join('/'));
  7090. if (realCurators.length > 0) {
  7091. for (const curator of realCurators) {
  7092. prom.push(this.#toggleCurator(curator, doTask));
  7093. await delay(1e3);
  7094. }
  7095. }
  7096. if (realCuratorLikes.length > 0) {
  7097. for (const curatorLike of realCuratorLikes) {
  7098. prom.push(this.#toggleCuratorLike(curatorLike, doTask));
  7099. await delay(1e3);
  7100. }
  7101. }
  7102. }
  7103. if (doTask && !globalOptions.doTask.steam.announcements) {
  7104. scripts_echoLog({
  7105. type: 'globalOptionsSkip',
  7106. text: 'steam.announcements'
  7107. });
  7108. } else {
  7109. const realAnnouncements = this.getRealParams('announcements', announcementLinks, doTask, link => {
  7110. if (link.includes('store.steampowered.com')) {
  7111. return link.match(/store\.steampowered\.com\/news\/app\/([\d]+)\/view\/([\d]+)/)?.slice(1, 3).join('/');
  7112. }
  7113. return link.match(/steamcommunity\.com\/games\/([\d]+)\/announcements\/detail\/([\d]+)/)?.slice(1, 3).join('/');
  7114. });
  7115. if (doTask && realAnnouncements.length > 0) {
  7116. for (const id of realAnnouncements) {
  7117. prom.push(this.#likeAnnouncement(id));
  7118. await delay(1e3);
  7119. }
  7120. }
  7121. }
  7122. if (doTask && !globalOptions.doTask.steam.licenses) {
  7123. scripts_echoLog({
  7124. type: 'globalOptionsSkip',
  7125. text: 'steam.licenses'
  7126. });
  7127. } else if (doTask && globalOptions.doTask.steam.licenses && licenseLinks.length > 0) {
  7128. for (const ids of licenseLinks) {
  7129. const [ type, idsStr ] = ids.split('-');
  7130. const idsArr = idsStr.split(',');
  7131. for (const id of idsArr) {
  7132. prom.push(this.#addLicense(`${type}-${id}`));
  7133. await delay(1e3);
  7134. }
  7135. }
  7136. }
  7137. if (doTask && !globalOptions.doTask.steam.playtests) {
  7138. scripts_echoLog({
  7139. type: 'globalOptionsSkip',
  7140. text: 'steam.playtests'
  7141. });
  7142. } else {
  7143. const realPlaytests = this.getRealParams('playtests', playtestLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  7144. if (doTask && globalOptions.doTask.steam.playtests && realPlaytests.length > 0) {
  7145. for (const id of realPlaytests) {
  7146. prom.push(this.#requestPlayTestAccess(id));
  7147. await delay(1e3);
  7148. }
  7149. }
  7150. }
  7151. return Promise.all(prom).then(async () => {
  7152. if (this.#oldArea && this.#area !== this.#oldArea) {
  7153. scripts_echoLog({}).warning(i18n('steamFinishNotice') + this.#oldArea);
  7154. await this.#changeArea(this.#oldArea);
  7155. }
  7156. return true;
  7157. });
  7158. } catch (error) {
  7159. throwError(error, 'Steam.toggle');
  7160. return false;
  7161. }
  7162. }
  7163. #setCache(type, name, id) {
  7164. try {
  7165. this.#cache[type][name] = id;
  7166. GM_setValue('steamCache', this.#cache);
  7167. } catch (error) {
  7168. throwError(error, 'Steam.setCache');
  7169. }
  7170. }
  7171. }
  7172. const social_Steam = Steam;
  7173. class Website {
  7174. undoneTasks;
  7175. socialTasks;
  7176. giveawayId;
  7177. socialInitialized = {
  7178. discord: false,
  7179. instagram: false,
  7180. reddit: false,
  7181. twitch: false,
  7182. twitter: false,
  7183. vk: false,
  7184. youtube: false,
  7185. steamStore: false,
  7186. steamCommunity: false
  7187. };
  7188. initialized = false;
  7189. steamTaskType = {
  7190. steamStore: false,
  7191. steamCommunity: false
  7192. };
  7193. social = {};
  7194. async #bind(name, init) {
  7195. try {
  7196. return {
  7197. name: name,
  7198. result: await init
  7199. };
  7200. } catch (error) {
  7201. throwError(error, 'Website.bind');
  7202. return {
  7203. name: name,
  7204. result: false
  7205. };
  7206. }
  7207. }
  7208. async initSocial(action) {
  7209. try {
  7210. const pro = [];
  7211. const tasks = action === 'do' ? this.undoneTasks : this.socialTasks;
  7212. if (tasks.discord) {
  7213. const hasDiscord = Object.values(tasks.discord).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7214. if (hasDiscord && (!this.socialInitialized.discord || !this.social.discord)) {
  7215. this.social.discord = new social_Discord();
  7216. pro.push(this.#bind('discord', this.social.discord.init(action)));
  7217. }
  7218. }
  7219. if (tasks.instagram) {
  7220. const hasInstagram = Object.values(tasks.instagram).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7221. if (hasInstagram && (!this.socialInitialized.instagram || !this.social.instagram)) {
  7222. this.social.instagram = new social_Instagram();
  7223. pro.push(this.#bind('instagram', this.social.instagram.init()));
  7224. }
  7225. }
  7226. if (tasks.reddit) {
  7227. const hasReddit = Object.values(tasks.reddit).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7228. if (hasReddit && (!this.socialInitialized.reddit || !this.social.reddit)) {
  7229. this.social.reddit = new social_Reddit();
  7230. pro.push(this.#bind('reddit', this.social.reddit.init()));
  7231. }
  7232. }
  7233. if (tasks.twitch) {
  7234. const hasTwitch = Object.values(tasks.twitch).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7235. if (hasTwitch && (!this.socialInitialized.twitch || !this.social.twitch)) {
  7236. this.social.twitch = new social_Twitch();
  7237. pro.push(this.#bind('twitch', this.social.twitch.init()));
  7238. }
  7239. }
  7240. if (tasks.twitter) {
  7241. const hasTwitter = Object.values(tasks.twitter).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7242. if (hasTwitter && (!this.socialInitialized.twitter || !this.social.twitter)) {
  7243. this.social.twitter = new social_Twitter();
  7244. pro.push(this.#bind('twitter', this.social.twitter.init()));
  7245. }
  7246. }
  7247. if (tasks.vk) {
  7248. const hasVk = Object.values(tasks.vk).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7249. if (hasVk && (!this.socialInitialized.vk || !this.social.vk)) {
  7250. this.social.vk = new social_Vk();
  7251. pro.push(this.#bind('vk', this.social.vk.init()));
  7252. }
  7253. }
  7254. if (tasks.youtube) {
  7255. const hasYoutube = Object.values(tasks.youtube).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7256. if (hasYoutube && (!this.socialInitialized.youtube || !this.social.youtube)) {
  7257. this.social.youtube = new Youtube();
  7258. pro.push(this.#bind('youtube', this.social.youtube.init()));
  7259. }
  7260. }
  7261. if (tasks.steam) {
  7262. const steamLength = Object.values(tasks.steam).reduce((total, arr) => [ ...total, ...arr ]).length;
  7263. if (steamLength > 0) {
  7264. if (!this.social.steam) {
  7265. this.social.steam = new social_Steam();
  7266. }
  7267. 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);
  7268. if (steamLength - steamCommunityLength > 0) {
  7269. this.steamTaskType.steamStore = true;
  7270. if (!this.socialInitialized.steamStore) {
  7271. pro.push(this.#bind('steamStore', this.social.steam.init('store')));
  7272. }
  7273. }
  7274. if (steamCommunityLength > 0) {
  7275. if (!this.socialInitialized.steamCommunity) {
  7276. this.steamTaskType.steamCommunity = true;
  7277. pro.push(this.#bind('steamCommunity', this.social.steam.init('community')));
  7278. }
  7279. }
  7280. }
  7281. }
  7282. if (tasks.links && tasks.links.length > 0) {
  7283. this.social.visitLink = visitLink;
  7284. }
  7285. return await Promise.all(pro).then(result => {
  7286. let checked = true;
  7287. for (const data of result) {
  7288. if (data.result) {
  7289. this.socialInitialized[data.name] = data.result;
  7290. } else {
  7291. checked = false;
  7292. }
  7293. }
  7294. return checked;
  7295. });
  7296. } catch (error) {
  7297. throwError(error, 'Website.initSocial');
  7298. return false;
  7299. }
  7300. }
  7301. uniqueTasks(allTasks) {
  7302. try {
  7303. const result = {};
  7304. for (const [ social, types ] of Object.entries(allTasks)) {
  7305. result[social] = {};
  7306. for (const [ type, tasks ] of Object.entries(types)) {
  7307. result[social][type] = unique(tasks);
  7308. }
  7309. }
  7310. return result;
  7311. } catch (error) {
  7312. throwError(error, 'Website.uniqueTasks');
  7313. return allTasks;
  7314. }
  7315. }
  7316. async toggleTask(action) {
  7317. try {
  7318. if (!this.initialized && !this.init()) {
  7319. return false;
  7320. }
  7321. if (!await this.classifyTask(action)) {
  7322. return false;
  7323. }
  7324. await this.initSocial(action);
  7325. const pro = [];
  7326. const doTask = action === 'do';
  7327. const tasks = doTask ? this.undoneTasks : this.socialTasks;
  7328. if (this.socialInitialized.discord === true && this.social.discord) {
  7329. pro.push(this.social.discord.toggle({
  7330. doTask: doTask,
  7331. ...tasks.discord
  7332. }));
  7333. }
  7334. if (this.socialInitialized.instagram === true && this.social.instagram) {
  7335. pro.push(this.social.instagram.toggle({
  7336. doTask: doTask,
  7337. ...tasks.instagram
  7338. }));
  7339. }
  7340. if (this.socialInitialized.reddit === true && this.social.reddit) {
  7341. pro.push(this.social.reddit.toggle({
  7342. doTask: doTask,
  7343. ...tasks.reddit
  7344. }));
  7345. }
  7346. if (this.socialInitialized.twitch === true && this.social.twitch) {
  7347. pro.push(this.social.twitch.toggle({
  7348. doTask: doTask,
  7349. ...tasks.twitch
  7350. }));
  7351. }
  7352. if (this.socialInitialized.twitter === true && this.social.twitter) {
  7353. pro.push(this.social.twitter.toggle({
  7354. doTask: doTask,
  7355. ...tasks.twitter
  7356. }));
  7357. }
  7358. if (this.socialInitialized.vk === true && this.social.vk) {
  7359. pro.push(this.social.vk.toggle({
  7360. doTask: doTask,
  7361. ...tasks.vk
  7362. }));
  7363. }
  7364. if (this.socialInitialized.youtube === true && this.social.youtube) {
  7365. pro.push(this.social.youtube.toggle({
  7366. doTask: doTask,
  7367. ...tasks.youtube
  7368. }));
  7369. }
  7370. if ((this.steamTaskType.steamCommunity ? this.socialInitialized.steamCommunity === true : true) && (this.steamTaskType.steamStore ? this.socialInitialized.steamStore === true : true) && this.social.steam) {
  7371. pro.push(this.social.steam.toggle({
  7372. doTask: doTask,
  7373. ...tasks.steam
  7374. }));
  7375. }
  7376. if (this.social.visitLink && tasks.links && doTask) {
  7377. for (const link of tasks.links) {
  7378. pro.push(this.social.visitLink(link));
  7379. }
  7380. }
  7381. if (doTask && tasks.extra && this.extraDoTask) {
  7382. const hasExtra = Object.values(tasks.extra).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7383. if (hasExtra) {
  7384. pro.push(this.extraDoTask(tasks.extra));
  7385. }
  7386. }
  7387. await Promise.all(pro);
  7388. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7389. return true;
  7390. } catch (error) {
  7391. throwError(error, 'Website.toggleTask');
  7392. return false;
  7393. }
  7394. }
  7395. async doTask() {
  7396. try {
  7397. return await this.toggleTask('do');
  7398. } catch (error) {
  7399. throwError(error, 'Website.doTask');
  7400. return false;
  7401. }
  7402. }
  7403. async undoTask() {
  7404. try {
  7405. return await this.toggleTask('undo');
  7406. } catch (error) {
  7407. throwError(error, 'Website.undoTask');
  7408. return false;
  7409. }
  7410. }
  7411. }
  7412. const website_Website = Website;
  7413. const defaultTasksTemplate = {
  7414. steam: {
  7415. groupLinks: [],
  7416. wishlistLinks: [],
  7417. curatorLinks: [],
  7418. followLinks: []
  7419. },
  7420. discord: {
  7421. serverLinks: []
  7422. },
  7423. vk: {
  7424. nameLinks: []
  7425. },
  7426. extra: {
  7427. website: []
  7428. }
  7429. };
  7430. const defaultTasks = JSON.stringify(defaultTasksTemplate);
  7431. class FreeAnyWhere extends website_Website {
  7432. name = 'FreeAnyWhere';
  7433. tasks = [];
  7434. socialTasks = JSON.parse(defaultTasks);
  7435. undoneTasks = JSON.parse(defaultTasks);
  7436. buttons = [ 'doTask', 'undoTask', 'verifyTask', 'getKey' ];
  7437. static test() {
  7438. return window.location.host === 'freeanywhere.net';
  7439. }
  7440. async init() {
  7441. try {
  7442. const logStatus = scripts_echoLog({
  7443. text: i18n('initing')
  7444. });
  7445. debug('检测登录按钮');
  7446. if ($('div.header__login a[href*=logout]').length === 0) {
  7447. window.open('https://freeanywhere.net/game.php?steam_login', '_self');
  7448. logStatus.warning(i18n('needLogin'));
  7449. return false;
  7450. }
  7451. debug('检测是否为登录页面');
  7452. if (window.location.href.includes('/login')) {
  7453. logStatus.warning(i18n('needLogin'));
  7454. return false;
  7455. }
  7456. this.initialized = true;
  7457. logStatus.success();
  7458. return true;
  7459. } catch (error) {
  7460. throwError(error, 'Freeanywhere.init');
  7461. return false;
  7462. }
  7463. }
  7464. async classifyTask(action) {
  7465. try {
  7466. const logStatus = scripts_echoLog({
  7467. text: i18n('getTasksInfo')
  7468. });
  7469. if (action === 'undo') {
  7470. this.socialTasks = GM_getValue(`fawTasks-${this.giveawayId}`)?.tasks || JSON.parse(defaultTasks);
  7471. }
  7472. const tasks = $('div.game__content-tasks__task').map((index, element) => ({
  7473. id: $(element).attr('data-id'),
  7474. social: $(element).find('div.task-img img').attr('alt'),
  7475. link: $(element).find('div.task-link a').attr('href'),
  7476. title: $(element).find('div.task-link').text().trim(),
  7477. type: $(element).attr('data-type'),
  7478. isSuccess: $(element).hasClass('done')
  7479. })).toArray();
  7480. if (tasks.length === 0) {
  7481. logStatus.success();
  7482. return false;
  7483. }
  7484. if (action === 'verify') {
  7485. this.tasks = [];
  7486. }
  7487. for (const task of tasks) {
  7488. debug('任务分类', task);
  7489. const {
  7490. id,
  7491. social,
  7492. title,
  7493. type,
  7494. link,
  7495. isSuccess
  7496. } = task;
  7497. const taskInfo = {
  7498. id: id,
  7499. title: title,
  7500. social: social,
  7501. type: type
  7502. };
  7503. if (action === 'verify' && !isSuccess) {
  7504. this.tasks.push(taskInfo);
  7505. continue;
  7506. }
  7507. switch (type) {
  7508. case 'steam_account_verify':
  7509. break;
  7510.  
  7511. case 'steam_game_wishlist':
  7512. if (action === 'undo' && link) {
  7513. this.socialTasks.steam.wishlistLinks.push(link);
  7514. }
  7515. if (action === 'do' && !isSuccess && link) {
  7516. this.undoneTasks.steam.wishlistLinks.push(link);
  7517. }
  7518. break;
  7519.  
  7520. case 'steam_group_sub':
  7521. if (action === 'undo' && link) {
  7522. this.socialTasks.steam.groupLinks.push(link);
  7523. }
  7524. if (action === 'do' && !isSuccess && link) {
  7525. this.undoneTasks.steam.groupLinks.push(link);
  7526. }
  7527. break;
  7528.  
  7529. case 'site_visit':
  7530. if (action === 'do' && !isSuccess) {
  7531. this.undoneTasks.extra.website.push(`id=${id}&type=${type}&task=true`);
  7532. }
  7533. break;
  7534.  
  7535. case 'vk_community_sub':
  7536. if (action === 'undo' && link) {
  7537. this.socialTasks.vk.nameLinks.push(link);
  7538. }
  7539. if (action === 'do' && !isSuccess && link) {
  7540. this.undoneTasks.vk.nameLinks.push(link);
  7541. }
  7542. break;
  7543.  
  7544. case 'vk_post_like':
  7545. if (action === 'undo' && link) {
  7546. this.socialTasks.vk.nameLinks.push(`${link}&action=like`);
  7547. }
  7548. if (action === 'do' && !isSuccess && link) {
  7549. this.undoneTasks.vk.nameLinks.push(`${link}&action=like`);
  7550. }
  7551. break;
  7552.  
  7553. case 'discord_server_sub':
  7554. if (action === 'undo' && link) {
  7555. this.socialTasks.discord.serverLinks.push(link);
  7556. }
  7557. if (action === 'do' && !isSuccess && link) {
  7558. this.undoneTasks.discord.serverLinks.push(link);
  7559. }
  7560. break;
  7561.  
  7562. case 'telegram_channel_sub':
  7563. scripts_echoLog({}).warning(`${i18n('tgTaskNotice')}`);
  7564. break;
  7565.  
  7566. case 'none':
  7567. scripts_echoLog({}).warning(`${i18n('notConnect')}`);
  7568. break;
  7569.  
  7570. default:
  7571. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${type}`);
  7572. break;
  7573. }
  7574. }
  7575. logStatus.success();
  7576. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7577. this.socialTasks = this.uniqueTasks(this.socialTasks);
  7578. if (window.DEBUG) {
  7579. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7580. }
  7581. GM_setValue(`fawTasks-${this.giveawayId}`, {
  7582. tasks: this.socialTasks,
  7583. time: new Date().getTime()
  7584. });
  7585. return true;
  7586. } catch (error) {
  7587. throwError(error, 'Freeanywhere.classifyTask');
  7588. return false;
  7589. }
  7590. }
  7591. async verifyTask() {
  7592. try {
  7593. if (!this.initialized && !this.init()) {
  7594. debug('未初始化');
  7595. return false;
  7596. }
  7597. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  7598. debug('任务列表为空', this.tasks);
  7599. return false;
  7600. }
  7601. const pro = [];
  7602. for (const task of this.tasks) {
  7603. pro.push(this.#verify(task));
  7604. await delay(1e3);
  7605. }
  7606. await Promise.all(pro);
  7607. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7608. return !!await this.getKey(true);
  7609. } catch (error) {
  7610. throwError(error, 'Freeanywhere.verifyTask');
  7611. return false;
  7612. }
  7613. }
  7614. async extraDoTask({
  7615. website
  7616. }) {
  7617. try {
  7618. const pro = [];
  7619. for (const link of website) {
  7620. pro.push(this.#doVisitWebsite(link));
  7621. }
  7622. return Promise.all(pro).then(() => true);
  7623. } catch (error) {
  7624. throwError(error, 'FreeAnyWhere.extraDoTask');
  7625. return false;
  7626. }
  7627. }
  7628. async #doVisitWebsite(link) {
  7629. try {
  7630. const logStatus = scripts_echoLog({
  7631. text: i18n('visitingLink')
  7632. });
  7633. const {
  7634. result,
  7635. statusText,
  7636. status
  7637. } = await tools_httpRequest({
  7638. url: 'https://freeanywhere.net/php/task_site_visit_done.php',
  7639. method: 'POST',
  7640. headers: {
  7641. 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  7642. },
  7643. data: link
  7644. });
  7645. if (result === 'Success') {
  7646. logStatus.success();
  7647. return true;
  7648. }
  7649. logStatus.error(`${result}:${statusText}(${status})`);
  7650. return false;
  7651. } catch (error) {
  7652. throwError(error, 'FreeAnyWhere.doVisitWebsite');
  7653. return false;
  7654. }
  7655. }
  7656. async getKey(initialized) {
  7657. try {
  7658. if (!initialized && !this.initialized && !this.init()) {
  7659. debug('未初始化');
  7660. return false;
  7661. }
  7662. const logStatus = scripts_echoLog({
  7663. text: i18n('gettingKey')
  7664. });
  7665. const {
  7666. result,
  7667. statusText,
  7668. status,
  7669. data
  7670. } = await tools_httpRequest({
  7671. url: 'https://freeanywhere.net/php/user_get_key.php',
  7672. method: 'POST'
  7673. });
  7674. if (result === 'Success') {
  7675. if (data?.responseText.indexOf('bad') !== -1 || data?.responseText.length > 50) {
  7676. logStatus.error(data?.responseText);
  7677. return false;
  7678. }
  7679. logStatus.success();
  7680. scripts_echoLog({}).success(data.responseText);
  7681. return data.responseText;
  7682. }
  7683. logStatus.error(`${result}:${statusText}(${status})`);
  7684. return false;
  7685. } catch (error) {
  7686. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7687. return false;
  7688. }
  7689. }
  7690. async #verify(task) {
  7691. try {
  7692. const logStatus = scripts_echoLog({
  7693. html: `<li>${i18n('verifyingTask')}${task.title.trim()}...<font></font></li>`
  7694. });
  7695. const {
  7696. result,
  7697. statusText,
  7698. status,
  7699. data
  7700. } = await tools_httpRequest({
  7701. url: 'https://freeanywhere.net/php/user_task_update.php',
  7702. method: 'POST',
  7703. headers: {
  7704. 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  7705. },
  7706. data: `id=${task.id}&type=${task.type}`
  7707. });
  7708. if (result === 'Success') {
  7709. if (data?.responseText.trim() === 'good') {
  7710. logStatus.success();
  7711. return true;
  7712. }
  7713. debug('任务验证结果', data?.response);
  7714. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7715. return false;
  7716. }
  7717. logStatus.error(`${result}:${statusText}(${status})`);
  7718. return false;
  7719. } catch (error) {
  7720. throwError(error, 'Freeanywhere.verify');
  7721. return false;
  7722. }
  7723. }
  7724. }
  7725. const Freeanywhere = FreeAnyWhere;
  7726. const Giveawaysu_defaultTasks = {
  7727. steam: {
  7728. groupLinks: [],
  7729. wishlistLinks: [],
  7730. curatorLinks: [],
  7731. curatorLikeLinks: [],
  7732. followLinks: [],
  7733. forumLinks: [],
  7734. announcementLinks: [],
  7735. workshopVoteLinks: [],
  7736. playtestLinks: []
  7737. },
  7738. discord: {
  7739. serverLinks: []
  7740. },
  7741. instagram: {
  7742. userLinks: []
  7743. },
  7744. vk: {
  7745. nameLinks: []
  7746. },
  7747. twitch: {
  7748. channelLinks: []
  7749. },
  7750. reddit: {
  7751. redditLinks: []
  7752. },
  7753. youtube: {
  7754. channelLinks: [],
  7755. likeLinks: []
  7756. },
  7757. twitter: {
  7758. userLinks: [],
  7759. retweetLinks: []
  7760. }
  7761. };
  7762. class GiveawaySu extends website_Website {
  7763. name = 'GiveawaySu';
  7764. socialTasks = Giveawaysu_defaultTasks;
  7765. undoneTasks = Giveawaysu_defaultTasks;
  7766. buttons = [ 'doTask', 'undoTask' ];
  7767. static test() {
  7768. return /^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(window.location.href);
  7769. }
  7770. async after() {
  7771. try {
  7772. if (!this.#checkLogin()) {
  7773. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7774. }
  7775. if (!await this.#checkLeftKey()) {
  7776. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7777. }
  7778. scripts_echoLog({}).warning(i18n('gsNotice'));
  7779. } catch (error) {
  7780. throwError(error, 'Giveawaysu.after');
  7781. }
  7782. }
  7783. init() {
  7784. try {
  7785. const logStatus = scripts_echoLog({
  7786. text: i18n('initing')
  7787. });
  7788. if ($('a.steam-login').length > 0) {
  7789. window.open('/steam/redirect', '_self');
  7790. logStatus.warning(i18n('needLogin'));
  7791. return false;
  7792. }
  7793. if (!this.#getGiveawayId()) {
  7794. return false;
  7795. }
  7796. this.initialized = true;
  7797. logStatus.success();
  7798. return true;
  7799. } catch (error) {
  7800. throwError(error, 'Giveawaysu.init');
  7801. return false;
  7802. }
  7803. }
  7804. async classifyTask(action) {
  7805. try {
  7806. const logStatus = scripts_echoLog({
  7807. text: i18n('getTasksInfo')
  7808. });
  7809. if (action === 'undo') {
  7810. this.socialTasks = GM_getValue(`gasTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  7811. return true;
  7812. }
  7813. const pro = [];
  7814. const tasks = $('#actions tr');
  7815. if ($('div.bind-discord').is(':visible')) {
  7816. $('div.bind-discord a')[0].click();
  7817. }
  7818. if ($('div.bind-twitch').is(':visible')) {
  7819. $('div.bind-twitch a')[0].click();
  7820. }
  7821. for (const task of tasks) {
  7822. pro.push(new Promise(resolve => {
  7823. const td = $(task).find('td:not(".hidden")');
  7824. const colorfulTask = td.eq(1).find('a:not([data-trigger="link"])');
  7825. const colorlessTask = td.eq(2).find('a:not([data-trigger="link"])');
  7826. const taskDes = colorfulTask.length > 0 ? colorfulTask : colorlessTask;
  7827. const taskIcon = td.eq(0).find('i').attr('class') || '';
  7828. const taskName = taskDes.text().trim();
  7829. if (taskIcon.includes('ban') || /disable adblock/gi.test(taskName)) {
  7830. return resolve(true);
  7831. }
  7832. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  7833. if (!taskLink) {
  7834. return resolve(false);
  7835. }
  7836. if (taskIcon.includes('steam') && /join/gi.test(taskName)) {
  7837. this.undoneTasks.steam.groupLinks.push(taskLink);
  7838. } else if (/like.*announcement/gi.test(taskName)) {
  7839. this.undoneTasks.steam.announcementLinks.push(taskLink);
  7840. } else if (/(follow|subscribe).*curator/gim.test(taskName) && /^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  7841. this.undoneTasks.steam.curatorLinks.push(taskLink);
  7842. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  7843. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  7844. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  7845. this.undoneTasks.steam.forumLinks.push(taskLink);
  7846. } else if (taskIcon.includes('thumbs-up') && /^https?:\/\/steamcommunity\.com\/sharedfiles\/filedetails\/\?id=[\d]+/.test(taskLink)) {
  7847. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7848. } else if (taskIcon.includes('plus') && /request.*playtest/gim.test(taskName)) {
  7849. this.undoneTasks.steam.playtestLinks.push(taskLink);
  7850. } else if (taskIcon.includes('discord') || /join.*discord/gim.test(taskName)) {
  7851. this.undoneTasks.discord.serverLinks.push(taskLink);
  7852. } else if (taskIcon.includes('instagram') || /follow.*instagram/gim.test(taskName)) {
  7853. this.undoneTasks.instagram.userLinks.push(taskLink);
  7854. } else if (taskIcon.includes('twitch') || /follow.*twitch.*channel/gim.test(taskName)) {
  7855. this.undoneTasks.twitch.channelLinks.push(taskLink);
  7856. } else if (taskIcon.includes('reddit') || /subscribe.*subreddit/gim.test(taskName) || /follow.*reddit/gim.test(taskName)) {
  7857. this.undoneTasks.reddit.redditLinks.push(taskLink);
  7858. } else if (/watch.*art/gim.test(taskName)) {
  7859. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7860. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  7861. this.undoneTasks.youtube.channelLinks.push(taskLink);
  7862. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  7863. this.undoneTasks.youtube.likeLinks.push(taskLink);
  7864. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  7865. this.undoneTasks.vk.nameLinks.push(taskLink);
  7866. } else {
  7867. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  7868. if (/wishlist.*game|add.*wishlist/gim.test(taskName)) {
  7869. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  7870. }
  7871. if (/follow.*button/gim.test(taskName)) {
  7872. this.undoneTasks.steam.followLinks.push(taskLink);
  7873. }
  7874. }
  7875. }
  7876. resolve(true);
  7877. }).catch(error => {
  7878. throwError(error, 'Giveawaysu.classifyTask->getRedirectLink');
  7879. return false;
  7880. });
  7881. }));
  7882. }
  7883. await Promise.all(pro);
  7884. logStatus.success();
  7885. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7886. this.socialTasks = this.undoneTasks;
  7887. if (window.DEBUG) {
  7888. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7889. }
  7890. GM_setValue(`gasTasks-${this.giveawayId}`, {
  7891. tasks: this.socialTasks,
  7892. time: new Date().getTime()
  7893. });
  7894. return true;
  7895. } catch (error) {
  7896. throwError(error, 'Giveawaysu.classifyTask');
  7897. return false;
  7898. }
  7899. }
  7900. #checkLogin() {
  7901. try {
  7902. if (!globalOptions.other.checkLogin) {
  7903. return true;
  7904. }
  7905. if ($('a.steam-login').length > 0) {
  7906. window.open('/steam/redirect', '_self');
  7907. }
  7908. return true;
  7909. } catch (error) {
  7910. throwError(error, 'Giveawaysu.checkLogin');
  7911. return false;
  7912. }
  7913. }
  7914. async #checkLeftKey() {
  7915. try {
  7916. if (!globalOptions.other.checkLeftKey) {
  7917. return true;
  7918. }
  7919. if ($('.giveaway-ended').length > 0 && $('.giveaway-key').length === 0) {
  7920. await external_Swal_default().fire({
  7921. icon: 'warning',
  7922. title: i18n('notice'),
  7923. text: i18n('noKeysLeft'),
  7924. confirmButtonText: i18n('confirm'),
  7925. cancelButtonText: i18n('cancel'),
  7926. showCancelButton: true
  7927. }).then(({
  7928. value
  7929. }) => {
  7930. if (value) {
  7931. window.close();
  7932. }
  7933. });
  7934. }
  7935. return true;
  7936. } catch (error) {
  7937. throwError(error, 'Giveawaysu.checkLeftKey');
  7938. return false;
  7939. }
  7940. }
  7941. #getGiveawayId() {
  7942. try {
  7943. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  7944. if (giveawayId) {
  7945. this.giveawayId = giveawayId;
  7946. return true;
  7947. }
  7948. scripts_echoLog({
  7949. text: i18n('getFailed', 'GiveawayId')
  7950. });
  7951. return false;
  7952. } catch (error) {
  7953. throwError(error, 'Giveawaysu.getGiveawayId');
  7954. return false;
  7955. }
  7956. }
  7957. }
  7958. class Indiedb {
  7959. name = 'Indiedb';
  7960. buttons = [ 'doTask' ];
  7961. static test() {
  7962. return window.location.host === 'www.indiedb.com';
  7963. }
  7964. async after() {
  7965. try {
  7966. if (!this.#checkLogin()) {
  7967. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7968. }
  7969. if (!await this.#checkLeftKey()) {
  7970. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7971. }
  7972. } catch (error) {
  7973. throwError(error, 'Indiedb.after');
  7974. }
  7975. }
  7976. async doTask() {
  7977. try {
  7978. if (!await this.#join()) {
  7979. return false;
  7980. }
  7981. return await this.#do();
  7982. } catch (error) {
  7983. throwError(error, 'Indiedb.doTask');
  7984. return false;
  7985. }
  7986. }
  7987. async #join() {
  7988. try {
  7989. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7990. scripts_echoLog({}).error(i18n('needLogin'));
  7991. return false;
  7992. }
  7993. const currentoption = $('a.buttonenter.buttongiveaway');
  7994. if (/join giveaway/gim.test(currentoption.text())) {
  7995. const logStatus = scripts_echoLog({
  7996. text: `${i18n('joiningGiveaway')}...`
  7997. });
  7998. const {
  7999. result,
  8000. statusText,
  8001. status,
  8002. data
  8003. } = await tools_httpRequest({
  8004. url: currentoption.attr('href'),
  8005. method: 'POST',
  8006. data: 'ajax=t',
  8007. dataType: 'json',
  8008. headers: {
  8009. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  8010. Accept: 'application/json, text/javascript, */*; q=0.01',
  8011. Origin: window.location.origin,
  8012. referer: window.location.href
  8013. }
  8014. });
  8015. if (result === 'Success') {
  8016. if (data?.status === 200) {
  8017. if (data.response?.success) {
  8018. currentoption.addClass('buttonentered').text('Success - Giveaway joined');
  8019. $('#giveawaysjoined').slideDown();
  8020. $('#giveawaysrecommend').slideDown();
  8021. logStatus.success(`Success${data.response?.text ? `:${data.response?.text}` : ''}`);
  8022. return true;
  8023. }
  8024. logStatus.error(`Error${data.response?.text ? `:${data.response?.text}` : ''}`);
  8025. return false;
  8026. }
  8027. if (await this.#join2()) {
  8028. logStatus.success('Success');
  8029. return true;
  8030. }
  8031. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  8032. return false;
  8033. }
  8034. logStatus.error(`${result}:${statusText}(${status})`);
  8035. return false;
  8036. } else if (/success/gim.test($('a.buttonenter.buttongiveaway').text())) {
  8037. return true;
  8038. }
  8039. scripts_echoLog({}).warning(i18n('needJoinGiveaway'));
  8040. return false;
  8041. } catch (error) {
  8042. throwError(error, 'Indiedb.join');
  8043. return false;
  8044. }
  8045. }
  8046. async #join2() {
  8047. try {
  8048. return await new Promise(resolve => {
  8049. const targetNode = document.getElementById('giveawaysjoined');
  8050. const config = {
  8051. attributes: true
  8052. };
  8053. const observer = new MutationObserver(() => {
  8054. if ($('#giveawaysjoined').is(':visible')) {
  8055. resolve(true);
  8056. observer.disconnect();
  8057. }
  8058. });
  8059. observer.observe(targetNode, config);
  8060. $('a.buttonenter.buttongiveaway')[0]?.click();
  8061. setTimeout(() => {
  8062. resolve(false);
  8063. observer.disconnect();
  8064. }, 3e4);
  8065. });
  8066. } catch (error) {
  8067. throwError(error, 'Indiedb.join2');
  8068. return false;
  8069. }
  8070. }
  8071. async #do() {
  8072. try {
  8073. const id = $('script').map((index, script) => {
  8074. if (/\$\(document\)/gim.test(script.innerHTML)) {
  8075. return [ script.innerHTML.match(/"\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0], script.innerHTML.match(/"\/newsletter\/ajax\/subscribeprofile\/optin\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0] ];
  8076. }
  8077. return null;
  8078. });
  8079. if (id.length === 2) {
  8080. const pro = [];
  8081. const tasks = $('#giveawaysjoined a[class*=promo]');
  8082. for (const task of tasks) {
  8083. const promo = $(task);
  8084. if (!promo.hasClass('buttonentered')) {
  8085. const status = scripts_echoLog({
  8086. text: `${i18n('doing')}:${promo.parents('p').text()}...`
  8087. });
  8088. if (/facebookpromo|twitterpromo|visitpromo/gim.test(task.className)) {
  8089. let text = '';
  8090. if (promo.hasClass('facebookpromo')) {
  8091. text = 'facebookpromo';
  8092. } else if (promo.hasClass('twitterpromo')) {
  8093. text = 'twitterpromo';
  8094. } else {
  8095. text = 'visitpromo';
  8096. }
  8097. pro.push(new Promise(resolve => {
  8098. $.ajax({
  8099. type: 'POST',
  8100. url: urlPath(`/giveaways/ajax/${text}/${id[0]}`),
  8101. timeout: 6e4,
  8102. dataType: 'json',
  8103. data: {
  8104. ajax: 't'
  8105. },
  8106. error(response, error, exception) {
  8107. if (window.DEBUG) {
  8108. console.log('%cAuto-Task[Debug]:', 'color:red', {
  8109. response: response,
  8110. error: error,
  8111. exception: exception
  8112. });
  8113. }
  8114. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  8115. resolve(true);
  8116. },
  8117. success(response) {
  8118. if (response.success) {
  8119. status.success(`Success:${response.text}`);
  8120. promo.addClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  8121. resolve(true);
  8122. } else {
  8123. status.error(`Error:${response.text}`);
  8124. resolve(true);
  8125. }
  8126. }
  8127. });
  8128. }));
  8129. } else if (promo.hasClass('emailoptinpromo')) {
  8130. pro.push(new Promise(resolve => {
  8131. $.ajax({
  8132. type: 'POST',
  8133. url: urlPath(`/newsletter/ajax/subscribeprofile/optin/${id[1]}`),
  8134. timeout: 6e4,
  8135. dataType: 'json',
  8136. data: {
  8137. ajax: 't',
  8138. emailsystoggle: 4
  8139. },
  8140. error(response, error, exception) {
  8141. if (window.DEBUG) {
  8142. console.log('%cAuto-Task[Debug]:', 'color:red', {
  8143. response: response,
  8144. error: error,
  8145. exception: exception
  8146. });
  8147. }
  8148. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  8149. resolve(true);
  8150. },
  8151. success(response) {
  8152. if (response.success) {
  8153. status.success(`Success:${response.text}`);
  8154. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  8155. resolve(true);
  8156. } else {
  8157. status.error(`Error:${response.text}`);
  8158. resolve(true);
  8159. }
  8160. }
  8161. });
  8162. }));
  8163. } else if (promo.hasClass('watchingpromo')) {
  8164. pro.push(new Promise(resolve => {
  8165. const data = getUrlQuery(promo.attr('href'));
  8166. data.ajax = 't';
  8167. $.ajax({
  8168. type: 'POST',
  8169. url: urlPath(promo.attr('href')?.split(/[?#]/)[0]),
  8170. timeout: 6e4,
  8171. dataType: 'json',
  8172. data: data,
  8173. error(response, error, exception) {
  8174. if (window.DEBUG) {
  8175. console.log('%cAuto-Task[Debug]:', 'color:red', {
  8176. response: response,
  8177. error: error,
  8178. exception: exception
  8179. });
  8180. }
  8181. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  8182. resolve(true);
  8183. },
  8184. success(response) {
  8185. if (response.success) {
  8186. status.success(`Success:${response.text}`);
  8187. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  8188. resolve(true);
  8189. } else {
  8190. status.error(`Error:${response.text}`);
  8191. resolve(true);
  8192. }
  8193. }
  8194. });
  8195. }));
  8196. } else if (!/the-challenge-of-adblock/gim.test(promo.attr('href'))) {
  8197. pro.push(new Promise(resolve => {
  8198. $.ajax({
  8199. type: 'POST',
  8200. url: urlPath(promo.attr('href')),
  8201. timeout: 6e4,
  8202. dataType: 'json',
  8203. data: {
  8204. ajax: 't'
  8205. },
  8206. error(response, error, exception) {
  8207. if (window.DEBUG) {
  8208. console.log('%cAuto-Task[Debug]:', 'color:red', {
  8209. response: response,
  8210. error: error,
  8211. exception: exception
  8212. });
  8213. }
  8214. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  8215. resolve(true);
  8216. },
  8217. success(response) {
  8218. if (response.success) {
  8219. status.success(`Success:${response.text}`);
  8220. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  8221. resolve(true);
  8222. } else {
  8223. status.error(`Error:${response.text}`);
  8224. resolve(true);
  8225. }
  8226. }
  8227. });
  8228. }));
  8229. } else {
  8230. status.error(`Error:${i18n('unKnownTaskType')}`);
  8231. }
  8232. }
  8233. }
  8234. await Promise.all(pro);
  8235. scripts_echoLog({}).success(i18n('allTasksComplete'));
  8236. return true;
  8237. }
  8238. scripts_echoLog({}).error(i18n('getFailed', 'TaskId'));
  8239. return false;
  8240. } catch (error) {
  8241. throwError(error, 'Indiedb.classifyTask');
  8242. return false;
  8243. }
  8244. }
  8245. #checkLogin() {
  8246. try {
  8247. if (!globalOptions.other.checkLogin) {
  8248. return true;
  8249. }
  8250. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  8251. window.open('/members/login', '_self');
  8252. }
  8253. return true;
  8254. } catch (error) {
  8255. throwError(error, 'Indiedb.checkLogin');
  8256. return false;
  8257. }
  8258. }
  8259. async #checkLeftKey() {
  8260. try {
  8261. if (!globalOptions.other.checkLeftKey) {
  8262. return true;
  8263. }
  8264. if ($('a.buttonenter:contains("next time"), a.buttonenter:contains("Giveaway is closed")').length > 0) {
  8265. await external_Swal_default().fire({
  8266. icon: 'warning',
  8267. title: i18n('notice'),
  8268. text: i18n('giveawayEnded'),
  8269. confirmButtonText: i18n('confirm'),
  8270. cancelButtonText: i18n('cancel'),
  8271. showCancelButton: true
  8272. }).then(({
  8273. value
  8274. }) => {
  8275. if (value) {
  8276. window.close();
  8277. }
  8278. });
  8279. }
  8280. return true;
  8281. } catch (error) {
  8282. throwError(error, 'Indiedb.checkLeftKey');
  8283. return false;
  8284. }
  8285. }
  8286. }
  8287. const website_Indiedb = Indiedb;
  8288. const Keyhub_defaultTasksTemplate = {
  8289. steam: {
  8290. groupLinks: [],
  8291. officialGroupLinks: [],
  8292. wishlistLinks: [],
  8293. curatorLinks: []
  8294. },
  8295. discord: {
  8296. serverLinks: []
  8297. },
  8298. extra: {
  8299. videoTasks: []
  8300. },
  8301. links: []
  8302. };
  8303. const Keyhub_defaultTasks = JSON.stringify(Keyhub_defaultTasksTemplate);
  8304. class Keyhub extends website_Website {
  8305. name = 'Keyhub';
  8306. socialTasks = JSON.parse(Keyhub_defaultTasks);
  8307. undoneTasks = JSON.parse(Keyhub_defaultTasks);
  8308. buttons = [ 'doTask', 'undoTask' ];
  8309. static test() {
  8310. return window.location.host === 'key-hub.eu';
  8311. }
  8312. async after() {
  8313. try {
  8314. if (!this.#checkLogin()) {
  8315. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8316. }
  8317. if (!await this.#checkLeftKey()) {
  8318. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8319. }
  8320. $('.NSFW').hide();
  8321. } catch (error) {
  8322. throwError(error, 'Keyhub.after');
  8323. }
  8324. }
  8325. init() {
  8326. try {
  8327. const logStatus = scripts_echoLog({
  8328. text: i18n('initing')
  8329. });
  8330. if ($('a[href*="/connect/steam"]').length > 0) {
  8331. window.open('/connect/steam', '_self');
  8332. logStatus.warning(i18n('needLogin'));
  8333. return false;
  8334. }
  8335. if (!this.#getGiveawayId()) {
  8336. return false;
  8337. }
  8338. $('#VPNoverlay').hide();
  8339. $('#mainArticleSection').show();
  8340. this.initialized = true;
  8341. logStatus.success();
  8342. return true;
  8343. } catch (error) {
  8344. throwError(error, 'Keyhub.init');
  8345. return false;
  8346. }
  8347. }
  8348. async classifyTask(action) {
  8349. try {
  8350. const logStatus = scripts_echoLog({
  8351. text: i18n('getTasksInfo')
  8352. });
  8353. if (action === 'undo') {
  8354. this.socialTasks = GM_getValue(`khTasks-${this.giveawayId}`)?.tasks || JSON.parse(Keyhub_defaultTasks);
  8355. }
  8356. const tasks = $('.task:not(".googleads")').filter((index, element) => action === 'do' ? $(element).find('i.fa-check-circle:visible').length === 0 : true).find('a');
  8357. for (const task of tasks) {
  8358. let link = $(task).attr('href');
  8359. const taskDes = $(task).text().trim();
  8360. if (!link) {
  8361. continue;
  8362. }
  8363. if (/\/away\?data=/.test(link) || /steamcommunity\.com\/gid\//.test(link)) {
  8364. link = await getRedirectLink(link) || link;
  8365. }
  8366. if (/https?:\/\/key-hub\.eu\/connect\/discord/.test(link)) {
  8367. GM_openInTab(link, {
  8368. active: true
  8369. });
  8370. } else if (/steamcommunity\.com\/groups\//.test(link)) {
  8371. if (action === 'undo') {
  8372. this.socialTasks.steam.groupLinks.push(link);
  8373. }
  8374. if (action === 'do') {
  8375. this.undoneTasks.steam.groupLinks.push(link);
  8376. }
  8377. } else if (/steamcommunity\.com\/games\/[\d]+/.test(link)) {
  8378. if (action === 'undo') {
  8379. this.socialTasks.steam.officialGroupLinks.push(link);
  8380. }
  8381. if (action === 'do') {
  8382. this.undoneTasks.steam.officialGroupLinks.push(link);
  8383. }
  8384. } else if (/store\.steampowered\.com\/app\//.test(link) && /wishlist/gim.test(taskDes)) {
  8385. if (action === 'undo') {
  8386. this.socialTasks.steam.wishlistLinks.push(link);
  8387. }
  8388. if (action === 'do') {
  8389. this.undoneTasks.steam.wishlistLinks.push(link);
  8390. }
  8391. } else if (/store\.steampowered\.com\/curator\//.test(link)) {
  8392. if (action === 'undo') {
  8393. this.socialTasks.steam.curatorLinks.push(link);
  8394. }
  8395. if (action === 'do') {
  8396. this.undoneTasks.steam.curatorLinks.push(link);
  8397. }
  8398. } else if (/^https?:\/\/discord\.com\/invite\//.test(link)) {
  8399. if (action === 'undo') {
  8400. this.socialTasks.discord.serverLinks.push(link);
  8401. }
  8402. if (action === 'do') {
  8403. this.undoneTasks.discord.serverLinks.push(link);
  8404. }
  8405. } else if (/^javascript:videoTask.+/.test(link)) {
  8406. if (action === 'do') {
  8407. const taskData = link.match(/javascript:videoTask\('.+?','(.+?)'/)?.[1];
  8408. if (taskData) {
  8409. this.undoneTasks.extra.videoTasks.push(taskData);
  8410. }
  8411. }
  8412. } 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 {
  8413. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  8414. }
  8415. }
  8416. logStatus.success();
  8417. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8418. this.socialTasks = this.uniqueTasks(this.socialTasks);
  8419. if (window.DEBUG) {
  8420. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8421. }
  8422. GM_setValue(`khTasks-${this.giveawayId}`, {
  8423. tasks: this.socialTasks,
  8424. time: new Date().getTime()
  8425. });
  8426. return true;
  8427. } catch (error) {
  8428. throwError(error, 'Keyhub.classifyTask');
  8429. return false;
  8430. }
  8431. }
  8432. async #doScriptTask(data) {
  8433. try {
  8434. const logStatus = scripts_echoLog({
  8435. text: i18n('doingKeyhubTask')
  8436. });
  8437. const {
  8438. result,
  8439. statusText,
  8440. status,
  8441. data: response
  8442. } = await tools_httpRequest({
  8443. url: `/away?data=${data}`,
  8444. method: 'GET',
  8445. headers: {
  8446. origin: 'https://key-hub.eu',
  8447. referer: 'https://key-hub.eu/'
  8448. }
  8449. });
  8450. if (result === 'Success') {
  8451. if (response?.status === 200) {
  8452. logStatus.success();
  8453. return true;
  8454. }
  8455. logStatus.error(`Error:${response?.statusText}(${response?.status})`);
  8456. return false;
  8457. }
  8458. logStatus.error(`${result}:${statusText}(${status})`);
  8459. return false;
  8460. } catch (error) {
  8461. throwError(error, 'Keyhub.doScriptTask');
  8462. return false;
  8463. }
  8464. }
  8465. async extraDoTask({
  8466. videoTasks
  8467. }) {
  8468. try {
  8469. const pro = [];
  8470. for (const data of videoTasks) {
  8471. pro.push(this.#doScriptTask(data));
  8472. }
  8473. return Promise.all(pro).then(() => true);
  8474. } catch (error) {
  8475. throwError(error, 'Keyhub.extraDoTask');
  8476. return false;
  8477. }
  8478. }
  8479. #getGiveawayId() {
  8480. try {
  8481. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  8482. if (giveawayId) {
  8483. this.giveawayId = giveawayId;
  8484. return true;
  8485. }
  8486. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  8487. return false;
  8488. } catch (error) {
  8489. throwError(error, 'Keyhub.getGiveawayId');
  8490. return false;
  8491. }
  8492. }
  8493. async #checkLeftKey() {
  8494. try {
  8495. if (!globalOptions.other.checkLeftKey) {
  8496. return true;
  8497. }
  8498. const leftKey = $('#keysleft').text().trim();
  8499. if (leftKey === '0') {
  8500. await external_Swal_default().fire({
  8501. icon: 'warning',
  8502. title: i18n('notice'),
  8503. text: i18n('noKeysLeft'),
  8504. confirmButtonText: i18n('confirm'),
  8505. cancelButtonText: i18n('cancel'),
  8506. showCancelButton: true
  8507. }).then(({
  8508. value
  8509. }) => {
  8510. if (value) {
  8511. window.close();
  8512. }
  8513. });
  8514. }
  8515. return true;
  8516. } catch (error) {
  8517. throwError(error, 'Keyhub.checkLeftKey');
  8518. return false;
  8519. }
  8520. }
  8521. #checkLogin() {
  8522. try {
  8523. if (!globalOptions.other.checkLogin) {
  8524. return true;
  8525. }
  8526. if ($('a[href*="/connect/steam"]').length > 0) {
  8527. window.open('/connect/steam', '_self');
  8528. }
  8529. return true;
  8530. } catch (error) {
  8531. throwError(error, 'Keyhub.checkLogin');
  8532. return false;
  8533. }
  8534. }
  8535. }
  8536. const website_Keyhub = Keyhub;
  8537. const Givekey_defaultTasksTemplate = {
  8538. steam: {
  8539. groupLinks: [],
  8540. wishlistLinks: [],
  8541. curatorLinks: [],
  8542. curatorLikeLinks: []
  8543. },
  8544. twitter: {
  8545. userLinks: []
  8546. },
  8547. vk: {
  8548. nameLinks: []
  8549. },
  8550. discord: {
  8551. serverLinks: []
  8552. }
  8553. };
  8554. const Givekey_defaultTasks = JSON.stringify(Givekey_defaultTasksTemplate);
  8555. class Givekey extends website_Website {
  8556. name = 'Givekey';
  8557. tasks = [];
  8558. socialTasks = JSON.parse(Givekey_defaultTasks);
  8559. undoneTasks = JSON.parse(Givekey_defaultTasks);
  8560. userId;
  8561. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8562. static test() {
  8563. return window.location.host === 'givekey.ru';
  8564. }
  8565. async after() {
  8566. try {
  8567. await new Promise(resolve => {
  8568. const checker = setInterval(() => {
  8569. if ($('#navbarDropdown').length > 0) {
  8570. clearInterval(checker);
  8571. resolve(true);
  8572. }
  8573. }, 500);
  8574. });
  8575. if (!await this.#checkLeftKey()) {
  8576. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8577. }
  8578. } catch (error) {
  8579. throwError(error, 'Givekey.after');
  8580. }
  8581. }
  8582. init() {
  8583. try {
  8584. const logStatus = scripts_echoLog({
  8585. text: i18n('initing')
  8586. });
  8587. if ($('a[href*="/auth/steam"]').length > 0) {
  8588. window.open('/auth/steam', '_self');
  8589. logStatus.warning(i18n('needLogin'));
  8590. return false;
  8591. }
  8592. if (!this.#getGiveawayId()) {
  8593. return false;
  8594. }
  8595. const userId = $('meta[name="user-id"]').attr('content');
  8596. if (!userId) {
  8597. logStatus.error(i18n('getFailed', i18n('userId')));
  8598. return false;
  8599. }
  8600. this.userId = userId;
  8601. this.initialized = true;
  8602. logStatus.success();
  8603. return true;
  8604. } catch (error) {
  8605. throwError(error, 'Givekey.init');
  8606. return false;
  8607. }
  8608. }
  8609. async classifyTask(action) {
  8610. try {
  8611. const logStatus = scripts_echoLog({
  8612. text: i18n('getTasksInfo')
  8613. });
  8614. if (action === 'undo') {
  8615. this.socialTasks = GM_getValue(`gkTasks-${this.giveawayId}`)?.tasks || JSON.parse(Givekey_defaultTasks);
  8616. }
  8617. const tasks = $('.card-body:has("button") .row');
  8618. for (const task of tasks) {
  8619. const taskEle = $(task);
  8620. const isSuccess = /Complete/i.test(taskEle.find('button').text().trim());
  8621. if (isSuccess && action !== 'undo') {
  8622. continue;
  8623. }
  8624. const checkButton = taskEle.find('#task_check');
  8625. const taskId = checkButton.attr('data-id');
  8626. if (taskId) {
  8627. this.tasks.push(taskId);
  8628. }
  8629. if (action === 'verify') {
  8630. continue;
  8631. }
  8632. let href = taskEle.find('a').attr('href') || null;
  8633. const text = taskEle.find('a').text().trim();
  8634. const icon = taskEle.find('i');
  8635. if (!href || !text) {
  8636. continue;
  8637. }
  8638. if (/^https?:\/\/givekey\.ru\/giveaway\/[\d]+\/execution_task/.test(href)) {
  8639. href = await getRedirectLink(href);
  8640. }
  8641. if (!href) {
  8642. continue;
  8643. }
  8644. if (/^https?:\/\/vk\.com\//.test(href)) {
  8645. this.socialTasks.vk.nameLinks.push(href);
  8646. if (action === 'do' && !isSuccess) {
  8647. this.undoneTasks.vk.nameLinks.push(href);
  8648. }
  8649. } else if (/^https?:\/\/steamcommunity\.com\/groups/.test(href)) {
  8650. this.socialTasks.steam.groupLinks.push(href);
  8651. if (action === 'do' && !isSuccess) {
  8652. this.undoneTasks.steam.groupLinks.push(href);
  8653. }
  8654. } else if (/^https?:\/\/store\.steampowered\.com\/app\//.test(href)) {
  8655. this.socialTasks.steam.wishlistLinks.push(href);
  8656. if (action === 'do' && !isSuccess) {
  8657. this.undoneTasks.steam.wishlistLinks.push(href);
  8658. }
  8659. } else if (/Subscribe/gi.test(text) && icon.hasClass('fa-steam-square')) {
  8660. if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(href)) {
  8661. this.socialTasks.steam.curatorLinks.push(href);
  8662. if (action === 'do' && !isSuccess) {
  8663. this.undoneTasks.steam.curatorLinks.push(href);
  8664. }
  8665. } else {
  8666. this.socialTasks.steam.curatorLikeLinks.push(href);
  8667. if (action === 'do' && !isSuccess) {
  8668. this.undoneTasks.steam.curatorLikeLinks.push(href);
  8669. }
  8670. }
  8671. } else if (/^https?:\/\/twitter\.com\//.test(href) && /Subscribe/gi.test(text)) {
  8672. this.socialTasks.twitter.userLinks.push(href);
  8673. if (action === 'do' && !isSuccess) {
  8674. this.undoneTasks.twitter.userLinks.push(href);
  8675. }
  8676. } else if (icon.hasClass('fa-discord') || /^https?:\/\/discord\.com\/invite\//.test(href)) {
  8677. this.socialTasks.discord.serverLinks.push(href);
  8678. if (action === 'do' && !isSuccess) {
  8679. this.undoneTasks.discord.serverLinks.push(href);
  8680. }
  8681. } else {
  8682. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${text}(${href})`);
  8683. }
  8684. }
  8685. logStatus.success();
  8686. this.tasks = unique(this.tasks);
  8687. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8688. this.socialTasks = this.uniqueTasks(this.socialTasks);
  8689. if (window.DEBUG) {
  8690. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8691. }
  8692. GM_setValue(`gkTasks-${this.giveawayId}`, {
  8693. tasks: this.socialTasks,
  8694. time: new Date().getTime()
  8695. });
  8696. return true;
  8697. } catch (error) {
  8698. throwError(error, 'Givekey.classifyTask');
  8699. return false;
  8700. }
  8701. }
  8702. async verifyTask() {
  8703. try {
  8704. if (!this.initialized && !this.init()) {
  8705. return false;
  8706. }
  8707. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  8708. return false;
  8709. }
  8710. scripts_echoLog({}).warning(i18n('giveKeyNoticeBefore'));
  8711. const taskLength = this.tasks.length;
  8712. for (let i = 0; i < taskLength; i++) {
  8713. await this.#verify(this.tasks[i]);
  8714. if (i < taskLength - 1) {
  8715. await delay(15e3);
  8716. }
  8717. }
  8718. scripts_echoLog({}).success(i18n('allTasksComplete'));
  8719. scripts_echoLog({
  8720. html: `<li><font class="warning">${i18n('giveKeyNoticeAfter')}</font></li>`
  8721. });
  8722. return true;
  8723. } catch (error) {
  8724. throwError(error, 'Givekey.verifyTask');
  8725. return false;
  8726. }
  8727. }
  8728. async #verify(task) {
  8729. try {
  8730. const logStatus = scripts_echoLog({
  8731. html: `<li>${i18n('verifyingTask')}${task}...<font></font></li>`
  8732. });
  8733. return await new Promise(resolve => {
  8734. $.ajax({
  8735. url: 'https://givekey.ru/giveaway/task',
  8736. method: 'POST',
  8737. data: `id=${task}&user_id=${this.userId}`,
  8738. dataType: 'json',
  8739. headers: {
  8740. 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  8741. },
  8742. success: data => {
  8743. if (data.btn) {
  8744. $(`button[data-id=${this.userId}]`).html(data.btn);
  8745. }
  8746. if (data.status === 'ok') {
  8747. $(`.task_check_${data.id}`).html(`<button class="btn btn-success mb-2 btn-block" disabled>${data.btn}</button>`);
  8748. logStatus.success();
  8749. resolve(true);
  8750. } else if (data.status === 'end') {
  8751. logStatus.success();
  8752. scripts_echoLog({}).success(data.key);
  8753. resolve(true);
  8754. } else {
  8755. logStatus.error(`Error:${data.msg}`);
  8756. resolve(false);
  8757. }
  8758. },
  8759. error: xhr => {
  8760. logStatus.error(`Error:${xhr.statusText}(${xhr.status})`);
  8761. resolve(false);
  8762. }
  8763. });
  8764. });
  8765. } catch (error) {
  8766. throwError(error, 'Givekey.verify');
  8767. return false;
  8768. }
  8769. }
  8770. #getGiveawayId() {
  8771. try {
  8772. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  8773. if (giveawayId) {
  8774. this.giveawayId = giveawayId;
  8775. return true;
  8776. }
  8777. scripts_echoLog({
  8778. text: i18n('getFailed', 'GiveawayId')
  8779. });
  8780. return false;
  8781. } catch (error) {
  8782. throwError(error, 'Givekey.getGiveawayId');
  8783. return false;
  8784. }
  8785. }
  8786. async #checkLeftKey() {
  8787. try {
  8788. if (!globalOptions.other.checkLeftKey) {
  8789. return true;
  8790. }
  8791. if (!$('#keys_count').text()) {
  8792. await external_Swal_default().fire({
  8793. icon: 'warning',
  8794. title: i18n('notice'),
  8795. text: i18n('noKeysLeft'),
  8796. confirmButtonText: i18n('confirm'),
  8797. cancelButtonText: i18n('cancel'),
  8798. showCancelButton: true
  8799. }).then(({
  8800. value
  8801. }) => {
  8802. if (value) {
  8803. window.close();
  8804. }
  8805. });
  8806. }
  8807. return true;
  8808. } catch (error) {
  8809. throwError(error, 'Givekey.checkLeftKey');
  8810. return false;
  8811. }
  8812. }
  8813. }
  8814. const website_Givekey = Givekey;
  8815. class GiveeClub extends GiveawaySu {
  8816. name = 'GiveeClub';
  8817. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8818. static test() {
  8819. return /^https?:\/\/givee\.club\/.*?\/event\/[\d]+/.test(window.location.href);
  8820. }
  8821. async after() {
  8822. try {
  8823. if (!this.#checkLogin()) {
  8824. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8825. }
  8826. if (!await this.#checkLeftKey()) {
  8827. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8828. }
  8829. } catch (error) {
  8830. throwError(error, 'GiveeClub.after');
  8831. }
  8832. }
  8833. init() {
  8834. try {
  8835. const logStatus = scripts_echoLog({
  8836. text: i18n('initing')
  8837. });
  8838. if (!this.#checkLogin()) {
  8839. logStatus.warning(i18n('needLogin'));
  8840. return false;
  8841. }
  8842. if (!this.#getGiveawayId()) {
  8843. return false;
  8844. }
  8845. this.initialized = true;
  8846. logStatus.success();
  8847. return true;
  8848. } catch (error) {
  8849. throwError(error, 'GiveeClub.init');
  8850. return false;
  8851. }
  8852. }
  8853. async classifyTask(action) {
  8854. try {
  8855. const logStatus = scripts_echoLog({
  8856. text: i18n('getTasksInfo')
  8857. });
  8858. if (action === 'undo') {
  8859. this.socialTasks = GM_getValue(`gcTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  8860. return true;
  8861. }
  8862. this.undoneTasks = Giveawaysu_defaultTasks;
  8863. const pro = [];
  8864. const tasks = $('.event-actions tr');
  8865. for (const task of tasks) {
  8866. pro.push(new Promise(resolve => {
  8867. const taskDes = $(task).find('.event-action-label a');
  8868. const taskIcon = $(task).find('.event-action-icon i').attr('class') || '';
  8869. const taskName = taskDes.text().trim();
  8870. const taskType = $(task).find('button[data-type]')?.attr('data-type');
  8871. const taskFinished = $(task).find('.event-action-buttons .btn-success')?.length;
  8872. if (taskIcon.includes('ban') || /AdBlock/i.test(taskName) || taskIcon.includes('envelope') || taskFinished) {
  8873. return resolve(true);
  8874. }
  8875. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  8876. if (!taskLink) {
  8877. return resolve(false);
  8878. }
  8879. if (taskType === 'steam.group.join' && /^https?:\/\/steamcommunity\.com\/groups/.test(taskLink)) {
  8880. this.undoneTasks.steam.groupLinks.push(taskLink);
  8881. } else if (/like.*announcement/gi.test(taskName)) {
  8882. this.undoneTasks.steam.announcementLinks.push(taskLink);
  8883. } else if (taskType === 'steam.game.wishlist' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8884. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  8885. } else if (taskType === 'steam.game.wishlist' && taskDes.attr('data-steam-wishlist-appid')) {
  8886. this.undoneTasks.steam.wishlistLinks.push(`https://store.steampowered.com/app/${taskDes.attr('data-steam-wishlist-appid')}`);
  8887. } else if (taskType === 'steam.game.follow' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8888. this.undoneTasks.steam.followLinks.push(taskLink);
  8889. } else if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  8890. this.undoneTasks.steam.curatorLinks.push(taskLink);
  8891. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  8892. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  8893. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  8894. this.undoneTasks.steam.forumLinks.push(taskLink);
  8895. } else if (taskIcon.includes('discord')) {
  8896. this.undoneTasks.discord.serverLinks.push(taskLink);
  8897. } else if (taskIcon.includes('instagram')) {
  8898. this.undoneTasks.instagram.userLinks.push(taskLink);
  8899. } else if (taskIcon.includes('twitch')) {
  8900. this.undoneTasks.twitch.channelLinks.push(taskLink);
  8901. } else if (taskIcon.includes('reddit')) {
  8902. this.undoneTasks.reddit.redditLinks.push(taskLink);
  8903. } else if (/watch.*art/gim.test(taskName)) {
  8904. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  8905. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  8906. this.undoneTasks.youtube.channelLinks.push(taskLink);
  8907. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  8908. this.undoneTasks.youtube.likeLinks.push(taskLink);
  8909. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  8910. this.undoneTasks.vk.nameLinks.push(taskLink);
  8911. } else if (taskIcon.includes('twitter')) {
  8912. if (/https?:\/\/(twitter|x)\.com\/[^/]+\/?$/gim.test(taskLink)) {
  8913. this.undoneTasks.twitter.userLinks.push(taskLink);
  8914. } else if (/https?:\/\/(twitter|x)\.com\/[^/]+?\/status\/[\d]+/gim.test(taskLink)) {
  8915. this.undoneTasks.twitter.retweetLinks.push(taskLink);
  8916. }
  8917. } else {
  8918. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  8919. if (/follow.*button/gim.test(taskName)) {
  8920. this.undoneTasks.steam.followLinks.push(taskLink);
  8921. }
  8922. }
  8923. }
  8924. resolve(true);
  8925. }).catch(error => {
  8926. throwError(error, 'GiveeClub.classifyTask->getRedirectLink');
  8927. return false;
  8928. });
  8929. }));
  8930. }
  8931. await Promise.all(pro);
  8932. logStatus.success();
  8933. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8934. this.socialTasks = this.undoneTasks;
  8935. if (window.DEBUG) {
  8936. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8937. }
  8938. GM_setValue(`gcTasks-${this.giveawayId}`, {
  8939. tasks: this.socialTasks,
  8940. time: new Date().getTime()
  8941. });
  8942. return true;
  8943. } catch (error) {
  8944. throwError(error, 'GiveeClub.classifyTask');
  8945. return false;
  8946. }
  8947. }
  8948. async verifyTask() {
  8949. try {
  8950. const logStatus = scripts_echoLog({
  8951. text: i18n('giveeClubVerifyNotice')
  8952. });
  8953. const taskButtons = $('.event-actions tr button').has('i.glyphicon-refresh').not('[data-type="user.adblock"]');
  8954. for (const button of taskButtons) {
  8955. button.click();
  8956. if ($(button).attr('data-type') !== 'steam.game.wishlist') {
  8957. await delay(1e3);
  8958. }
  8959. }
  8960. logStatus.warning(i18n('giveeClubVerifyFinished'));
  8961. return true;
  8962. } catch (error) {
  8963. throwError(error, 'Givekey.verifyTask');
  8964. return false;
  8965. }
  8966. }
  8967. #checkLogin() {
  8968. try {
  8969. if (!globalOptions.other.checkLogin) {
  8970. return true;
  8971. }
  8972. if ($('a[href*="/account/auth"]').length > 0) {
  8973. window.open($('a[href*="/account/auth"]').attr('href'), '_self');
  8974. }
  8975. return true;
  8976. } catch (error) {
  8977. throwError(error, 'GiveeClub.checkLogin');
  8978. return false;
  8979. }
  8980. }
  8981. #getGiveawayId() {
  8982. const giveawayId = window.location.href.match(/\/event\/([\d]+)/)?.[1];
  8983. if (giveawayId) {
  8984. this.giveawayId = giveawayId;
  8985. return true;
  8986. }
  8987. scripts_echoLog({
  8988. text: i18n('getFailed', 'GiveawayId')
  8989. });
  8990. return false;
  8991. }
  8992. async #checkLeftKey() {
  8993. try {
  8994. if (!globalOptions.other.checkLeftKey) {
  8995. return true;
  8996. }
  8997. if ($('.event-ended').length > 0 && $('.event-winner').length === 0) {
  8998. await external_Swal_default().fire({
  8999. icon: 'warning',
  9000. title: i18n('notice'),
  9001. text: i18n('giveawayEnded'),
  9002. confirmButtonText: i18n('confirm'),
  9003. cancelButtonText: i18n('cancel'),
  9004. showCancelButton: true
  9005. }).then(({
  9006. value
  9007. }) => {
  9008. if (value) {
  9009. window.close();
  9010. }
  9011. });
  9012. }
  9013. return true;
  9014. } catch (error) {
  9015. throwError(error, 'Giveawaysu.checkLeftKey');
  9016. return false;
  9017. }
  9018. }
  9019. }
  9020. const website_GiveeClub = GiveeClub;
  9021. const defaultOptions = {
  9022. maxPoint: '99999999'
  9023. };
  9024. class OpiumPulses {
  9025. name = 'OpiumPulses';
  9026. options = {
  9027. ...defaultOptions,
  9028. ...GM_getValue('OpiumPulsesOptions')
  9029. };
  9030. maxPoints = 99999999;
  9031. myPoints = 0;
  9032. buttons = [ 'doFreeTask', 'doPointTask' ];
  9033. static test() {
  9034. return window.location.host === 'www.opiumpulses.com';
  9035. }
  9036. async after() {
  9037. try {
  9038. if (!this.#checkLogin()) {
  9039. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9040. }
  9041. this.maxPoints = parseInt(this.options.maxPoint, 10);
  9042. } catch (error) {
  9043. throwError(error, 'OpiumPulses.after');
  9044. }
  9045. }
  9046. async doFreeTask() {
  9047. try {
  9048. this.#toggleTask('FREE');
  9049. } catch (error) {
  9050. throwError(error, 'OpiumPulses.doFreeTask');
  9051. }
  9052. }
  9053. async doPointTask() {
  9054. try {
  9055. this.myPoints = parseInt($('.page-header__nav-func-user-nav-items.points-items').text().match(/[\d]+/gim)?.[0] || '0', 10);
  9056. this.#toggleTask('points');
  9057. } catch (error) {
  9058. throwError(error, 'OpiumPulses.doPointTask');
  9059. }
  9060. }
  9061. async #toggleTask(type) {
  9062. try {
  9063. const items = $(`.giveaways-page-item:contains('${type}'):not(:contains('ENTERED'))`);
  9064. for (const item of items) {
  9065. const needPoints = parseInt($(item).find('.giveaways-page-item-header-points').text().match(/[\d]+/gim)?.[0] || '999999', 10);
  9066. const name = $(item).find('.giveaways-page-item-footer-name').text().trim();
  9067. if (type === 'points' && needPoints > this.myPoints) {
  9068. scripts_echoLog({}).warning(`${i18n('noPoints')}: ${name}`);
  9069. } else if (type === 'points' && !needPoints) {
  9070. scripts_echoLog({}).warning(`${i18n('getNeedPointsFailed')}: ${name}`);
  9071. } else if (!(type === 'points' && needPoints > this.maxPoints)) {
  9072. const logStatus = scripts_echoLog({
  9073. text: `${i18n('joiningLottery')}<a href="${$(item).find('a.giveaways-page-item-img-btn-more').attr('href')}" target="_blank">${name}</a>...`
  9074. });
  9075. const aElement = $(item).find('a.giveaways-page-item-img-btn-enter:contains(\'enter\')');
  9076. if (aElement?.attr('onclick')?.includes('checkUser')) {
  9077. const giveawayId = aElement.attr('onclick')?.match(/[\d]+/)?.[0];
  9078. if (giveawayId) {
  9079. checkUser(giveawayId);
  9080. }
  9081. }
  9082. if (!aElement.attr('href')) {
  9083. logStatus.error('Error: No "href".');
  9084. continue;
  9085. }
  9086. const {
  9087. result,
  9088. statusText,
  9089. status,
  9090. data
  9091. } = await tools_httpRequest({
  9092. url: aElement.attr('href'),
  9093. method: 'GET'
  9094. });
  9095. if (result === 'Success') {
  9096. const {
  9097. result: result0,
  9098. statusText: statusText0,
  9099. status: status0,
  9100. data: data0
  9101. } = await tools_httpRequest({
  9102. url: data?.finalUrl,
  9103. method: 'GET'
  9104. });
  9105. if (data0?.responseText && /You've entered this giveaway/gim.test(data0.responseText)) {
  9106. logStatus.success();
  9107. const points = data0.responseText.match(/Points:[\s]*?([\d]+)/)?.[1];
  9108. if (type === 'points' && points) {
  9109. this.myPoints = parseInt(points, 10);
  9110. }
  9111. } else if (data0?.responseText && /You're not eligible to enter/gim.test(data0.responseText)) {
  9112. logStatus.error('You\'re not eligible to enter');
  9113. } else {
  9114. logStatus.error(`${result0}:${statusText0}(${status0})`);
  9115. }
  9116. } else {
  9117. logStatus.error(`${result}:${statusText}(${status})`);
  9118. }
  9119. }
  9120. }
  9121. scripts_echoLog({
  9122. text: '-----END-----'
  9123. });
  9124. } catch (error) {
  9125. throwError(error, 'OpiumPulses.toggleTask');
  9126. }
  9127. }
  9128. init() {
  9129. return true;
  9130. }
  9131. classifyTask() {
  9132. return true;
  9133. }
  9134. #checkLogin() {
  9135. try {
  9136. if (!globalOptions.other.checkLogin) {
  9137. return true;
  9138. }
  9139. if ($('a[href*="/site/login"]').length > 1) {
  9140. window.open('/site/login', '_self');
  9141. }
  9142. return true;
  9143. } catch (error) {
  9144. throwError(error, 'OpiumPulses.checkLogin');
  9145. return false;
  9146. }
  9147. }
  9148. }
  9149. const website_OpiumPulses = OpiumPulses;
  9150. const external_dayjs_namespaceObject = dayjs;
  9151. var external_dayjs_default = __webpack_require__.n(external_dayjs_namespaceObject);
  9152. const leftKeyChecker = {
  9153. async classify(link) {
  9154. try {
  9155. if (/^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(link)) {
  9156. return await this.giveawaySu(link);
  9157. }
  9158. if (/^https?:\/\/givee\.club\/[\w]+?\/event\/[\d]+/.test(link)) {
  9159. return await this.giveeClub(link);
  9160. }
  9161. if (/^https?:\/\/gleam\.io\/.+?\/.+/.test(link)) {
  9162. return await this.gleam(link);
  9163. }
  9164. if (/^https?:\/\/www\.indiedb\.com\/giveaways\/.+/.test(link)) {
  9165. return await this.indieDb(link);
  9166. }
  9167. if (/^https?:\/\/key-hub\.eu\/giveaway\/[\d]+/.test(link)) {
  9168. return await this.keyhub(link);
  9169. }
  9170. if (/^https?:\/\/opquests\.com\/quests\/[\d]+/.test(link)) {
  9171. return await this.opquests(link);
  9172. }
  9173. if (/^https?:\/\/itch\.io\/s\/[\d]+?\/.*/.test(link)) {
  9174. return await this.itch(link);
  9175. }
  9176. return false;
  9177. } catch (error) {
  9178. throwError(error, 'leftKeyChecker.classify');
  9179. return false;
  9180. }
  9181. },
  9182. async giveawaySu(link) {
  9183. try {
  9184. const {
  9185. result,
  9186. data
  9187. } = await tools_httpRequest({
  9188. url: link,
  9189. method: 'GET'
  9190. });
  9191. if (result === 'Success' && data?.status === 200) {
  9192. if (data.responseText.includes('class="steam-login"')) {
  9193. return false;
  9194. }
  9195. if (data.responseText.includes('class="giveaway-ended"')) {
  9196. return 'Ended';
  9197. }
  9198. return 'Active';
  9199. }
  9200. return false;
  9201. } catch (error) {
  9202. throwError(error, 'leftKeyChecker.giveawaySu');
  9203. return false;
  9204. }
  9205. },
  9206. async giveeClub(link) {
  9207. try {
  9208. const {
  9209. result,
  9210. data
  9211. } = await tools_httpRequest({
  9212. url: link,
  9213. method: 'GET'
  9214. });
  9215. if (result === 'Success' && data?.status === 200) {
  9216. if (data.responseText.includes('class="event-winner"')) {
  9217. return 'Won';
  9218. }
  9219. if (data.responseText.includes('class="event-ended"')) {
  9220. return 'Ended';
  9221. }
  9222. return 'Active';
  9223. }
  9224. return false;
  9225. } catch (error) {
  9226. throwError(error, 'leftKeyChecker.giveeClub');
  9227. return false;
  9228. }
  9229. },
  9230. async gleam(link) {
  9231. try {
  9232. const {
  9233. result,
  9234. data
  9235. } = await tools_httpRequest({
  9236. url: link,
  9237. method: 'GET'
  9238. });
  9239. if (result === 'Success' && data?.status === 200) {
  9240. if (/incentives&quot;:{&quot;[\d]+?&quot;:\[&quot;.+?&quot;\]/.test(data.responseText)) {
  9241. return 'Won';
  9242. }
  9243. const campaignDiv = data.responseText.match(/<div class='popup-blocks-container'[\w\W]+?'>/)?.[0];
  9244. if (!campaignDiv) {
  9245. return false;
  9246. }
  9247. const campaignString = $(campaignDiv).attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  9248. if (!campaignString) {
  9249. return false;
  9250. }
  9251. const {
  9252. campaign
  9253. } = JSON.parse(campaignString);
  9254. if (campaign.banned) {
  9255. return 'Banned';
  9256. }
  9257. if (campaign.finished) {
  9258. return 'Ended';
  9259. }
  9260. if (campaign.paused) {
  9261. return 'Paused';
  9262. }
  9263. if (new Date().getTime() < campaign.starts_at * 1e3) {
  9264. return 'NotStart';
  9265. }
  9266. return 'Active';
  9267. }
  9268. return false;
  9269. } catch (error) {
  9270. throwError(error, 'leftKeyChecker.gleam');
  9271. return false;
  9272. }
  9273. },
  9274. async indieDb(link) {
  9275. try {
  9276. const {
  9277. result,
  9278. data
  9279. } = await tools_httpRequest({
  9280. url: link,
  9281. method: 'GET'
  9282. });
  9283. if (result === 'Success' && data?.status === 200) {
  9284. if (data.responseText.includes('Congrats you WON')) {
  9285. return 'Won';
  9286. }
  9287. if (data.responseText.includes('Giveaway is closed') || data.responseText.includes('next time')) {
  9288. return 'Ended';
  9289. }
  9290. return 'Active';
  9291. }
  9292. return false;
  9293. } catch (error) {
  9294. throwError(error, 'leftKeyChecker.indieDb');
  9295. return false;
  9296. }
  9297. },
  9298. async keyhub(link) {
  9299. try {
  9300. const {
  9301. result,
  9302. data
  9303. } = await tools_httpRequest({
  9304. url: link,
  9305. method: 'GET'
  9306. });
  9307. if (result === 'Success' && data?.status === 200) {
  9308. const keysleft = data.responseText.match(/<span id="keysleft">([\d]+?)<\/span>/)?.[1];
  9309. if (!keysleft) {
  9310. return false;
  9311. }
  9312. if (keysleft === '0') {
  9313. return 'Ended';
  9314. }
  9315. return `Active(${keysleft})`;
  9316. }
  9317. return false;
  9318. } catch (error) {
  9319. throwError(error, 'leftKeyChecker.keyhub');
  9320. return false;
  9321. }
  9322. },
  9323. async opquests(link) {
  9324. try {
  9325. const {
  9326. result,
  9327. data
  9328. } = await tools_httpRequest({
  9329. url: link,
  9330. method: 'GET'
  9331. });
  9332. if (result === 'Success' && data?.status === 200) {
  9333. const keysleft = data.responseText.match(/<div class="">[\s]*?([\d]+?)[\s]*?of/)?.[1];
  9334. if (!keysleft) {
  9335. return false;
  9336. }
  9337. if (keysleft === '0') {
  9338. return 'Ended';
  9339. }
  9340. return `Active(${keysleft})`;
  9341. } else if (data?.status === 404) {
  9342. return 'Ended';
  9343. }
  9344. return false;
  9345. } catch (error) {
  9346. throwError(error, 'leftKeyChecker.opquests');
  9347. return false;
  9348. }
  9349. },
  9350. async itch(link) {
  9351. try {
  9352. const {
  9353. result,
  9354. data
  9355. } = await tools_httpRequest({
  9356. url: link,
  9357. method: 'GET'
  9358. });
  9359. if (result === 'Success' && data?.status === 200) {
  9360. const endDate = data.responseText.match(/{"start_date":"[0-9A-Z-:]+?".*?"end_date":"([0-9A-Z-:]+?)".*?}/)?.[1];
  9361. if (!endDate) {
  9362. return false;
  9363. }
  9364. if (new Date().getTime() > new Date(endDate).getTime()) {
  9365. return 'Ended';
  9366. }
  9367. return `Active(${external_dayjs_default()(endDate).format('YYYY-MM-DD HH:mm:ss')})`;
  9368. }
  9369. return false;
  9370. } catch (error) {
  9371. throwError(error, 'leftKeyChecker.itch');
  9372. return false;
  9373. }
  9374. }
  9375. };
  9376. const website_leftKeyChecker = leftKeyChecker;
  9377. const Keylol_defaultTasksTemplate = {
  9378. steam: {
  9379. groupLinks: [],
  9380. wishlistLinks: [],
  9381. curatorLinks: [],
  9382. curatorLikeLinks: [],
  9383. followLinks: [],
  9384. forumLinks: [],
  9385. announcementLinks: [],
  9386. workshopVoteLinks: [],
  9387. licenseLinks: []
  9388. },
  9389. discord: {
  9390. serverLinks: []
  9391. },
  9392. instagram: {
  9393. userLinks: []
  9394. },
  9395. vk: {
  9396. nameLinks: []
  9397. },
  9398. twitch: {
  9399. channelLinks: []
  9400. },
  9401. reddit: {
  9402. redditLinks: []
  9403. },
  9404. twitter: {
  9405. userLinks: [],
  9406. retweetLinks: []
  9407. },
  9408. youtube: {
  9409. channelLinks: [],
  9410. likeLinks: []
  9411. }
  9412. };
  9413. const Keylol_defaultTasks = JSON.stringify(Keylol_defaultTasksTemplate);
  9414. class Keylol extends website_Website {
  9415. name = 'Keylol';
  9416. socialTasks = JSON.parse(Keylol_defaultTasks);
  9417. undoneTasks = JSON.parse(Keylol_defaultTasks);
  9418. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect' ];
  9419. static test() {
  9420. 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'));
  9421. }
  9422. init() {
  9423. return true;
  9424. }
  9425. after() {
  9426. try {
  9427. const selector = this.name === 'Keylol' ? '#postlist>div[id^="post_"]:first' : 'div.container';
  9428. const mainPost = $(selector);
  9429. const discordLinks = mainPost.find('a[href*="discord.com"]:visible');
  9430. const redditLinks = mainPost.find('a[href*="reddit.com"]:visible');
  9431. const insLinks = mainPost.find('a[href*="instagram.com"]:visible');
  9432. const twitterLinks = mainPost.find('a[href*="twitter.com"]:visible,a[href*="x.com"]:visible');
  9433. const twitchLinks = mainPost.find('a[href*="twitch.tv"]:visible');
  9434. const vkLinks = mainPost.find('a[href*="vk.com"]:visible');
  9435. const steamStoreLinks = mainPost.find('a[href*="store.steampowered.com"]:visible');
  9436. const steamCommunityLinks = mainPost.find('a[href*="steamcommunity.com"]:visible');
  9437. const ytbLinks = mainPost.find('a[href*="youtube.com"]:visible');
  9438. if (discordLinks.length > 0) {
  9439. for (const discordLink of discordLinks) {
  9440. const link = $(discordLink).attr('href');
  9441. if (!(link && /^https?:\/\/discord\.com\/invite\/.+/.test(link))) {
  9442. continue;
  9443. }
  9444. this.#addBtn(discordLink, 'discord', 'serverLinks', link);
  9445. }
  9446. }
  9447. if (redditLinks.length > 0) {
  9448. for (const redditLink of redditLinks) {
  9449. const link = $(redditLink).attr('href');
  9450. if (!(link && /^https?:\/\/www\.reddit\.com\/(r|user)\/.+/.test(link))) {
  9451. continue;
  9452. }
  9453. this.#addBtn(redditLink, 'reddit', 'redditLinks', link);
  9454. }
  9455. }
  9456. if (insLinks.length > 0) {
  9457. for (const insLink of insLinks) {
  9458. const link = $(insLink).attr('href');
  9459. if (!(link && /^https:\/\/www\.instagram\.com\/.+/.test(link))) {
  9460. continue;
  9461. }
  9462. this.#addBtn(insLink, 'instagram', 'userLinks', link);
  9463. }
  9464. }
  9465. if (twitterLinks.length > 0) {
  9466. for (const twitterLink of twitterLinks) {
  9467. const link = $(twitterLink).attr('href');
  9468. if (!(link && /^https:\/\/twitter\.com\/.+/.test(link))) {
  9469. continue;
  9470. }
  9471. if (/https:\/\/twitter\.com\/.*?\/status\/[\d]+/.test(link)) {
  9472. this.#addBtn(twitterLink, 'twitter', 'retweetLinks', link);
  9473. } else {
  9474. this.#addBtn(twitterLink, 'twitter', 'userLinks', link);
  9475. }
  9476. }
  9477. }
  9478. if (twitchLinks.length > 0) {
  9479. for (const twitchLink of twitchLinks) {
  9480. const link = $(twitchLink).attr('href');
  9481. if (!(link && /^https:\/\/(www\.)?twitch\.tv\/.+/.test(link))) {
  9482. continue;
  9483. }
  9484. this.#addBtn(twitchLink, 'twitch', 'channelLinks', link);
  9485. }
  9486. }
  9487. if (vkLinks.length > 0) {
  9488. for (const vkLink of vkLinks) {
  9489. const link = $(vkLink).attr('href');
  9490. if (!(link && /^https:\/\/vk\.com\/.+/.test(link))) {
  9491. continue;
  9492. }
  9493. this.#addBtn(vkLink, 'vk', 'nameLinks', link);
  9494. }
  9495. }
  9496. if (steamStoreLinks.length > 0) {
  9497. for (const steamStoreLink of steamStoreLinks) {
  9498. const link = $(steamStoreLink).attr('href');
  9499. if (!link) {
  9500. continue;
  9501. }
  9502. if (/curator\/[\d]+/.test(link)) {
  9503. this.#addBtn(steamStoreLink, 'steam', 'curatorLinks', link);
  9504. } else if (/(publisher|developer|franchise)\/.+/.test(link)) {
  9505. this.#addBtn(steamStoreLink, 'steam', 'curatorLikeLinks', link);
  9506. } else if (/news(hub)?\/app\/[\d]+\/view\/[\d]+/.test(link)) {
  9507. this.#addBtn(steamStoreLink, 'steam', 'announcementLinks', link);
  9508. } else if (/app\/[\d]+/.test(link)) {
  9509. this.#addBtn(steamStoreLink, 'steam', 'followLinks', link);
  9510. this.#addBtn(steamStoreLink, 'steam', 'wishlistLinks', link);
  9511. }
  9512. }
  9513. }
  9514. if (steamCommunityLinks.length > 0) {
  9515. for (const steamCommunityLink of steamCommunityLinks) {
  9516. const link = $(steamCommunityLink).attr('href');
  9517. if (!link) {
  9518. continue;
  9519. }
  9520. if (/groups\/.+/.test(link)) {
  9521. this.#addBtn(steamCommunityLink, 'steam', 'groupLinks', link);
  9522. } else if (/announcements\/detail\/[\d]+/.test(link)) {
  9523. this.#addBtn(steamCommunityLink, 'steam', 'announcementLinks', link);
  9524. }
  9525. }
  9526. }
  9527. if (ytbLinks.length > 0) {
  9528. for (const ytbLink of ytbLinks) {
  9529. const link = $(ytbLink).attr('href');
  9530. if (!link) {
  9531. continue;
  9532. }
  9533. this.#addBtn(ytbLink, 'youtube', 'channelLinks', link);
  9534. this.#addBtn(ytbLink, 'youtube', 'likeLinks', link);
  9535. }
  9536. }
  9537. 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');
  9538. if (giveawayLinks.length > 0) {
  9539. for (const giveawayLink of giveawayLinks) {
  9540. const link = $(giveawayLink).attr('href');
  9541. if (!link) {
  9542. continue;
  9543. }
  9544. website_leftKeyChecker.classify(link).then(status => {
  9545. if (!status) {
  9546. return;
  9547. }
  9548. if (/^Active/.test(status)) {
  9549. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status active" title="${i18n('Active')}">${status}</font>`);
  9550. return;
  9551. }
  9552. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status not-active" title="${i18n(status)}">${status}</font>`);
  9553. }).catch(error => {
  9554. throwError(error, 'keylol.after -> leftKeyChecker');
  9555. });
  9556. }
  9557. }
  9558. if (this.name === 'Keylol') {
  9559. const asfLinks = mainPost.find('a[href^="#asf"]:visible');
  9560. if (asfLinks.length > 0) {
  9561. for (const asfLink of asfLinks) {
  9562. const link = $(asfLink).attr('href');
  9563. if (!link) {
  9564. continue;
  9565. }
  9566. this.#addBtn($(`a[href="${link}"]`).after('<span style="color: #ccc; margin: 0 -5px 0 5px"> | </span>').next()[0], 'steam', 'licenseLinks', `appid-${link.replace('#asf', '')}`);
  9567. }
  9568. }
  9569. const subLinks = mainPost.find('a[href*="steamdb.info/sub/"]:visible');
  9570. if (subLinks.length > 0) {
  9571. for (const subLink of subLinks) {
  9572. const link = $(subLink).attr('href');
  9573. if (!link) {
  9574. continue;
  9575. }
  9576. const subid = link.match(/^https:\/\/steamdb\.info\/sub\/([\d]+)/)?.[1];
  9577. if (!subid) {
  9578. continue;
  9579. }
  9580. this.#addBtn(subLink, 'steam', 'licenseLinks', `subid-${subid}`);
  9581. }
  9582. }
  9583. const asfLinks2 = mainPost.find('.blockcode:contains("addlicense"):visible');
  9584. if (asfLinks2.length > 0) {
  9585. for (const asfLink of asfLinks2) {
  9586. const appid = [ ...asfLink.innerText.matchAll(/a(pp)?\/([\d]+)/g) ].map(matched => matched?.[2]).filter(id => id) || [];
  9587. if (appid.length > 0) {
  9588. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `appid-${appid.join(',')}`);
  9589. }
  9590. const subid = asfLink.innerText.match(/[\d]+/g)?.filter(matched => !appid.includes(matched));
  9591. if (!subid || subid.length === 0) {
  9592. continue;
  9593. }
  9594. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `subid-${subid.join(',')}`);
  9595. }
  9596. }
  9597. }
  9598. if ($('#threadindex').length > 0) {
  9599. const [ targetNode ] = $('#postlist').children('div[id^="post_"]');
  9600. const config = {
  9601. childList: true
  9602. };
  9603. const observer = new MutationObserver(() => {
  9604. observer.disconnect();
  9605. this.after();
  9606. });
  9607. observer.observe(targetNode, config);
  9608. }
  9609. } catch (error) {
  9610. throwError(error, 'keylol.after');
  9611. }
  9612. }
  9613. classifyTask(action) {
  9614. try {
  9615. this.socialTasks = JSON.parse(Keylol_defaultTasks);
  9616. this.undoneTasks = JSON.parse(Keylol_defaultTasks);
  9617. const selectedBtns = $('.auto-task-keylol[selected="selected"]:visible');
  9618. for (const btn of selectedBtns) {
  9619. const button = $(btn);
  9620. const social = button.attr('data-social');
  9621. const type = button.attr('data-type');
  9622. const link = button.attr('data-link');
  9623. if (!(social && type && link)) {
  9624. continue;
  9625. }
  9626. if (action === 'do') {
  9627. this.undoneTasks[social][type].push(link);
  9628. }
  9629. if (action === 'undo') {
  9630. this.socialTasks[social][type].push(link);
  9631. }
  9632. }
  9633. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9634. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9635. if (window.DEBUG) {
  9636. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9637. }
  9638. return true;
  9639. } catch (error) {
  9640. throwError(error, 'Keylol.classifyTask');
  9641. return false;
  9642. }
  9643. }
  9644. selectAll() {
  9645. try {
  9646. $('.auto-task-keylol:visible').attr('selected', 'selected');
  9647. } catch (error) {
  9648. throwError(error, 'Keylol.selectAll');
  9649. }
  9650. }
  9651. selectNone() {
  9652. try {
  9653. $('.auto-task-keylol:visible').removeAttr('selected');
  9654. } catch (error) {
  9655. throwError(error, 'Keylol.selectNone');
  9656. }
  9657. }
  9658. invertSelect() {
  9659. try {
  9660. $('.auto-task-keylol:visible').each((index, element) => {
  9661. element.getAttribute('selected') ? element.removeAttribute('selected') : element.setAttribute('selected', 'selected');
  9662. });
  9663. } catch (error) {
  9664. throwError(error, 'Keylol.invertSelect');
  9665. }
  9666. }
  9667. #addBtn(before, social, linkType, link) {
  9668. try {
  9669. $(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>`);
  9670. } catch (error) {
  9671. throwError(error, 'keylol.addBtn');
  9672. }
  9673. }
  9674. }
  9675. const website_Keylol = Keylol;
  9676. const Opquests_defaultTasks = {
  9677. steam: {
  9678. groupLinks: [],
  9679. wishlistLinks: [],
  9680. followLinks: [],
  9681. curatorLikeLinks: []
  9682. },
  9683. twitter: {
  9684. userLinks: [],
  9685. retweetLinks: []
  9686. }
  9687. };
  9688. class Opquests extends website_Website {
  9689. name = 'Opquests';
  9690. undoneTasks = {
  9691. ...Opquests_defaultTasks
  9692. };
  9693. buttons = [ 'doTask', 'verifyTask', 'getKey' ];
  9694. static test() {
  9695. return window.location.host === 'opquests.com';
  9696. }
  9697. async after() {
  9698. try {
  9699. if (!this.#checkLogin()) {
  9700. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9701. }
  9702. const opquestsVerifyTasks = GM_getValue('opquestsVerifyTasks') || [];
  9703. if (opquestsVerifyTasks.length > 0) {
  9704. const taskId = opquestsVerifyTasks.pop();
  9705. GM_setValue('opquestsVerifyTasks', opquestsVerifyTasks);
  9706. const [ verifyBtn ] = $(`#task_id[value="${taskId}"]`).parent().find('button[type="button"]').has('i.fa-check');
  9707. if (verifyBtn) {
  9708. verifyBtn.click();
  9709. return;
  9710. }
  9711. this.after();
  9712. return;
  9713. }
  9714. if (GM_getValue('opquestsVerifyTasks')) {
  9715. GM_deleteValue('opquestsVerifyTasks');
  9716. }
  9717. } catch (error) {
  9718. throwError(error, 'Opquests.after');
  9719. }
  9720. }
  9721. init() {
  9722. try {
  9723. const logStatus = scripts_echoLog({
  9724. text: i18n('initing')
  9725. });
  9726. if ($('a[href*="/auth/redirect"]').length > 0) {
  9727. window.open('/auth/redirect', '_self');
  9728. logStatus.warning(i18n('needLogin'));
  9729. return false;
  9730. }
  9731. if (!this.#getGiveawayId()) {
  9732. return false;
  9733. }
  9734. this.initialized = true;
  9735. logStatus.success();
  9736. return true;
  9737. } catch (error) {
  9738. throwError(error, 'Opquests.init');
  9739. return false;
  9740. }
  9741. }
  9742. async classifyTask(action) {
  9743. try {
  9744. if (action === 'undo') {
  9745. scripts_echoLog({
  9746. text: i18n('cannotUndo')
  9747. });
  9748. return false;
  9749. }
  9750. const logStatus = scripts_echoLog({
  9751. text: i18n('getTasksInfo')
  9752. });
  9753. const tasks = $('.w-full:contains("Validate") .items-center');
  9754. for (const task of tasks) {
  9755. const link = $(task).find('a:contains("Open")').attr('href');
  9756. const taskDes = $(task).find('div').eq(1).text().trim();
  9757. if (!link) {
  9758. continue;
  9759. }
  9760. if (/steamcommunity\.com\/groups\//.test(link)) {
  9761. this.undoneTasks.steam.groupLinks.push(link);
  9762. } else if (/store\.steampowered\.com\/app\//.test(link)) {
  9763. if (/wishlist/gim.test(taskDes)) {
  9764. this.undoneTasks.steam.wishlistLinks.push(link);
  9765. } else if (/follow/gim.test(taskDes)) {
  9766. this.undoneTasks.steam.followLinks.push(link);
  9767. }
  9768. } else if (/store\.steampowered\.com\/(publisher|developer|curator)\//.test(link) && /follow/gim.test(taskDes)) {
  9769. this.undoneTasks.steam.curatorLikeLinks.push(link);
  9770. } else if (link.includes('//x.com/') && /follow/gim.test(taskDes)) {
  9771. this.undoneTasks.twitter.userLinks.push(link);
  9772. } else if (link.includes('//x.com/') && link.includes('status') && /Repost/gim.test(taskDes)) {
  9773. this.undoneTasks.twitter.retweetLinks.push(link);
  9774. } else if (/clash.gg/.test(link)) {
  9775. scripts_echoLog({}).warning(`${i18n('unSupporttedTaskType')}: ${taskDes}(${link})`);
  9776. } else {
  9777. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  9778. }
  9779. }
  9780. logStatus.success();
  9781. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9782. if (window.DEBUG) {
  9783. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9784. }
  9785. return true;
  9786. } catch (error) {
  9787. throwError(error, 'Opquests.classifyTask');
  9788. return false;
  9789. }
  9790. }
  9791. async verifyTask() {
  9792. try {
  9793. if (!this.initialized) {
  9794. this.init();
  9795. }
  9796. const tasks = $.makeArray($('.items-center').has('input[name="task_id"]')).map(ele => $(ele).find('input[name="task_id"]').val());
  9797. GM_setValue('opquestsVerifyTasks', tasks);
  9798. await this.#confirm();
  9799. this.after();
  9800. return true;
  9801. } catch (error) {
  9802. throwError(error, 'Opquests.verifyTask');
  9803. return false;
  9804. }
  9805. }
  9806. async #confirm() {
  9807. try {
  9808. const logStatus = scripts_echoLog({
  9809. html: `<li>${i18n('confirmingTask')}...<font></font></li>`
  9810. });
  9811. const {
  9812. result,
  9813. statusText,
  9814. status,
  9815. data
  9816. } = await tools_httpRequest({
  9817. url: `https://opquests.com/quests/${this.giveawayId}?confirm=1`,
  9818. method: 'GET',
  9819. nochche: true,
  9820. headers: {
  9821. origin: 'https://opquests.com',
  9822. referer: `https://opquests.com/warning?id=${this.giveawayId}`
  9823. }
  9824. });
  9825. if (result === 'Success') {
  9826. if (data?.status === 200) {
  9827. logStatus.success();
  9828. return true;
  9829. }
  9830. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9831. return false;
  9832. }
  9833. logStatus.error(`${result}:${statusText}(${status})`);
  9834. return false;
  9835. } catch (error) {
  9836. throwError(error, 'Opquests.confirm');
  9837. return false;
  9838. }
  9839. }
  9840. async getKey(isButton) {
  9841. try {
  9842. const logStatus = scripts_echoLog({
  9843. text: i18n('gettingKey')
  9844. });
  9845. const {
  9846. result,
  9847. statusText,
  9848. status,
  9849. data
  9850. } = await tools_httpRequest({
  9851. url: 'https://opquests.com/keys',
  9852. method: 'GET'
  9853. });
  9854. if (result === 'Success') {
  9855. if (data?.responseText) {
  9856. const key = $(data?.responseText).find(`div.items-center:contains("${$('h1.font-bold').text().trim().replace(' Quest', '')}")`).find('div.font-bold').next().text();
  9857. if (!key) {
  9858. logStatus.error('Error: Key was not found');
  9859. if (isButton) {
  9860. window.open('https://opquests.com/keys', '_self');
  9861. }
  9862. return false;
  9863. }
  9864. logStatus.success();
  9865. scripts_echoLog({}).success(key);
  9866. return true;
  9867. }
  9868. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9869. return false;
  9870. }
  9871. logStatus.error(`${result}:${statusText}(${status})`);
  9872. return false;
  9873. } catch (error) {
  9874. throwError(error, 'Opquests.getGiveawayId');
  9875. return false;
  9876. }
  9877. }
  9878. #getGiveawayId() {
  9879. try {
  9880. const giveawayId = window.location.href.match(/quests\/([\d]+)/)?.[1];
  9881. if (giveawayId) {
  9882. this.giveawayId = giveawayId;
  9883. return true;
  9884. }
  9885. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  9886. return false;
  9887. } catch (error) {
  9888. throwError(error, 'Opquests.getGiveawayId');
  9889. return false;
  9890. }
  9891. }
  9892. #checkLogin() {
  9893. try {
  9894. if (!globalOptions.other.checkLogin) {
  9895. return true;
  9896. }
  9897. if ($('a[href*="/auth/redirect"]').length > 0) {
  9898. window.open('/auth/redirect', '_self');
  9899. }
  9900. return true;
  9901. } catch (error) {
  9902. throwError(error, 'Opquests.checkLogin');
  9903. return false;
  9904. }
  9905. }
  9906. }
  9907. const website_Opquests = Opquests;
  9908. const Gleam_defaultTasksTemplate = {
  9909. steam: {
  9910. groupLinks: [],
  9911. wishlistLinks: [],
  9912. followLinks: [],
  9913. curatorLinks: [],
  9914. curatorLikeLinks: []
  9915. },
  9916. twitter: {
  9917. userLinks: [],
  9918. retweetLinks: []
  9919. },
  9920. twitch: {
  9921. channelLinks: []
  9922. },
  9923. discord: {
  9924. serverLinks: []
  9925. },
  9926. youtube: {
  9927. channelLinks: []
  9928. },
  9929. extra: {
  9930. gleam: []
  9931. }
  9932. };
  9933. const Gleam_defaultTasks = JSON.stringify(Gleam_defaultTasksTemplate);
  9934. class Gleam extends website_Website {
  9935. name = 'Gleam';
  9936. undoneTasks = JSON.parse(Gleam_defaultTasks);
  9937. socialTasks = JSON.parse(Gleam_defaultTasks);
  9938. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  9939. static test() {
  9940. return window.location.host === 'gleam.io';
  9941. }
  9942. before() {
  9943. try {
  9944. unsafeWindow.confirm = () => {};
  9945. unsafeWindow.alert = () => {};
  9946. unsafeWindow.prompt = () => {};
  9947. } catch (error) {
  9948. throwError(error, 'Gleam.before');
  9949. }
  9950. }
  9951. async after() {
  9952. try {
  9953. if (window.location.search.includes('8b07d23f4bfa65f9')) {
  9954. const checkComplete = setInterval(() => {
  9955. if ($('.entry-content .entry-method i.fa-check').length > 0) {
  9956. clearInterval(checkComplete);
  9957. window.close();
  9958. }
  9959. });
  9960. for (const task of $('.entry-content .entry-method')) {
  9961. const taskInfo = $(task).find('.user-links');
  9962. const expandInfo = $(task).find('.expandable');
  9963. const aElements = expandInfo.find('a.btn,a:contains(Continue),button:contains(Continue)');
  9964. if (aElements.length > 0) {
  9965. for (const element of aElements) {
  9966. const $element = $(element);
  9967. const href = $element.attr('href');
  9968. $element.removeAttr('href')[0].click();
  9969. $element.attr('href', href);
  9970. await delay(1e3);
  9971. }
  9972. }
  9973. taskInfo[0].click();
  9974. await delay(1e3);
  9975. }
  9976. scripts_echoLog({}).warning(i18n('gleamTaskNotice'));
  9977. } else if (!await this.#checkLeftKey()) {
  9978. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  9979. }
  9980. } catch (error) {
  9981. throwError(error, 'Gleam.after');
  9982. }
  9983. }
  9984. init() {
  9985. try {
  9986. const logStatus = scripts_echoLog({
  9987. text: i18n('initing')
  9988. });
  9989. if (!this.#getGiveawayId()) {
  9990. return false;
  9991. }
  9992. this.initialized = true;
  9993. logStatus.success();
  9994. return true;
  9995. } catch (error) {
  9996. throwError(error, 'Gleam.init');
  9997. return false;
  9998. }
  9999. }
  10000. async classifyTask(action) {
  10001. try {
  10002. const logStatus = scripts_echoLog({
  10003. text: i18n('getTasksInfo')
  10004. });
  10005. if (action === 'undo') {
  10006. this.socialTasks = GM_getValue(`gleamTasks-${this.giveawayId}`)?.tasks || JSON.parse(Gleam_defaultTasks);
  10007. }
  10008. const tasks = $('.entry-content .entry-method');
  10009. for (const task of tasks) {
  10010. const $task = $(task);
  10011. if (action === 'do' && $task.find('i.fa-question').length === 0) {
  10012. continue;
  10013. }
  10014. const socialIcon = $task.find('.icon-wrapper i');
  10015. const taskInfo = $task.find('.user-links');
  10016. const taskText = taskInfo.text().trim();
  10017. const expandInfo = $task.find('.expandable');
  10018. const aElements = expandInfo.find('a.btn');
  10019. if (aElements.length > 0) {
  10020. for (const element of aElements) {
  10021. const $element = $(element);
  10022. const href = $element.attr('href');
  10023. $element.removeAttr('href')[0].click();
  10024. $element.attr('href', href);
  10025. }
  10026. }
  10027. if (socialIcon.hasClass('fa-twitter') || socialIcon.hasClass('fa-x-twitter')) {
  10028. const link = $task.find('a[href^="https://twitter.com/"],a[href^="https://x.com/"]').attr('href');
  10029. if (!link) {
  10030. continue;
  10031. }
  10032. if (/follow/gi.test(taskText)) {
  10033. if (action === 'undo') {
  10034. this.socialTasks.twitter.userLinks.push(link);
  10035. }
  10036. if (action === 'do') {
  10037. this.undoneTasks.twitter.userLinks.push(link);
  10038. }
  10039. } else if (/retweet/gim.test(taskText)) {
  10040. if (action === 'undo') {
  10041. this.socialTasks.twitter.retweetLinks.push(link);
  10042. }
  10043. if (action === 'do') {
  10044. this.undoneTasks.twitter.retweetLinks.push(link);
  10045. }
  10046. }
  10047. } else if (socialIcon.hasClass('fa-twitch')) {
  10048. if (/follow/gim.test(taskText)) {
  10049. const link = $task.find('a[href^="https://twitch.tv/"]').attr('href');
  10050. if (!link) {
  10051. continue;
  10052. }
  10053. if (action === 'undo') {
  10054. this.socialTasks.twitch.channelLinks.push(link);
  10055. }
  10056. if (action === 'do') {
  10057. this.undoneTasks.twitch.channelLinks.push(link);
  10058. }
  10059. }
  10060. } else if (socialIcon.hasClass('fa-discord')) {
  10061. if (/join/gim.test(taskText)) {
  10062. let link = $task.find('a[href^="https://discord.com/invite/"]').attr('href');
  10063. if (!link) {
  10064. const ggLink = $task.find('a[href^="https://discord.gg/"]').attr('href')?.match(/discord\.gg\/([^/]+)/)?.[1];
  10065. if (!ggLink) {
  10066. continue;
  10067. }
  10068. link = `https://discord.com/invite/${ggLink}`;
  10069. }
  10070. if (action === 'undo') {
  10071. this.socialTasks.discord.serverLinks.push(link);
  10072. }
  10073. if (action === 'do') {
  10074. this.undoneTasks.discord.serverLinks.push(link);
  10075. }
  10076. }
  10077. } else if (socialIcon.hasClass('fa-external-link-square-alt')) {
  10078. continue;
  10079. } else if (socialIcon.hasClass('fa-youtube')) {
  10080. if (/subscribe/gim.test(taskText)) {
  10081. const link = $task.find('a[href^="https://www.youtube.com/channel/"]').attr('href');
  10082. if (!link) {
  10083. continue;
  10084. }
  10085. if (action === 'undo') {
  10086. this.socialTasks.youtube.channelLinks.push(link);
  10087. }
  10088. if (action === 'do') {
  10089. this.undoneTasks.youtube.channelLinks.push(link);
  10090. }
  10091. }
  10092. } else if (socialIcon.attr('class')?.includes('steam')) {
  10093. if (/join.*group/gi.test(taskText)) {
  10094. const link = $task.find('a[href^="https://steamcommunity.com/groups/"]').attr('href');
  10095. if (!link) {
  10096. continue;
  10097. }
  10098. if (action === 'undo') {
  10099. this.socialTasks.steam.groupLinks.push(link);
  10100. }
  10101. if (action === 'do') {
  10102. this.undoneTasks.steam.groupLinks.push(link);
  10103. }
  10104. } else if (/follow.*curator/gi.test(taskText)) {
  10105. const link = $task.find('a[href^="https://store.steampowered.com/curator/"]').attr('href');
  10106. if (!link) {
  10107. continue;
  10108. }
  10109. if (action === 'undo') {
  10110. this.socialTasks.steam.curatorLinks.push(link);
  10111. }
  10112. if (action === 'do') {
  10113. this.undoneTasks.steam.curatorLinks.push(link);
  10114. }
  10115. }
  10116. } else if (socialIcon.hasClass('fa-bullhorn') && /Complete|Increase/gi.test(taskText)) {
  10117. if (action !== 'do') {
  10118. continue;
  10119. }
  10120. const gleamLink = await this.#getGleamLink(taskText);
  10121. if (!gleamLink) {
  10122. continue;
  10123. }
  10124. this.undoneTasks.extra.gleam.push(gleamLink);
  10125. } 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 {
  10126. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskText}`);
  10127. }
  10128. }
  10129. logStatus.success();
  10130. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  10131. this.socialTasks = this.uniqueTasks(this.socialTasks);
  10132. if (window.DEBUG) {
  10133. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  10134. }
  10135. GM_setValue(`gleamTasks-${this.giveawayId}`, {
  10136. tasks: this.socialTasks,
  10137. time: new Date().getTime()
  10138. });
  10139. return true;
  10140. } catch (error) {
  10141. throwError(error, 'Gleam.classifyTask');
  10142. return false;
  10143. }
  10144. }
  10145. async extraDoTask({
  10146. gleam
  10147. }) {
  10148. try {
  10149. const pro = [];
  10150. for (const link of gleam) {
  10151. pro.push(this.#doGleamTask(link));
  10152. }
  10153. return Promise.all(pro).then(() => true);
  10154. } catch (error) {
  10155. throwError(error, 'Gleam.extraDoTask');
  10156. return false;
  10157. }
  10158. }
  10159. async verifyTask() {
  10160. try {
  10161. scripts_echoLog({
  10162. text: `${i18n('verifyingTask')}...`
  10163. });
  10164. const tasks = $('.entry-content .entry-method');
  10165. unsafeWindow._OxA = '_OxA';
  10166. for (const task of tasks) {
  10167. if ($('[campaign-key="campaign.key"]').length > 0) {
  10168. return scripts_echoLog({
  10169. text: i18n('campaign')
  10170. });
  10171. }
  10172. const $task = $(task);
  10173. if ($task.find('i.fa-question').length === 0) {
  10174. continue;
  10175. }
  10176. const taskInfo = $task.find('.user-links');
  10177. taskInfo[0].click();
  10178. const aElements = $task.find('.expandable').find('a.btn');
  10179. if (aElements.length > 0) {
  10180. for (const element of aElements) {
  10181. const $element = $(element);
  10182. const href = $element.attr('href');
  10183. $element.removeAttr('href')[0].click();
  10184. $element.attr('href', href);
  10185. }
  10186. }
  10187. unsafeWindow.$hookTimer?.setSpeed(1e3);
  10188. const visitBtn = $task.find('.expandable').find('span:contains(more seconds),button:contains(more seconds)').filter(':visible');
  10189. if (visitBtn.length > 0 && unsafeWindow.$hookTimer) {
  10190. const newTab = GM_openInTab('', {
  10191. active: true
  10192. });
  10193. await delay(1e3);
  10194. newTab?.close();
  10195. window.focus();
  10196. }
  10197. await delay(3e3);
  10198. unsafeWindow.$hookTimer?.setSpeed(1);
  10199. const expandInfo = $task.find('.expandable');
  10200. const [ input ] = expandInfo.find('input');
  10201. if (input) {
  10202. const evt = new Event('input', {
  10203. bubbles: true,
  10204. cancelable: true,
  10205. composed: true
  10206. });
  10207. const valuelimit = [ ...expandInfo.text().matchAll(/"(.+?)"/g) ].at(-1)?.[1];
  10208. input.value = valuelimit || 'vloot';
  10209. input.dispatchEvent(evt);
  10210. await delay(1e3);
  10211. }
  10212. await this.#checkSync();
  10213. const continueBtn = $task.find('.expandable').find('span:contains(Continue),button:contains(Continue)');
  10214. for (const button of continueBtn) {
  10215. button.click();
  10216. await delay(500);
  10217. await this.#checkSync();
  10218. }
  10219. }
  10220. scripts_echoLog({
  10221. text: i18n('verifiedGleamTasks')
  10222. });
  10223. } catch (error) {
  10224. throwError(error, 'Gleam.verifyTask');
  10225. return false;
  10226. }
  10227. }
  10228. async #checkSync() {
  10229. try {
  10230. return await new Promise(resolve => {
  10231. const checker = setInterval(() => {
  10232. if ($('.entry-content .entry-method i.fa-sync').length === 0) {
  10233. clearInterval(checker);
  10234. resolve(true);
  10235. }
  10236. }, 500);
  10237. });
  10238. } catch (error) {
  10239. throwError(error, 'Gleam.checkSync');
  10240. return false;
  10241. }
  10242. }
  10243. async #doGleamTask(link) {
  10244. try {
  10245. const logStatus = scripts_echoLog({
  10246. text: i18n('doingGleamTask')
  10247. });
  10248. return await new Promise(resolve => {
  10249. GM_openInTab(`${link}?8b07d23f4bfa65f9`, {
  10250. active: true,
  10251. insert: true,
  10252. setParent: true
  10253. }).onclose = () => {
  10254. logStatus.success();
  10255. resolve(true);
  10256. };
  10257. });
  10258. } catch (error) {
  10259. throwError(error, 'Gleam.doGleamTask');
  10260. return false;
  10261. }
  10262. }
  10263. #getGiveawayId() {
  10264. try {
  10265. const giveawayId = window.location.pathname;
  10266. if (giveawayId) {
  10267. this.giveawayId = giveawayId;
  10268. return true;
  10269. }
  10270. scripts_echoLog({
  10271. text: i18n('getFailed', 'GiveawayId')
  10272. });
  10273. return false;
  10274. } catch (error) {
  10275. throwError(error, 'Gleam.getGiveawayId');
  10276. return false;
  10277. }
  10278. }
  10279. async #getGleamLink(title) {
  10280. try {
  10281. const logStatus = scripts_echoLog({
  10282. text: i18n('gettingGleamLink')
  10283. });
  10284. const {
  10285. result,
  10286. statusText,
  10287. status,
  10288. data
  10289. } = await tools_httpRequest({
  10290. url: 'https://www.vloot.io/api/v1/giveaways',
  10291. method: 'GET',
  10292. responseType: 'json'
  10293. });
  10294. if (result === 'Success') {
  10295. if (data?.status === 200 && data?.response?.Success === true && data?.response?.Data) {
  10296. const {
  10297. link
  10298. } = data.response.Data.find(giveaway => title.replace(/[\s]/g, '').toLowerCase().includes(giveaway.title.replace(/[\s]/g, '').toLowerCase())) || {};
  10299. if (link) {
  10300. logStatus.success();
  10301. return link;
  10302. }
  10303. logStatus.error(`Error:${i18n('getLinkFailed')}`);
  10304. return false;
  10305. }
  10306. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10307. return false;
  10308. }
  10309. logStatus.error(`${result}:${statusText}(${status})`);
  10310. return false;
  10311. } catch (error) {
  10312. throwError(error, 'Gleam.getGleamLink');
  10313. return false;
  10314. }
  10315. }
  10316. async #checkLeftKey() {
  10317. try {
  10318. if (!globalOptions.other.checkLeftKey) {
  10319. return true;
  10320. }
  10321. const campaignString = $('div.popup-blocks-container').attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  10322. if (!campaignString) {
  10323. return false;
  10324. }
  10325. const {
  10326. campaign,
  10327. incentive
  10328. } = JSON.parse(campaignString);
  10329. const controllerString = $('div.campaign.reward').attr('ng-init')?.match(/initContestant\(([\w\W]+?)\);/)?.[1];
  10330. let ownedKey = false;
  10331. if (controllerString) {
  10332. if (JSON.parse(controllerString).contestant?.claims?.incentives?.[incentive.id]?.length) {
  10333. ownedKey = true;
  10334. }
  10335. }
  10336. if (campaign.banned || campaign.finished && !ownedKey || campaign.paused || new Date().getTime() < campaign.starts_at * 1e3) {
  10337. await external_Swal_default().fire({
  10338. icon: 'warning',
  10339. title: i18n('notice'),
  10340. text: i18n('giveawayNotWork'),
  10341. confirmButtonText: i18n('confirm'),
  10342. cancelButtonText: i18n('cancel'),
  10343. showCancelButton: true
  10344. }).then(({
  10345. value
  10346. }) => {
  10347. if (value) {
  10348. window.close();
  10349. }
  10350. });
  10351. }
  10352. return true;
  10353. } catch (error) {
  10354. throwError(error, 'Gleam.checkLeftKey');
  10355. return false;
  10356. }
  10357. }
  10358. }
  10359. const website_Gleam = Gleam;
  10360. const SweepWidget_defaultOptions = {
  10361. username: '',
  10362. email: ''
  10363. };
  10364. class SweepWidget extends website_Website {
  10365. name = 'SweepWidget';
  10366. options = {
  10367. ...SweepWidget_defaultOptions,
  10368. ...GM_getValue('SweepWidgetOptions')
  10369. };
  10370. buttons = [ 'doTask' ];
  10371. static test() {
  10372. return /^https?:\/\/sweepwidget\.com\/view\/[\d]+/.test(window.location.href);
  10373. }
  10374. async after() {
  10375. try {
  10376. if (!this.#checkLogin()) {
  10377. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  10378. }
  10379. } catch (error) {
  10380. throwError(error, 'SweepWidget.after');
  10381. }
  10382. }
  10383. init() {
  10384. try {
  10385. const logStatus = scripts_echoLog({
  10386. text: i18n('initing')
  10387. });
  10388. if (!this.#checkLogin()) {
  10389. logStatus.warning(i18n('needLogin'));
  10390. return false;
  10391. }
  10392. if (!this.#getGiveawayId()) {
  10393. return false;
  10394. }
  10395. this.initialized = true;
  10396. logStatus.success();
  10397. return true;
  10398. } catch (error) {
  10399. throwError(error, 'SweepWidget.init');
  10400. return false;
  10401. }
  10402. }
  10403. classifyTask() {
  10404. return true;
  10405. }
  10406. async doTask() {
  10407. try {
  10408. if ($('#unlock_rewards_main_wrapper').length === 0) {
  10409. if ($('input[name="sw__login_name"]:visible').length > 0) {
  10410. $('input[name="sw__login_name"]').val(this.options.username);
  10411. }
  10412. if ($('input[name="sw__login_email"]:visible').length > 0) {
  10413. $('input[name="sw__login_email"]').val(this.options.email);
  10414. }
  10415. if ($('#sw_login_button:visible').length > 0) {
  10416. $('#sw_login_button')[0].click();
  10417. }
  10418. if (!await this.#checkEnter()) {
  10419. return false;
  10420. }
  10421. }
  10422. const logStatus = scripts_echoLog({
  10423. text: i18n('SweepWidgetNotice')
  10424. });
  10425. const tasks = $('#sw_inner_entry_methods_l2_wrapper>div.sw_entry');
  10426. for (const task of tasks) {
  10427. const $task = $(task);
  10428. if ($task.find('i.fa-check:visible').length > 0) {
  10429. continue;
  10430. }
  10431. const title = $task.find('.sw_text_inner');
  10432. title[0].click();
  10433. const aElement = $task.find('a.sw_link');
  10434. const link = aElement.attr('href');
  10435. aElement.attr('href', '#a').attr('target', '_self');
  10436. aElement[0]?.click();
  10437. await delay(300);
  10438. aElement.attr('href', link).attr('target', '_blank');
  10439. $task.find('input[type="text"]').val('test');
  10440. const verifyBtn = $task.find('input.sw_verify');
  10441. if (verifyBtn.prop('disabled') === true) {
  10442. title[0].click();
  10443. await delay(300);
  10444. title[0].click();
  10445. await delay(300);
  10446. }
  10447. $task.find('input.sw_verify').removeAttr('disabled')[0]?.click();
  10448. await this.#checkFinish($task);
  10449. await delay(parseInt(`${Math.random() * (3e3 - 1e3 + 1) + 1e3}`, 10));
  10450. }
  10451. logStatus.success();
  10452. return true;
  10453. } catch (error) {
  10454. throwError(error, 'SweepWidget.doTask');
  10455. return false;
  10456. }
  10457. }
  10458. #checkLogin() {
  10459. try {
  10460. if ($('#twitter_login_button').length > 0) {
  10461. $('#twitter_login_button')[0].click();
  10462. }
  10463. return true;
  10464. } catch (error) {
  10465. throwError(error, 'SweepWidget.checkLogin');
  10466. return false;
  10467. }
  10468. }
  10469. #getGiveawayId() {
  10470. try {
  10471. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  10472. if (giveawayId) {
  10473. this.giveawayId = giveawayId;
  10474. return true;
  10475. }
  10476. scripts_echoLog({
  10477. text: i18n('getFailed', 'GiveawayId')
  10478. });
  10479. return false;
  10480. } catch (error) {
  10481. throwError(error, 'SweepWidget.getGiveawayId');
  10482. return false;
  10483. }
  10484. }
  10485. async #checkEnter() {
  10486. try {
  10487. return new Promise(resolve => {
  10488. const checker = setInterval(() => {
  10489. if ($('#unlock_rewards_main_wrapper').length > 0) {
  10490. clearInterval(checker);
  10491. resolve(true);
  10492. }
  10493. }, 500);
  10494. });
  10495. } catch (error) {
  10496. throwError(error, 'SweepWidget.checkEnter');
  10497. return false;
  10498. }
  10499. }
  10500. async #checkFinish($task) {
  10501. try {
  10502. return new Promise(resolve => {
  10503. const checker = setInterval(() => {
  10504. if ($task.find('i.fa-check:visible').length > 0 || $task.find('.sw_entry_input:visible').length === 0) {
  10505. clearInterval(checker);
  10506. resolve(true);
  10507. }
  10508. }, 500);
  10509. });
  10510. } catch (error) {
  10511. throwError(error, 'SweepWidget.checkFinish');
  10512. return false;
  10513. }
  10514. }
  10515. }
  10516. const website_SweepWidget = SweepWidget;
  10517. const defaultWhiteList = {
  10518. discord: {
  10519. servers: []
  10520. },
  10521. instagram: {
  10522. users: []
  10523. },
  10524. twitch: {
  10525. channels: []
  10526. },
  10527. twitter: {
  10528. users: [],
  10529. retweets: [],
  10530. likes: []
  10531. },
  10532. vk: {
  10533. names: []
  10534. },
  10535. youtube: {
  10536. channels: [],
  10537. likes: []
  10538. },
  10539. reddit: {
  10540. reddits: []
  10541. },
  10542. steam: {
  10543. groups: [],
  10544. officialGroups: [],
  10545. wishlists: [],
  10546. follows: [],
  10547. forums: [],
  10548. workshops: [],
  10549. curators: [],
  10550. workshopVotes: [],
  10551. curatorLikes: [],
  10552. announcements: [],
  10553. licenses: [],
  10554. playtests: []
  10555. }
  10556. };
  10557. const link2id = async function(type) {
  10558. try {
  10559. const link = $('#socialLink').val();
  10560. let id = '';
  10561. switch (type) {
  10562. case 'discord.servers':
  10563. id = link.match(/invite\/(.+)/)?.[1] || '';
  10564. break;
  10565.  
  10566. case 'instagram.users':
  10567. id = link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1] || '';
  10568. break;
  10569.  
  10570. case 'twitch.channels':
  10571. id = link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2] || '';
  10572. break;
  10573.  
  10574. case 'twitter.users':
  10575. id = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || '';
  10576. break;
  10577.  
  10578. case 'twitter.retweets':
  10579. id = link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1] || '';
  10580. break;
  10581.  
  10582. case 'vk.names':
  10583. id = link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1] || '';
  10584. break;
  10585.  
  10586. case 'youtube.channels':
  10587. id = (await getInfo(link, 'channel'))?.params?.channelId || '';
  10588. break;
  10589.  
  10590. case 'youtube.likes':
  10591. id = (await getInfo(link, 'likeVideo'))?.params?.videoId || '';
  10592. break;
  10593.  
  10594. case 'reddit.reddits':
  10595. id = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1] || link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1] || '';
  10596. break;
  10597.  
  10598. case 'steam.groups':
  10599. id = link.match(/groups\/(.+)\/?/)?.[1] || '';
  10600. break;
  10601.  
  10602. case 'steam.wishlists':
  10603. case 'steam.follows':
  10604. case 'steam.forums':
  10605. id = link.match(/app\/([\d]+)/)?.[1] || '';
  10606. break;
  10607.  
  10608. case 'steam.workshops':
  10609. id = link.match(/\?id=([\d]+)/)?.[1] || '';
  10610. break;
  10611.  
  10612. case 'steam.curators':
  10613. {
  10614. if (link.includes('curator')) {
  10615. id = link.match(/curator\/([\d]+)/)?.[1] || '';
  10616. } else {
  10617. const param = link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3);
  10618. if (!param || param.length !== 2) {
  10619. break;
  10620. }
  10621. const steam = new social_Steam();
  10622. if (await steam.init()) {
  10623. id = await steam.getCuratorId(param[0], param[1]) || '';
  10624. }
  10625. }
  10626. }
  10627. break;
  10628. }
  10629. return id;
  10630. } catch (error) {
  10631. throwError(error, 'link2id');
  10632. return i18n('getFailed', 'id');
  10633. }
  10634. };
  10635. const disabledType = {
  10636. steam: [ 'workshopVotes', 'curatorLikes', 'announcements' ],
  10637. twitter: [ 'likes' ]
  10638. };
  10639. const assignWhiteList = whiteList => {
  10640. try {
  10641. const newWhiteList = {};
  10642. for (const [ key, value ] of Object.entries(defaultWhiteList)) {
  10643. newWhiteList[key] = {
  10644. ...value,
  10645. ...whiteList[key]
  10646. };
  10647. }
  10648. return newWhiteList;
  10649. } catch (error) {
  10650. throwError(error, 'assignWhiteList');
  10651. return defaultWhiteList;
  10652. }
  10653. };
  10654. const whiteListOptions = function(showType) {
  10655. try {
  10656. const whiteList = assignWhiteList(GM_getValue('whiteList') || {});
  10657. let whiteListOptionsForm = `<form id="whiteListForm" class="auto-task-form">
  10658. <table class="auto-task-table"><thead><tr><td>${i18n('website')}</td><td>${i18n('type')}</td><td>${i18n('edit')}</td></tr></thead><tbody>`;
  10659. for (const [ social, types ] of Object.entries(whiteList)) {
  10660. 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('');
  10661. }
  10662. whiteListOptionsForm += '</tbody></table></form>';
  10663. if (showType === 'swal') {
  10664. external_Swal_default().fire({
  10665. title: i18n('whiteListOptions'),
  10666. html: whiteListOptionsForm,
  10667. showConfirmButton: false,
  10668. showCloseButton: true
  10669. });
  10670. } else {
  10671. $('body').append(`<h2>${i18n('whiteList')}</h2>${whiteListOptionsForm}`);
  10672. }
  10673. $('.editWhiteList').on('click', function() {
  10674. const value = $(this).attr('data-value');
  10675. if (!value) {
  10676. return;
  10677. }
  10678. const [ social, type ] = value.split('.');
  10679. if (!whiteList?.[social]?.[type]) {
  10680. scripts_echoLog({}).warning(i18n('whiteListNotFound', value));
  10681. return;
  10682. }
  10683. external_Swal_default().fire({
  10684. title: i18n('changeWhiteListOption', value),
  10685. input: 'textarea',
  10686. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10687. <button id="link2id" data-type="${value}" class="swal2-confirm swal2-styled">获取id</button>
  10688. <p style="margin-bottom:0 !important;">在下方填写白名单,每行一个</p>`,
  10689. inputValue: whiteList[social][type].join('\n'),
  10690. showConfirmButton: true,
  10691. confirmButtonText: i18n('save'),
  10692. showCancelButton: true,
  10693. cancelButtonText: i18n('close'),
  10694. showDenyButton: true,
  10695. denyButtonText: i18n('return')
  10696. }).then(({
  10697. isDenied,
  10698. isConfirmed,
  10699. value
  10700. }) => {
  10701. if (isDenied) {
  10702. if (showType === 'swal') {
  10703. whiteListOptions(showType);
  10704. }
  10705. return;
  10706. } else if (isConfirmed) {
  10707. whiteList[social][type] = value.split('\n');
  10708. GM_setValue('whiteList', whiteList);
  10709. external_Swal_default().fire({
  10710. title: i18n('changeWhiteListSuccess'),
  10711. icon: 'success'
  10712. });
  10713. }
  10714. });
  10715. $('#link2id').on('click', async function() {
  10716. const type = $(this).attr('data-type');
  10717. $('#socialLink').val(await link2id(type));
  10718. });
  10719. });
  10720. } catch (error) {
  10721. throwError(error, 'whiteListOptions');
  10722. }
  10723. };
  10724. const whiteList = whiteListOptions;
  10725. const setGistData = async (token, gistId, fileName, content) => {
  10726. try {
  10727. const logStatus = scripts_echoLog({
  10728. text: i18n('settingData')
  10729. });
  10730. const contentData = JSON.stringify({
  10731. files: {
  10732. [fileName]: {
  10733. content: JSON.stringify(content)
  10734. }
  10735. }
  10736. });
  10737. const {
  10738. result,
  10739. statusText,
  10740. status,
  10741. data
  10742. } = await tools_httpRequest({
  10743. url: `https://api.github.com/gists/${gistId}`,
  10744. headers: {
  10745. Accept: 'application/vnd.github.v3+json',
  10746. Authorization: `token ${token}`
  10747. },
  10748. data: contentData,
  10749. responseType: 'json',
  10750. method: 'POST',
  10751. timeout: 3e4
  10752. });
  10753. if (result === 'Success') {
  10754. if (data?.status === 200 && data.response.files?.[fileName]?.content === JSON.stringify(content)) {
  10755. logStatus.success();
  10756. return true;
  10757. }
  10758. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10759. return false;
  10760. }
  10761. logStatus.error(`${result}:${statusText}(${status})`);
  10762. return false;
  10763. } catch (error) {
  10764. throwError(error, 'setGistData');
  10765. return false;
  10766. }
  10767. };
  10768. const getGistData = async (token, gistId, fileName, test = false) => {
  10769. try {
  10770. const logStatus = scripts_echoLog({
  10771. text: i18n('gettingData')
  10772. });
  10773. const {
  10774. result,
  10775. statusText,
  10776. status,
  10777. data
  10778. } = await tools_httpRequest({
  10779. url: `https://api.github.com/gists/${gistId}`,
  10780. headers: {
  10781. Accept: 'application/vnd.github.v3+json',
  10782. Authorization: `token ${token}`
  10783. },
  10784. responseType: 'json',
  10785. method: 'GET',
  10786. timeout: 3e4
  10787. });
  10788. if (result === 'Success') {
  10789. if (data?.status === 200) {
  10790. const content = data.response?.files?.[fileName]?.content;
  10791. let formatedContent;
  10792. if (!content) {
  10793. logStatus.error(`Error:${i18n('noRemoteData')}`);
  10794. return false;
  10795. }
  10796. if (test) {
  10797. logStatus.success();
  10798. return true;
  10799. }
  10800. try {
  10801. formatedContent = JSON.parse(content);
  10802. } catch (error) {
  10803. logStatus.error(`Error:${i18n('errorRemoteDataFormat')}`);
  10804. return false;
  10805. }
  10806. logStatus.success();
  10807. return formatedContent;
  10808. }
  10809. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10810. return false;
  10811. }
  10812. logStatus.error(`${result}:${statusText}(${status})`);
  10813. return false;
  10814. } catch (error) {
  10815. throwError(error, 'getGistData');
  10816. return false;
  10817. }
  10818. };
  10819. const syncOptions = () => {
  10820. try {
  10821. const {
  10822. TOKEN,
  10823. GIST_ID,
  10824. FILE_NAME,
  10825. SYNC_HISTORY
  10826. } = GM_getValue('gistOptions') || {
  10827. TOKEN: '',
  10828. GIST_ID: '',
  10829. FILE_NAME: '',
  10830. SYNC_HISTORY: true
  10831. };
  10832. external_Swal_default().fire({
  10833. title: i18n('gistOptions'),
  10834. 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;">
  10835. ${i18n('upload2gist')}</button>` + `<button id="download-data" type="button" class="swal2-confirm swal2-styled" style="display: inline-block;">
  10836. ${i18n('downloadFromGist')}</button></p>`,
  10837. focusConfirm: false,
  10838. showLoaderOnConfirm: true,
  10839. 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>`,
  10840. preConfirm: async () => {
  10841. const token = $('#github-token').val();
  10842. const gistId = $('#gist-id').val();
  10843. const fileName = $('#file-name').val();
  10844. const syncHistory = $('#sync-history').prop('checked');
  10845. GM_setValue('gistOptions', {
  10846. TOKEN: token,
  10847. GIST_ID: gistId,
  10848. FILE_NAME: fileName,
  10849. SYNC_HISTORY: syncHistory
  10850. });
  10851. return await getGistData(token, gistId, fileName, true);
  10852. },
  10853. allowOutsideClick: () => !external_Swal_default().isLoading(),
  10854. confirmButtonText: i18n('saveAndTest'),
  10855. showCancelButton: true,
  10856. cancelButtonText: i18n('close')
  10857. }).then(({
  10858. value
  10859. }) => {
  10860. if (value) {
  10861. external_Swal_default().fire({
  10862. icon: 'success',
  10863. title: i18n('testSuccess')
  10864. }).then(syncOptions);
  10865. } else if (value !== undefined) {
  10866. external_Swal_default().fire({
  10867. icon: 'error',
  10868. title: i18n('testFailed')
  10869. }).then(syncOptions);
  10870. }
  10871. });
  10872. $('#upload-data').on('click', async () => {
  10873. const {
  10874. TOKEN,
  10875. GIST_ID,
  10876. FILE_NAME
  10877. } = GM_getValue('gistOptions') || {};
  10878. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10879. return external_Swal_default().fire({
  10880. icon: 'error',
  10881. title: i18n('saveAndTestNotice')
  10882. }).then(syncOptions);
  10883. }
  10884. external_Swal_default().fire({
  10885. icon: 'info',
  10886. title: i18n('processingData')
  10887. });
  10888. const data = {};
  10889. const names = GM_listValues();
  10890. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10891. for (const name of names) {
  10892. if (name === 'gistOptions' || /^[\w]+?Auth$/.test(name)) {
  10893. continue;
  10894. }
  10895. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10896. continue;
  10897. }
  10898. data[name] = GM_getValue(name);
  10899. }
  10900. external_Swal_default().update({
  10901. icon: 'info',
  10902. title: i18n('updatingData')
  10903. });
  10904. if (await setGistData(TOKEN, GIST_ID, FILE_NAME, data)) {
  10905. external_Swal_default().fire({
  10906. icon: 'success',
  10907. title: i18n('syncDataSuccess')
  10908. });
  10909. } else {
  10910. external_Swal_default().fire({
  10911. icon: 'error',
  10912. title: i18n('syncDataFailed')
  10913. });
  10914. }
  10915. });
  10916. $('#download-data').on('click', async () => {
  10917. const {
  10918. TOKEN,
  10919. GIST_ID,
  10920. FILE_NAME
  10921. } = GM_getValue('gistOptions') || {};
  10922. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10923. return external_Swal_default().fire({
  10924. icon: 'error',
  10925. title: i18n('saveAndTestNotice')
  10926. }).then(syncOptions);
  10927. }
  10928. external_Swal_default().fire({
  10929. icon: 'info',
  10930. title: i18n('downloadingData')
  10931. });
  10932. const data = await getGistData(TOKEN, GIST_ID, FILE_NAME);
  10933. if (!data) {
  10934. return external_Swal_default().fire({
  10935. icon: 'error',
  10936. title: i18n('checkedNoData')
  10937. }).then(syncOptions);
  10938. }
  10939. external_Swal_default().update({
  10940. icon: 'info',
  10941. title: i18n('savingData')
  10942. });
  10943. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10944. for (const [ name, value ] of Object.entries(data)) {
  10945. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10946. continue;
  10947. }
  10948. GM_setValue(name, value);
  10949. }
  10950. external_Swal_default().fire({
  10951. icon: 'success',
  10952. title: i18n('syncDataSuccess')
  10953. });
  10954. });
  10955. } catch (error) {
  10956. throwError(error, 'syncOptions');
  10957. }
  10958. };
  10959. const dataSync = syncOptions;
  10960. class Setting {
  10961. name = 'Setting';
  10962. buttons = [ 'saveGlobalOptions', 'syncData', 'tasksHistory' ];
  10963. syncData = dataSync;
  10964. tasksHistory() {
  10965. GM_openInTab('https://auto-task-v4.hclonely.com/history.html', {
  10966. active: true
  10967. });
  10968. }
  10969. static test() {
  10970. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/setting.html';
  10971. }
  10972. before() {
  10973. try {
  10974. $('body').html('').addClass('auto-task-options');
  10975. } catch (error) {
  10976. throwError(error, 'Setting.before');
  10977. }
  10978. }
  10979. after() {
  10980. try {
  10981. this.#environment();
  10982. changeGlobalOptions('page');
  10983. whiteList('page');
  10984. $('input[name="other.twitterVerifyId"]').after(`<button id="getTwitterUserId" type="button">${i18n('getTwitterUserId')}</button>`);
  10985. $('#getTwitterUserId').on('click', () => {
  10986. this.#getId('twitterUser');
  10987. });
  10988. $('input[name="other.youtubeVerifyChannel"]').after(`<button id="getYoutubeChannelId" type="button">${i18n('getYoutubeChannelId')}</button>`);
  10989. $('#getYoutubeChannelId').on('click', () => {
  10990. this.#getId('youtubeChannel');
  10991. });
  10992. $('input[name^="position"]').on('input', function() {
  10993. const type = $(this).attr('name').replace('position.', '');
  10994. const xLabel = 'rightleft';
  10995. const yLabel = 'topbottpm';
  10996. switch (type) {
  10997. case 'buttonSideX':
  10998. case 'buttonSideY':
  10999. case 'buttonDistance':
  11000. {
  11001. const distance = $('input[name="position.buttonDistance"]').val();
  11002. const sideX = $('input[name="position.buttonSideX"]').val();
  11003. const sideY = $('input[name="position.buttonSideY"]').val();
  11004. if (![ 'right', 'left' ].includes(sideX)) {
  11005. break;
  11006. }
  11007. if (![ 'top', 'bottom' ].includes(sideY)) {
  11008. break;
  11009. }
  11010. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  11011. break;
  11012. }
  11013. const distanceArr = distance.split(',');
  11014. $('#auto-task-buttons').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  11015. break;
  11016. }
  11017.  
  11018. case 'showButtonSideX':
  11019. case 'showButtonSideY':
  11020. case 'showButtonDistance':
  11021. {
  11022. const distance = $('input[name="position.showButtonDistance"]').val();
  11023. const sideX = $('input[name="position.showButtonSideX"]').val();
  11024. const sideY = $('input[name="position.showButtonSideY"]').val();
  11025. if (![ 'right', 'left' ].includes(sideX)) {
  11026. break;
  11027. }
  11028. if (![ 'top', 'bottom' ].includes(sideY)) {
  11029. break;
  11030. }
  11031. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  11032. break;
  11033. }
  11034. const distanceArr = distance.split(',');
  11035. $('div.show-button-div').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  11036. break;
  11037. }
  11038.  
  11039. case 'logSideX':
  11040. case 'logSideY':
  11041. case 'logDistance':
  11042. {
  11043. const distance = $('input[name="position.logDistance"]').val();
  11044. const sideX = $('input[name="position.logSideX"]').val();
  11045. const sideY = $('input[name="position.logSideY"]').val();
  11046. if (![ 'right', 'left' ].includes(sideX)) {
  11047. break;
  11048. }
  11049. if (![ 'top', 'bottom' ].includes(sideY)) {
  11050. break;
  11051. }
  11052. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  11053. break;
  11054. }
  11055. const distanceArr = distance.split(',');
  11056. $('#auto-task-info').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  11057. break;
  11058. }
  11059.  
  11060. default:
  11061. break;
  11062. }
  11063. });
  11064. $('input[name^="hotKey"]').attr('readonly', 'readonly').off('keydown').on('keydown', function(event) {
  11065. let functionKey = '';
  11066. if (event.altKey) {
  11067. functionKey += 'alt + ';
  11068. } else if (event.ctrlKey) {
  11069. functionKey += 'ctrl + ';
  11070. } else if (event.shiftKey) {
  11071. functionKey += 'shift + ';
  11072. }
  11073. $(this).val(functionKey + (event.key.length === 1 ? event.key.toLowerCase() : ''));
  11074. });
  11075. } catch (error) {
  11076. throwError(error, 'Setting.after');
  11077. }
  11078. }
  11079. saveGlobalOptions() {
  11080. try {
  11081. saveData();
  11082. } catch (error) {
  11083. throwError(error, 'Setting.saveGlobalOptions');
  11084. }
  11085. }
  11086. #getId(social) {
  11087. try {
  11088. external_Swal_default().fire({
  11089. title: i18n('getId', i18n(social)),
  11090. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  11091. <button id="link2id" data-type="${social}" class="swal2-confirm swal2-styled">获取id</button>`,
  11092. showCancelButton: true,
  11093. cancelButtonText: i18n('close'),
  11094. showConfirmButton: false
  11095. });
  11096. $('#link2id').on('click', async function() {
  11097. const link = $('#socialLink').val();
  11098. if (!link) {
  11099. return;
  11100. }
  11101. const type = $(this).attr('data-type');
  11102. if (type === 'twitterUser') {
  11103. const name = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || link;
  11104. $('#socialLink').val(await new social_Twitter().userName2id(name) || '');
  11105. } else if (type === 'youtubeChannel') {
  11106. const name = /^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www.youtube.com\/.*/.test(link) ? link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1] : link;
  11107. $('#socialLink').val((await getInfo(name, 'channel'))?.params?.channelId || '');
  11108. }
  11109. });
  11110. } catch (error) {
  11111. throwError(error, 'Setting.getId');
  11112. }
  11113. }
  11114. #environment() {
  11115. try {
  11116. const userAgent = (0, javascript_utils_umd_min.ua)();
  11117. const environmentForm = `<form id="environmentForm" class="auto-task-form">
  11118. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('name')}</td><td>${i18n('version')}</td></tr></thead><tbody>
  11119. <tr><td>${i18n('os')}</td><td>${userAgent.os}</td><td>${userAgent.osVersion}</td></tr>
  11120. <tr><td>${i18n('browser')}</td><td>${userAgent.browserZH}</td><td>${userAgent.browserVersion}</td></tr>
  11121. <tr><td>${i18n('scriptManager')}</td><td>${GM_info.scriptHandler}</td><td>${GM_info.version}</td></tr>
  11122. <tr><td>${i18n('script')}</td><td>${GM_info.script.name}</td><td>${GM_info.script.version}</td></tr>
  11123. </tbody></table></form>`;
  11124. $('body').append(`<h2>${i18n('environment')}</h2>${environmentForm}`);
  11125. } catch (error) {
  11126. throwError(error, 'Setting.environment');
  11127. }
  11128. }
  11129. }
  11130. const website_Setting = Setting;
  11131. class History extends website_Keylol {
  11132. name = 'History';
  11133. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect', 'clearHistory' ];
  11134. static test() {
  11135. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/history.html';
  11136. }
  11137. before() {
  11138. try {
  11139. $('body').html('<div class="container"></div>').addClass('auto-task-history');
  11140. const data = GM_listValues() || [];
  11141. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  11142. for (const item of tasksHistory) {
  11143. this.#addItem(item);
  11144. }
  11145. } catch (error) {
  11146. throwError(error, 'History.before');
  11147. }
  11148. }
  11149. clearHistory() {
  11150. try {
  11151. const data = GM_listValues() || [];
  11152. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  11153. for (const item of tasksHistory) {
  11154. GM_deleteValue(item);
  11155. }
  11156. external_Swal_default().fire({
  11157. title: i18n('clearHistoryFinished'),
  11158. icon: 'success'
  11159. });
  11160. } catch (error) {
  11161. throwError(error, 'History.clearHistory');
  11162. }
  11163. }
  11164. #addItem(item) {
  11165. try {
  11166. const tasksData = GM_getValue(item);
  11167. if (!tasksData?.tasks) {
  11168. return;
  11169. }
  11170. let html = '';
  11171. let title = '';
  11172. let link = '';
  11173. const [ website, id ] = item.split('-');
  11174. switch (website) {
  11175. case 'fawTasks':
  11176. title = `Freeanywhere[${id}]`;
  11177. link = `https://freeanywhere.net/#/giveaway/${id}`;
  11178. break;
  11179.  
  11180. case 'gasTasks':
  11181. title = `Giveawaysu[${id}]`;
  11182. link = `https://giveaway.su/giveaway/view/${id}`;
  11183. break;
  11184.  
  11185. case 'gcTasks':
  11186. title = `GiveeClub[${id}]`;
  11187. link = `https://givee.club/event/${id}`;
  11188. break;
  11189.  
  11190. case 'gkTasks':
  11191. title = `Givekey[${id}]`;
  11192. link = `https://givekey.ru/giveaway/${id}`;
  11193. break;
  11194.  
  11195. case 'gleamTasks':
  11196. title = `Gleam[${id}]`;
  11197. link = `https://gleam.io${id}`;
  11198. break;
  11199.  
  11200. case 'khTasks':
  11201. title = `keyhub[${id}]`;
  11202. link = `https://key-hub.eu/giveaway/${id}`;
  11203. break;
  11204.  
  11205. case 'prysTasks':
  11206. title = `Prys[${id}]`;
  11207. link = `https://prys.revadike.com/giveaway/?id=${id}`;
  11208. break;
  11209.  
  11210. default:
  11211. return;
  11212. }
  11213. for (const [ social, types ] of Object.entries(tasksData.tasks)) {
  11214. for (const [ type, tasks ] of Object.entries(types)) {
  11215. for (const task of tasks) {
  11216. 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>`;
  11217. }
  11218. }
  11219. }
  11220. $('.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>`);
  11221. $('span.delete-task').on('click', function() {
  11222. const itemName = $(this).attr('data-name');
  11223. if (itemName) {
  11224. GM_deleteValue(itemName);
  11225. $(`div.card[data-name="${itemName}"]`).remove();
  11226. external_Swal_default().fire({
  11227. title: i18n('clearTaskFinished'),
  11228. text: itemName,
  11229. icon: 'success'
  11230. });
  11231. } else {
  11232. external_Swal_default().fire({
  11233. title: i18n('clearTaskFailed'),
  11234. icon: 'error'
  11235. });
  11236. }
  11237. });
  11238. } catch (error) {
  11239. throwError(error, 'History.addItem');
  11240. }
  11241. }
  11242. }
  11243. const website_History = History;
  11244. const GiveawayHopper_defaultTasksTemplate = {
  11245. steam: {
  11246. groupLinks: [],
  11247. wishlistLinks: [],
  11248. followLinks: [],
  11249. curatorLinks: [],
  11250. curatorLikeLinks: []
  11251. },
  11252. twitter: {
  11253. userLinks: [],
  11254. retweetLinks: []
  11255. },
  11256. twitch: {
  11257. channelLinks: []
  11258. },
  11259. discord: {
  11260. serverLinks: []
  11261. },
  11262. youtube: {
  11263. channelLinks: []
  11264. },
  11265. extra: {
  11266. giveawayHopper: []
  11267. }
  11268. };
  11269. const GiveawayHopper_defaultTasks = JSON.stringify(GiveawayHopper_defaultTasksTemplate);
  11270. class GiveawayHopper extends website_Website {
  11271. name = 'GiveawayHopper';
  11272. undoneTasks = JSON.parse(GiveawayHopper_defaultTasks);
  11273. socialTasks = JSON.parse(GiveawayHopper_defaultTasks);
  11274. tasks = [];
  11275. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  11276. static test() {
  11277. return window.location.host === 'giveawayhopper.com';
  11278. }
  11279. async after() {
  11280. try {
  11281. if (!this.#checkLogin()) {
  11282. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  11283. }
  11284. this.#getGiveawayId();
  11285. } catch (error) {
  11286. throwError(error, 'GiveawayHopper.after');
  11287. }
  11288. }
  11289. async init() {
  11290. try {
  11291. const logStatus = scripts_echoLog({
  11292. text: i18n('initing')
  11293. });
  11294. if (!await this.#checkLeftKey()) {
  11295. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  11296. }
  11297. this.initialized = true;
  11298. logStatus.success();
  11299. return true;
  11300. } catch (error) {
  11301. throwError(error, 'GiveawayHopper.init');
  11302. return false;
  11303. }
  11304. }
  11305. async classifyTask(action) {
  11306. try {
  11307. if (!this.giveawayId) {
  11308. await this.#getGiveawayId();
  11309. }
  11310. const logStatus = scripts_echoLog({
  11311. text: i18n('getTasksInfo')
  11312. });
  11313. if (action === 'undo') {
  11314. this.socialTasks = GM_getValue(`giveawayHopperTasks-${this.giveawayId}`)?.tasks || JSON.parse(GiveawayHopper_defaultTasks);
  11315. }
  11316. const {
  11317. result,
  11318. statusText,
  11319. status,
  11320. data
  11321. } = await tools_httpRequest({
  11322. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/with-auth`,
  11323. method: 'GET',
  11324. responseType: 'json',
  11325. fetch: true,
  11326. headers: {
  11327. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  11328. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  11329. }
  11330. });
  11331. if (result === 'Success') {
  11332. if (data?.status === 200 && data?.response?.tasks) {
  11333. this.tasks = data.response.tasks;
  11334. for (const task of data.response.tasks) {
  11335. if (task.isDone) {
  11336. continue;
  11337. }
  11338. await tools_httpRequest({
  11339. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/visited`,
  11340. method: 'GET',
  11341. responseType: 'json',
  11342. fetch: true,
  11343. headers: {
  11344. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  11345. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  11346. }
  11347. });
  11348. if (task.category === 'Steam' && task.type === 'JoinGroup') {
  11349. const steamGroupLink = await getRedirectLink(`https://steamcommunity.com/gid/${task.group_id}`);
  11350. if (!steamGroupLink) {
  11351. continue;
  11352. }
  11353. if (action === 'undo') {
  11354. this.socialTasks.steam.groupLinks.push(steamGroupLink);
  11355. }
  11356. if (action === 'do') {
  11357. this.undoneTasks.steam.groupLinks.push(steamGroupLink);
  11358. }
  11359. continue;
  11360. }
  11361. if (task.category === 'Discord' && task.type === 'JoinServer') {
  11362. if (action === 'undo') {
  11363. this.socialTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  11364. }
  11365. if (action === 'do') {
  11366. this.undoneTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  11367. }
  11368. continue;
  11369. }
  11370. if ([ 'TikTok', 'YouTube', 'General' ].includes(task.category)) {
  11371. continue;
  11372. }
  11373. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${task.category}-${task.type}`);
  11374. }
  11375. logStatus.success();
  11376. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  11377. this.socialTasks = this.uniqueTasks(this.socialTasks);
  11378. if (window.DEBUG) {
  11379. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  11380. }
  11381. GM_setValue(`giveawayHopperTasks-${this.giveawayId}`, {
  11382. tasks: this.socialTasks,
  11383. time: new Date().getTime()
  11384. });
  11385. return true;
  11386. }
  11387. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  11388. return false;
  11389. }
  11390. logStatus.error(`${result}:${statusText}(${status})`);
  11391. return false;
  11392. } catch (error) {
  11393. throwError(error, 'GiveawayHopper.classifyTask');
  11394. return false;
  11395. }
  11396. }
  11397. async verifyTask() {
  11398. try {
  11399. for (const task of this.tasks) {
  11400. if (task.isDone) {
  11401. continue;
  11402. }
  11403. const logStatus = scripts_echoLog({
  11404. text: `${i18n('verifyingTask')}[${task.displayName?.replace(':target', task.targetName) || task.name}]...`
  11405. });
  11406. if (!task.link) {
  11407. if (task.category === 'YouTube' && task.type === 'FollowAccount') {
  11408. task.link = `https://www.youtube.com/@${task.targetName}`;
  11409. } else if (task.category === 'TikTok' && task.type === 'FollowAccount') {
  11410. task.link = `https://www.tiktok.com/@${task.targetName}`;
  11411. } else if (task.category === 'Steam' && task.type === 'JoinGroup') {
  11412. task.link = '';
  11413. } else if (task.category === 'Discord' && task.type === 'JoinServer') {
  11414. task.link = '';
  11415. }
  11416. }
  11417. if (task.link) {
  11418. await tools_httpRequest({
  11419. 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}`,
  11420. method: 'GET',
  11421. fetch: true,
  11422. headers: {
  11423. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  11424. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  11425. }
  11426. });
  11427. }
  11428. await delay(1e3);
  11429. const postData = {
  11430. taskcategory: task.category,
  11431. taskname: task.type
  11432. };
  11433. if ([ 'YouTube', 'TikTok' ].includes(task.category)) {
  11434. postData.username = '1';
  11435. }
  11436. const {
  11437. result,
  11438. statusText,
  11439. status,
  11440. data
  11441. } = await tools_httpRequest({
  11442. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/complete`,
  11443. method: 'POST',
  11444. fetch: true,
  11445. headers: {
  11446. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  11447. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1]),
  11448. 'content-type': 'application/json'
  11449. },
  11450. dataType: 'json',
  11451. data: JSON.stringify(postData)
  11452. });
  11453. if (result === 'Success') {
  11454. if (data?.status === 200 && data?.response?.completed) {
  11455. logStatus.success();
  11456. continue;
  11457. }
  11458. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  11459. continue;
  11460. }
  11461. logStatus.error(`${result}:${statusText}(${status})`);
  11462. continue;
  11463. }
  11464. } catch (error) {
  11465. throwError(error, 'GiveawayHopper.verifyTask');
  11466. return false;
  11467. }
  11468. }
  11469. #getGiveawayId() {
  11470. try {
  11471. const giveawayId = window.location.pathname.split('/').at(-1);
  11472. if (giveawayId) {
  11473. this.giveawayId = giveawayId;
  11474. return true;
  11475. }
  11476. scripts_echoLog({
  11477. text: i18n('getFailed', 'GiveawayId')
  11478. });
  11479. return false;
  11480. } catch (error) {
  11481. throwError(error, 'GiveawayHopper.getGiveawayId');
  11482. return false;
  11483. }
  11484. }
  11485. #checkLogin() {
  11486. try {
  11487. if (!globalOptions.other.checkLogin) {
  11488. return true;
  11489. }
  11490. if ($('div.widget-connections-edit:contains("Log in")').length > 0) {
  11491. $('div.widget-connections-edit:contains("Log in") a')[0].click();
  11492. }
  11493. return true;
  11494. } catch (error) {
  11495. throwError(error, 'GiveawayHopper.checkLogin');
  11496. return false;
  11497. }
  11498. }
  11499. async #checkLeftKey() {
  11500. try {
  11501. if (!globalOptions.other.checkLeftKey) {
  11502. return true;
  11503. }
  11504. if ($('p.widget-single-prize span').length > 0 && parseInt($('p.widget-single-prize span').text()?.match(/\d+/)?.[0] || '0', 10) > 0) {
  11505. return true;
  11506. }
  11507. await external_Swal_default().fire({
  11508. icon: 'warning',
  11509. title: i18n('notice'),
  11510. text: i18n('noKeysLeft'),
  11511. confirmButtonText: i18n('confirm'),
  11512. cancelButtonText: i18n('cancel'),
  11513. showCancelButton: true
  11514. }).then(({
  11515. value
  11516. }) => {
  11517. if (value) {
  11518. window.close();
  11519. }
  11520. });
  11521. return true;
  11522. } catch (error) {
  11523. throwError(error, 'GiveawayHopper.checkLeftKey');
  11524. return false;
  11525. }
  11526. }
  11527. }
  11528. const website_GiveawayHopper = GiveawayHopper;
  11529. 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 ];
  11530. const websiteOptions = function(website, options) {
  11531. try {
  11532. let websiteOptionsForm = `<form id="websiteOptionsForm" class="auto-task-form">
  11533. <table class="auto-task-table"><thead><tr><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  11534. for (const [ option, value ] of Object.entries(options)) {
  11535. websiteOptionsForm += `<tr><td>${option}</td><td><input class="editOption" type="text" name="${option}" value="${value}"/></td></tr>`;
  11536. }
  11537. websiteOptionsForm += '</tbody></table></form>';
  11538. external_Swal_default().fire({
  11539. title: i18n('websiteOptions'),
  11540. html: websiteOptionsForm,
  11541. showConfirmButton: true,
  11542. confirmButtonText: i18n('save'),
  11543. showCancelButton: true,
  11544. cancelButtonText: i18n('close')
  11545. }).then(({
  11546. isConfirmed
  11547. }) => {
  11548. if (isConfirmed) {
  11549. $('#websiteOptionsForm').serializeArray().map(value => {
  11550. options[value.name] = value.value;
  11551. return value;
  11552. });
  11553. GM_setValue(`${website}Options`, options);
  11554. external_Swal_default().fire({
  11555. title: i18n('changeWebsiteOptionsSuccess'),
  11556. icon: 'success'
  11557. });
  11558. }
  11559. });
  11560. } catch (error) {
  11561. throwError(error, 'websiteOptions');
  11562. }
  11563. };
  11564. const options = websiteOptions;
  11565. const external_keyboardJS_namespaceObject = keyboardJS;
  11566. var external_keyboardJS_default = __webpack_require__.n(external_keyboardJS_namespaceObject);
  11567. const checkUpdate = async (updateLink, auto) => {
  11568. try {
  11569. const checkUrl = `${updateLink}package.json?time=${new Date().getTime()}`;
  11570. const {
  11571. result,
  11572. statusText,
  11573. status,
  11574. data
  11575. } = await tools_httpRequest({
  11576. url: checkUrl,
  11577. responseType: 'json',
  11578. method: 'GET',
  11579. timeout: 3e4
  11580. });
  11581. if (result === 'Success') {
  11582. if (data?.response?.version) {
  11583. return data.response;
  11584. }
  11585. if (!auto) {
  11586. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${data?.statusText}(${data?.status})]`);
  11587. }
  11588. return false;
  11589. }
  11590. if (!auto) {
  11591. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${result}:${statusText}(${status})]`);
  11592. }
  11593. return false;
  11594. } catch (error) {
  11595. throwError(error, 'checkUpdate');
  11596. return false;
  11597. }
  11598. };
  11599. const hasNewVersion = (currentVersion, remoteVersion) => {
  11600. try {
  11601. const [ currentRealVersion ] = currentVersion.split('-');
  11602. const [ remoteRealVersion, isPreview ] = remoteVersion.split('-');
  11603. if (isPreview && !globalOptions.other.receivePreview) {
  11604. return false;
  11605. }
  11606. const [ currentVersion1, currentVersion2, currentVersion3 ] = currentRealVersion.split('.').map(value => parseInt(value, 10));
  11607. const [ remoteVersion1, remoteVersion2, remoteVersion3 ] = remoteRealVersion.split('.').map(value => parseInt(value, 10));
  11608. if (remoteVersion1 > currentVersion1) {
  11609. return true;
  11610. }
  11611. if (remoteVersion1 < currentVersion1) {
  11612. return false;
  11613. }
  11614. if (remoteVersion2 > currentVersion2) {
  11615. return true;
  11616. }
  11617. if (remoteVersion2 < currentVersion2) {
  11618. return false;
  11619. }
  11620. if (remoteVersion3 > currentVersion3) {
  11621. return true;
  11622. }
  11623. return false;
  11624. } catch (error) {
  11625. throwError(error, 'compareVersion');
  11626. return false;
  11627. }
  11628. };
  11629. const updateChecker = async () => {
  11630. try {
  11631. const currentVersion = GM_info.script.version;
  11632. const updateSource = globalOptions.other.autoUpdateSource.toLowerCase();
  11633. const updateLinks = {
  11634. github: 'https://github.com/HCLonely/auto-task-new/raw/main/',
  11635. jsdelivr: 'https://cdn.jsdelivr.net/gh/HCLonely/auto-task-v4@main/',
  11636. standby: 'https://auto-task-v4.hclonely.com/'
  11637. };
  11638. let version;
  11639. let updateLink = '';
  11640. let packageData;
  11641. if ([ 'github', 'jsdelivr', 'standby' ].includes(updateSource)) {
  11642. updateLink = updateLinks[updateSource];
  11643. packageData = await checkUpdate(updateLink, false);
  11644. } else {
  11645. updateLink = updateLinks.github;
  11646. packageData = await checkUpdate(updateLink, true);
  11647. if (!packageData) {
  11648. updateLink = updateLinks.jsdelivr;
  11649. packageData = await checkUpdate(updateLink, true);
  11650. if (!packageData) {
  11651. updateLink = updateLinks.standby;
  11652. packageData = await checkUpdate(updateLink, true);
  11653. }
  11654. }
  11655. }
  11656. if (packageData) {
  11657. version = packageData.version || currentVersion;
  11658. } else {
  11659. version = currentVersion;
  11660. scripts_echoLog({}).error(i18n('checkUpdateFailed'));
  11661. }
  11662. if (packageData && hasNewVersion(currentVersion, version)) {
  11663. scripts_echoLog({
  11664. html: `<li><font>${i18n('newVersionNotice', version, `${updateLink}dist/${GM_info.script.name}.user.js`)}</font></li>`
  11665. });
  11666. scripts_echoLog({
  11667. html: `<li>${i18n('updateText', version)}</li><ol class="update-text">${packageData.change?.map(change => `<li>${change}</li>`).join('')}<li>${i18n('updateHistory')}</li></ol>`
  11668. });
  11669. }
  11670. } catch (error) {
  11671. throwError(error, 'updateChecker');
  11672. }
  11673. };
  11674. const scripts_updateChecker = updateChecker;
  11675. window.STYLE = GM_addStyle(auto_task.A + GM_getResourceText('style'));
  11676. window.DEBUG = !!globalOptions.other?.debug;
  11677. window.TRACE = !!globalOptions.other?.debug && typeof console.trace === 'function';
  11678. const loadScript = async () => {
  11679. if (window.name === 'ATv4_twitchAuth' && window.location.hostname === 'www.twitch.tv') {
  11680. const authToken = external_Cookies_default().get('auth-token');
  11681. const isLogin = !!external_Cookies_default().get('login');
  11682. if (isLogin) {
  11683. GM_setValue('twitchAuth', {
  11684. authToken: authToken,
  11685. clientVersion: __twilightBuildID,
  11686. clientId: commonOptions?.headers?.['Client-ID'],
  11687. deviceId: commonOptions?.headers?.['Device-ID'],
  11688. clientSessionId: window.localStorage.local_storage_app_session_id.replace(/"/g, '')
  11689. });
  11690. window.close();
  11691. external_Swal_default().fire('', i18n('closePageNotice'));
  11692. } else {
  11693. external_Swal_default().fire('', i18n('needLogin'));
  11694. }
  11695. return;
  11696. }
  11697. if (window.name === 'ATv4_redditAuth' && window.location.hostname === 'www.reddit.com') {
  11698. const betaButton = $('#redesign-beta-optin-btn');
  11699. if (betaButton.length > 0) {
  11700. return betaButton[0].click();
  11701. }
  11702. window.close();
  11703. external_Swal_default().fire('', i18n('closePageNotice'));
  11704. return;
  11705. }
  11706. let website;
  11707. for (const Website of Websites) {
  11708. if (Website.test()) {
  11709. website = new Website();
  11710. break;
  11711. }
  11712. }
  11713. if (!website) {
  11714. console.log('%c%s', 'color:#ff0000', 'Auto-Task[Warning]: 脚本停止加载,当前网站不支持!');
  11715. return;
  11716. }
  11717. if (website?.before) {
  11718. await website?.before();
  11719. }
  11720. $('body').append(`
  11721. <div id="auto-task-info"
  11722. style="display:${globalOptions.other.defaultShowLog ? 'block' : 'none'};
  11723. ${globalOptions.position.logSideX}:${globalOptions.position.logDistance.split(',')[0]}px;
  11724. ${globalOptions.position.logSideY}:${globalOptions.position.logDistance.split(',')[1]}px;">
  11725. </div>
  11726. <div id="auto-task-buttons"
  11727. style="display:${globalOptions.other.defaultShowButton ? 'block' : 'none'};
  11728. ${globalOptions.position.buttonSideX}:${globalOptions.position.buttonDistance.split(',')[0]}px;
  11729. ${globalOptions.position.buttonSideY}:${globalOptions.position.buttonDistance.split(',')[1]}px;">
  11730. </div>
  11731. <div class="show-button-div"
  11732. style="display:${globalOptions.other.defaultShowButton ? 'none' : 'block'};
  11733. ${globalOptions.position.showButtonSideX}:${globalOptions.position.showButtonDistance.split(',')[0]}px;
  11734. ${globalOptions.position.showButtonSideY}:${globalOptions.position.showButtonDistance.split(',')[1]}px;">
  11735. <a class="auto-task-website-btn"
  11736. href="javascript:void(0);"
  11737. target="_self"
  11738. title="${i18n('showButton')}"> </a>
  11739. </div>
  11740. `);
  11741. $('div.show-button-div').on('click', () => {
  11742. $('#auto-task-buttons').show();
  11743. $('div.show-button-div').hide();
  11744. });
  11745. const toggleLog = () => {
  11746. const $this = $('#toggle-log');
  11747. const status = $this.attr('data-status');
  11748. if (status === 'show') {
  11749. $('#auto-task-info').hide();
  11750. $this.attr('data-status', 'hide').text(i18n('showLog'));
  11751. } else {
  11752. $('#auto-task-info').show();
  11753. $this.attr('data-status', 'show').text(i18n('hideLog'));
  11754. }
  11755. };
  11756. external_keyboardJS_default().bind(globalOptions.hotKey.doTaskKey, () => {
  11757. if (website.doTask) {
  11758. website.doTask();
  11759. }
  11760. });
  11761. external_keyboardJS_default().bind(globalOptions.hotKey.undoTaskKey, () => {
  11762. if (website.undoTask) {
  11763. website.undoTask();
  11764. }
  11765. });
  11766. external_keyboardJS_default().bind(globalOptions.hotKey.toggleLogKey, toggleLog);
  11767. if (website?.after) {
  11768. await website?.after();
  11769. }
  11770. if (website?.buttons && $('#auto-task-buttons').children().length === 0) {
  11771. $('#auto-task-buttons').addClass(`${website.name}-buttons`);
  11772. for (const button of website.buttons) {
  11773. if (website[button]) {
  11774. const btnElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">${i18n(button)}</a></p>`);
  11775. btnElement.find('a.auto-task-website-btn').on('click', () => {
  11776. website[button]();
  11777. });
  11778. $('#auto-task-buttons').append(btnElement);
  11779. }
  11780. }
  11781. }
  11782. const hideButtonElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">
  11783. ${i18n('hideButton')}</a></p>`);
  11784. hideButtonElement.find('a.auto-task-website-btn').on('click', () => {
  11785. $('#auto-task-buttons').hide();
  11786. $('div.show-button-div').show();
  11787. });
  11788. 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'}">
  11789. ${globalOptions.other.defaultShowLog ? i18n('hideLog') : i18n('showLog')}</a></p>`);
  11790. toggleLogElement.find('a.auto-task-website-btn').on('click', toggleLog);
  11791. $('#auto-task-buttons').append(hideButtonElement).append(toggleLogElement);
  11792. if (website?.options) {
  11793. GM_registerMenuCommand(i18n('changeWebsiteOptions'), () => {
  11794. options(website.name, website.options);
  11795. });
  11796. }
  11797. if (website.name !== 'Setting') {
  11798. GM_registerMenuCommand(i18n('changeGlobalOptions'), () => {
  11799. changeGlobalOptions('swal');
  11800. });
  11801. GM_registerMenuCommand(i18n('settingPage'), () => {
  11802. GM_openInTab('https://auto-task-v4.hclonely.com/setting.html', {
  11803. active: true
  11804. });
  11805. });
  11806. }
  11807. console.log('%c%s', 'color:#1bbe1a', 'Auto-Task[Load]: 脚本加载完成');
  11808. const [ v1, v2 ] = GM_info.version?.split('.') || [];
  11809. if (!(parseInt(v1, 10) >= 5 && parseInt(v2, 10) >= 2)) {
  11810. scripts_echoLog({}).error(i18n('versionNotMatched'));
  11811. }
  11812. if (!GM_getValue('notice')) {
  11813. external_Swal_default().fire({
  11814. title: i18n('swalNotice'),
  11815. icon: 'warning'
  11816. }).then(() => {
  11817. GM_openInTab(i18n('noticeLink'), {
  11818. active: true
  11819. });
  11820. GM_setValue('notice', new Date().getTime());
  11821. });
  11822. scripts_echoLog({
  11823. html: `<li><font class="warning">${i18n('echoNotice', i18n('noticeLink'))}</font></li>`
  11824. }).font?.find('a').on('click', () => {
  11825. GM_setValue('notice', new Date().getTime());
  11826. });
  11827. }
  11828. scripts_updateChecker();
  11829. };
  11830. if (window.location.hostname === 'discord.com') {
  11831. const LocalStorage = window.localStorage;
  11832. if (window.name === 'ATv4_discordAuth') {
  11833. window.localStorage.removeItem = () => true;
  11834. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11835. if (discordAuth && discordAuth.length > 0) {
  11836. GM_setValue('discordAuth', {
  11837. auth: discordAuth
  11838. });
  11839. window.close();
  11840. external_Swal_default().fire('', i18n('closePageNotice'));
  11841. } else {
  11842. external_Swal_default().fire({
  11843. text: i18n('getDiscordAuthFailed'),
  11844. icon: 'error'
  11845. });
  11846. }
  11847. } else {
  11848. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11849. if (discordAuth && discordAuth.length > 0) {
  11850. GM_setValue('discordAuth', {
  11851. auth: discordAuth
  11852. });
  11853. }
  11854. }
  11855. } else if (window.location.hostname === 'opquests.com') {
  11856. loadScript();
  11857. } else if ((window.name === 'ATv4_updateStoreAuth' || GM_getValue('ATv4_updateStoreAuth')) && window.location.host === 'store.steampowered.com') {
  11858. $(() => {
  11859. if ($('[data-miniprofile]').length === 0) {
  11860. return;
  11861. }
  11862. const storeSessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11863. if (storeSessionID) {
  11864. GM_deleteValue('ATv4_updateStoreAuth');
  11865. GM_setValue('steamStoreAuth', {
  11866. storeSessionID: storeSessionID
  11867. });
  11868. window.close();
  11869. external_Swal_default().fire('', i18n('closePageNotice'));
  11870. } else {
  11871. external_Swal_default().fire({
  11872. title: 'Error: Get "sessionID" failed',
  11873. icon: 'error'
  11874. });
  11875. }
  11876. });
  11877. } else if ((window.name === 'ATv4_updateCommunityAuth' || GM_getValue('ATv4_updateCommunityAuth')) && window.location.host === 'steamcommunity.com') {
  11878. $(() => {
  11879. const steam64Id = document.body.innerHTML.match(/g_steamID = "(.+?)";/)?.[1];
  11880. const communitySessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11881. if (steam64Id && communitySessionID) {
  11882. GM_deleteValue('ATv4_updateCommunityAuth');
  11883. GM_setValue('steamCommunityAuth', {
  11884. steam64Id: steam64Id,
  11885. communitySessionID: communitySessionID
  11886. });
  11887. window.close();
  11888. external_Swal_default().fire('', i18n('closePageNotice'));
  11889. } else {
  11890. setTimeout(() => {
  11891. external_Swal_default().fire({
  11892. title: 'Error: Get "sessionID" failed',
  11893. icon: 'error'
  11894. });
  11895. }, 3e3);
  11896. }
  11897. });
  11898. } else {
  11899. if (window.location.hostname === 'key-hub.eu') {
  11900. unsafeWindow.keyhubtracker = 1;
  11901. unsafeWindow.gaData = {};
  11902. }
  11903. $(loadScript);
  11904. }
  11905. }();
  11906. })();