auto-task-v4

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

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

  1. // ==UserScript==
  2. // @name auto-task-v4
  3. // @namespace auto-task-v4
  4. // @version 4.7.7
  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, redirectOnce = false) => {
  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. redirect: redirectOnce ? 'manual' : 'follow'
  1369. }).then(({
  1370. data
  1371. }) => {
  1372. if (data?.finalUrl) {
  1373. redirectLinksCache[link] = data.finalUrl;
  1374. GM_setValue('redirectLinks', redirectLinksCache);
  1375. return data.finalUrl;
  1376. }
  1377. return null;
  1378. });
  1379. } catch (error) {
  1380. throwError(error, 'getRedirectLink');
  1381. return null;
  1382. }
  1383. };
  1384. const visitLink = async (link, options) => {
  1385. try {
  1386. const logStatus = scripts_echoLog({
  1387. type: 'visitLink',
  1388. text: link
  1389. });
  1390. return await tools_httpRequest({
  1391. url: link,
  1392. method: 'GET',
  1393. ...options
  1394. }).then(({
  1395. result,
  1396. statusText,
  1397. status
  1398. }) => {
  1399. if (result === 'Success') {
  1400. logStatus.success();
  1401. return true;
  1402. }
  1403. logStatus.error(`${result}:${statusText}(${status})`);
  1404. return false;
  1405. });
  1406. } catch (error) {
  1407. throwError(error, 'visitLink');
  1408. return false;
  1409. }
  1410. };
  1411. const getUrlQuery = url => {
  1412. try {
  1413. const query = {};
  1414. if (url) {
  1415. if (url.includes('?')) {
  1416. url.split('?')[1].replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  1417. query[key] = value;
  1418. return str;
  1419. });
  1420. }
  1421. } else {
  1422. window.location.search.replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  1423. query[key] = value;
  1424. return str;
  1425. });
  1426. }
  1427. return query;
  1428. } catch (error) {
  1429. throwError(error, 'getUrlQuery');
  1430. return {};
  1431. }
  1432. };
  1433. const getUuid = () => {
  1434. const uuidUrl = URL.createObjectURL(new Blob()).toString();
  1435. return uuidUrl.slice(uuidUrl.lastIndexOf('/') + 1);
  1436. };
  1437. const stringToColour = str => {
  1438. try {
  1439. let hash = 0;
  1440. for (let i = 0; i < str.length; i++) {
  1441. hash = str.charCodeAt(i) + ((hash << 5) - hash);
  1442. }
  1443. let colour = '#';
  1444. for (let i = 0; i < 3; i++) {
  1445. const value = hash >> i * 8 & 255;
  1446. colour += `00${value.toString(16)}`.slice(-2);
  1447. }
  1448. return colour;
  1449. } catch (error) {
  1450. throwError(error, 'stringToColour');
  1451. return '#fff';
  1452. }
  1453. };
  1454. const debug = (log, data) => {
  1455. if (!window.DEBUG) {
  1456. return;
  1457. }
  1458. console.log('%c%s', 'color:#a7a7a7', `Auto-Task[Debug]: ${log}`);
  1459. if (data) {
  1460. console.log('%c%s', 'color:#a7a7a7', 'Auto-Task[Debug]: ', data);
  1461. }
  1462. };
  1463. const defaultGlobalOptions = {
  1464. doTask: {
  1465. discord: {
  1466. servers: true
  1467. },
  1468. instagram: {
  1469. users: true
  1470. },
  1471. twitch: {
  1472. channels: true
  1473. },
  1474. twitter: {
  1475. users: true,
  1476. retweets: true
  1477. },
  1478. vk: {
  1479. names: true
  1480. },
  1481. youtube: {
  1482. channels: true,
  1483. likes: true
  1484. },
  1485. reddit: {
  1486. reddits: true
  1487. },
  1488. steam: {
  1489. groups: true,
  1490. officialGroups: true,
  1491. wishlists: true,
  1492. follows: true,
  1493. forums: true,
  1494. workshops: true,
  1495. curators: true,
  1496. workshopVotes: true,
  1497. announcements: true,
  1498. licenses: true,
  1499. playtests: true
  1500. }
  1501. },
  1502. undoTask: {
  1503. discord: {
  1504. servers: true
  1505. },
  1506. instagram: {
  1507. users: true
  1508. },
  1509. twitch: {
  1510. channels: true
  1511. },
  1512. twitter: {
  1513. users: true,
  1514. retweets: true
  1515. },
  1516. vk: {
  1517. names: true
  1518. },
  1519. youtube: {
  1520. channels: true,
  1521. likes: true
  1522. },
  1523. reddit: {
  1524. reddits: true
  1525. },
  1526. steam: {
  1527. groups: true,
  1528. officialGroups: true,
  1529. wishlists: true,
  1530. follows: true,
  1531. forums: true,
  1532. workshops: true,
  1533. curators: true
  1534. }
  1535. },
  1536. ASF: {
  1537. AsfEnabled: false,
  1538. AsfIpcUrl: '',
  1539. AsfIpcPassword: '',
  1540. AsfBotname: 'asf'
  1541. },
  1542. position: {
  1543. buttonSideX: 'right',
  1544. buttonSideY: 'top',
  1545. buttonDistance: '15,30',
  1546. showButtonSideX: 'right',
  1547. showButtonSideY: 'top',
  1548. showButtonDistance: '15,30',
  1549. logSideX: 'right',
  1550. logSideY: 'bottom',
  1551. logDistance: '10,10'
  1552. },
  1553. hotKey: {
  1554. doTaskKey: 'alt + d',
  1555. undoTaskKey: 'alt + u',
  1556. toggleLogKey: 'alt + l'
  1557. },
  1558. other: {
  1559. twitterVerifyId: '783214',
  1560. youtubeVerifyChannel: 'UCrXUsMBcfTVqwAS7DKg9C0Q',
  1561. autoUpdateSource: 'jsdelivr',
  1562. language: 'zh',
  1563. checkLogin: true,
  1564. checkLeftKey: true,
  1565. defaultShowButton: true,
  1566. defaultShowLog: true,
  1567. debug: false,
  1568. receivePreview: true
  1569. }
  1570. };
  1571. const userDefinedGlobalOptions = GM_getValue('globalOptions') || {};
  1572. const assignObject = (obj1, obj2) => {
  1573. try {
  1574. const newObj = {};
  1575. for (const [ key, value ] of Object.entries(obj1)) {
  1576. if (Object.prototype.toString.call(value) === '[object Object]' && Object.prototype.toString.call(obj2[key]) === '[object Object]') {
  1577. newObj[key] = assignObject(value, obj2[key]);
  1578. } else {
  1579. newObj[key] = obj2[key] ?? value;
  1580. }
  1581. }
  1582. return newObj;
  1583. } catch (error) {
  1584. throwError(error, 'assignObject');
  1585. return defaultGlobalOptions;
  1586. }
  1587. };
  1588. const globalOptions = assignObject(defaultGlobalOptions, userDefinedGlobalOptions);
  1589. const saveData = () => {
  1590. try {
  1591. const data = {};
  1592. $('#globalOptionsForm').serializeArray().map(value => {
  1593. data[value.name] = value.value;
  1594. return value;
  1595. });
  1596. $.makeArray($('#globalOptionsForm input')).map(element => {
  1597. const name = $(element).attr('name');
  1598. const keys = name.split('.');
  1599. if (keys.length === 3) {
  1600. globalOptions[keys[0]][keys[1]][keys[2]] = data[name] ? data[name] === 'on' ? true : data[name] : data[name] ?? false;
  1601. } else if (keys.length === 2) {
  1602. globalOptions[keys[0]][keys[1]] = data[name] ? data[name] === 'on' ? true : data[name] : data[name] ?? false;
  1603. }
  1604. return element;
  1605. });
  1606. GM_setValue('globalOptions', globalOptions);
  1607. external_Swal_default().fire({
  1608. title: i18n('changeGlobalOptionsSuccess'),
  1609. icon: 'success'
  1610. });
  1611. } catch (error) {
  1612. throwError(error, 'saveData');
  1613. }
  1614. };
  1615. const changeGlobalOptions = showType => {
  1616. try {
  1617. let globalOptionsForm = `<form id="globalOptionsForm" class="auto-task-form">
  1618. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  1619. for (const [ type, data1 ] of Object.entries(globalOptions)) {
  1620. for (const [ option, data2 ] of Object.entries(data1)) {
  1621. if ([ 'other', 'position', 'hotKey', 'ASF' ].includes(type)) {
  1622. if (typeof data2 === 'boolean') {
  1623. 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>`;
  1624. } else {
  1625. 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>`;
  1626. }
  1627. } else {
  1628. for (const [ socialType, data3 ] of Object.entries(data2)) {
  1629. 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>`;
  1630. }
  1631. }
  1632. }
  1633. }
  1634. globalOptionsForm += '</tbody></table></form>';
  1635. if (showType === 'swal') {
  1636. external_Swal_default().fire({
  1637. title: i18n('globalOptions'),
  1638. html: globalOptionsForm,
  1639. showConfirmButton: true,
  1640. confirmButtonText: i18n('save'),
  1641. showCancelButton: true,
  1642. cancelButtonText: i18n('close')
  1643. }).then(({
  1644. isConfirmed
  1645. }) => {
  1646. if (isConfirmed) {
  1647. saveData();
  1648. }
  1649. });
  1650. } else {
  1651. $('body').append(`<h2>${i18n('globalOptions')}</h2>${globalOptionsForm}`);
  1652. }
  1653. } catch (error) {
  1654. throwError(error, 'changeGlobalOptions');
  1655. }
  1656. };
  1657. const data = {
  1658. website: '网站',
  1659. type: '类型',
  1660. edit: '编辑',
  1661. whiteList: '白名单',
  1662. skipTask: '跳过撤销任务',
  1663. whiteListOptions: '白名单设置',
  1664. changeWhiteListOption: '设置白名单(%0)',
  1665. whiteListNotFound: '找不到此项白名单: %0',
  1666. changeWhiteListSuccess: '白名单修改成功,刷新生效!',
  1667. changeWebsiteOptions: '网站设置',
  1668. changeGlobalOptions: '全局设置',
  1669. ok: '是',
  1670. save: '保存',
  1671. close: '关闭',
  1672. return: '返回',
  1673. option: '选项',
  1674. value: '值',
  1675. websiteOptions: '当前网站设置',
  1676. changeWebsiteOptionsSuccess: '更改当前网站设置成功,刷新生效!',
  1677. changeGlobalOptionsSuccess: '更改全局设置成功,刷新生效!',
  1678. needLogin: '请先登录!',
  1679. getTasksInfo: '正在获取并处理任务信息...',
  1680. gettingKey: '正在获取Key...',
  1681. verifyingTask: '正在验证任务',
  1682. notice: '自动任务脚本提醒',
  1683. noKeysLeft: '此页面已经没有剩余key了,是否关闭?',
  1684. giveawayEnded: '此活动已结束,是否关闭?',
  1685. giveawayNotWork: '此活动因某些原因(已结束/暂停/未开始...)不可用(如果是脚本误判请及时反馈),是否关闭?',
  1686. confirm: '确定',
  1687. cancel: '取消',
  1688. unKnown: '未知',
  1689. unKnownTaskType: '未识别的任务',
  1690. doing: '正在做任务',
  1691. allTasksComplete: '所有任务已完成!',
  1692. getTaskIdFailed: '获取任务Id失败!',
  1693. initSuccess: '%0 初始化成功!',
  1694. initFailed: '%0 初始化失败!',
  1695. errorLink: '链接错误: %0',
  1696. needInit: '请先初始化',
  1697. verifyingAuth: '正在验证%0凭证...',
  1698. updatingAuth: '正在更新%0凭证...',
  1699. refreshingToken: '正在刷新%0凭证...',
  1700. settingToken: '正在设置%0凭证...',
  1701. steamStoreTab: 'Steam商店(弹窗)',
  1702. steamCommunityTab: 'Steam社区(弹窗)',
  1703. initing: '正在初始化...',
  1704. getFailed: '获取%0失败!',
  1705. checkLoginFailed: '检测登录状态失败!',
  1706. checkLeftKeyFailed: '检测剩余Key失败!',
  1707. userId: '用户Id',
  1708. joiningGiveaway: '正在加入赠Key',
  1709. needJoinGiveaway: '需要先加入赠Key',
  1710. cannotUndo: '此网站不支持取消任务',
  1711. verifyAuth: '正在验证 %0 凭证...',
  1712. closePageNotice: '如果此页面没有自动关闭,请自行关闭本页面。',
  1713. errorReport: '检测到脚本报错,是否前往反馈BUG?',
  1714. visitingLink: '正在访问链接...',
  1715. doTask: '做任务',
  1716. undoTask: '撤销任务',
  1717. verifyTask: '验证任务',
  1718. getKey: '获取Key',
  1719. selectAll: '全选',
  1720. selectNone: '全不选',
  1721. invertSelect: '反选',
  1722. doFreeTask: '加入免费赠品',
  1723. doPointTask: '加入点数赠品',
  1724. skipTaskOption: '设置中已配置跳过任务',
  1725. other: '其他',
  1726. globalOptions: '全局设置',
  1727. checkLogin: '登录检测</br>需要登录的网站自动登录,部分网站支持',
  1728. checkLeftKey: '剩余Key检测</br>赠Key活动结束提示是否关闭,部分网站支持',
  1729. twitterVerifyId: '通过尝试关注该账号验证Twitter凭证</br>默认为Twitter官方帐号 783214</br>不想关注官方账号可以改为自己的帐号',
  1730. youtubeVerifyChannel: '通过尝试订阅该频道验证YouTube凭证</br>默认为YouTube官方频道 UCrXUsMBcfTVqwAS7DKg9C0Q</br>不想关注官方频道可以改为自己的频道',
  1731. autoUpdateSource: '更新源</br>github: 需代理,实时更新</br>jsdelivr: 可不用代理,更新有延迟</br>standby: 备用</br>auto: 依次使用github, jsdelivr, standby源进行尝试更新',
  1732. saveGlobalOptions: '保存设置',
  1733. settingPage: '设置页面',
  1734. name: '名称',
  1735. version: '版本',
  1736. scriptManager: '脚本管理器',
  1737. script: '脚本',
  1738. environment: '环境',
  1739. os: '系统',
  1740. browser: '浏览器',
  1741. getId: '获取 %0 id',
  1742. getTwitterUserId: '获取Twitter用户id(获取id功能仅在设置页面可用)',
  1743. getYoutubeChannelId: '获取Youtube频道id(获取id功能仅在设置页面可用)',
  1744. showButton: '显示按钮',
  1745. hideButton: '隐藏按钮',
  1746. showLog: '显示日志',
  1747. hideLog: '隐藏日志',
  1748. defaultShowButton: '默认显示按钮',
  1749. defaultShowLog: '默认显示日志',
  1750. debug: '输出调试日志,不要开启此选项!',
  1751. receivePreview: '接收预览版更新',
  1752. position: '组件位置',
  1753. buttonSideX: '按钮区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1754. buttonSideY: '按钮区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1755. buttonDistance: '按钮区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1756. showButtonSideX: '显示按钮水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1757. showButtonSideY: '显示按钮垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1758. showButtonDistance: '显示按钮距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1759. logSideX: '日志区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1760. logSideY: '日志区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1761. logDistance: '日志区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1762. hotKey: '快捷键',
  1763. doTaskKey: '做任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1764. undoTaskKey: '撤销任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1765. toggleLogKey: '显示/隐藏日志快捷键</br>(实时预览功能仅在设置页面可用)',
  1766. tasksHistory: '任务历史',
  1767. clearHistory: '清空历史',
  1768. clearHistoryFinished: '已清空任务历史!',
  1769. deleteTask: '删除任务',
  1770. lastChangeTime: '最后一次修改时间',
  1771. clearTaskFinished: '删除以下任务完成!',
  1772. clearTaskFailed: '删除任务失败,没有找到任务名!',
  1773. syncData: '数据同步',
  1774. settingData: '正在上传数据...',
  1775. gettingData: '正在获取数据...',
  1776. help: '帮助',
  1777. fileName: '文件名',
  1778. upload2gist: '同步到Gist',
  1779. downloadFromGist: '从Gist同步',
  1780. saveAndTest: '保存配置并测试',
  1781. testSuccess: '测试成功!',
  1782. testFailed: '测试失败!',
  1783. saveAndTestNotice: '请先保存配置并测试!',
  1784. processingData: '正在处理数据...',
  1785. updatingData: '正在上传数据...',
  1786. syncDataSuccess: '同步数据成功!',
  1787. syncDataFailed: '同步数据失败,请在控制台查看错误信息!',
  1788. downloadingData: '正在下载数据...',
  1789. checkedNoData: '没有检测到远程数据,请确认配置是否正确!',
  1790. savingData: '正在保存数据...',
  1791. syncHistory: '同步任务历史',
  1792. checkUpdateFailed: '检测更新失败',
  1793. newVersionNotice: '检测到新版本V%0, <a class="high-light" href="%1" target="_blank">点此更新</a>',
  1794. language: '语言</br>目前仅支持zh: 中文, en: 英文',
  1795. gistOptions: 'Gist 设置',
  1796. swalNotice: '检测到您第一次安装V4版本脚本,请前往阅读用前必读内容!',
  1797. echoNotice: '检测到您第一次安装V4版本脚本,请<a class="high-light" href="%0" target="_blank">点此前往</a>阅读用前必读内容!',
  1798. noticeLink: 'https://auto-task-doc.js.org/guide/#用前必读',
  1799. toGithub: '前往Github反馈',
  1800. toKeylol: '前往其乐论坛反馈',
  1801. copySuccess: '错误信息已复制到剪切板,是否前往其乐论坛反馈?',
  1802. copyFailed: '请复制下方错误信息后前往Keylol论坛反馈!',
  1803. updateText: '%0 版本更新内容:',
  1804. Active: '进行中',
  1805. Ended: '已结束',
  1806. Banned: '已封禁',
  1807. Paused: '已暂停',
  1808. notStart: '未开始',
  1809. noRemoteData: '检测到远程无数据',
  1810. errorRemoteDataFormat: '远程数据格式错误',
  1811. updateHistory: '历史更新记录<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">点此查看</a>',
  1812. AsfEnabled: '使用ASF做Steam相关任务(需<a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a>插件)',
  1813. AsfIpcUrl: 'ASF IPC 地址',
  1814. AsfIpcPassword: 'ASF IPC 密码',
  1815. versionNotMatched: '脚本管理器版本过低,需TamperMonkey >= 5.2.0或TamperMonkey Beta >= 5.2.6196',
  1816. groups: '组',
  1817. officialGroups: '官方组',
  1818. wishlists: '愿望单',
  1819. follows: '游戏关注',
  1820. forums: '论坛',
  1821. workshops: '创意工坊收藏',
  1822. curators: '鉴赏家',
  1823. workshopVotes: '创意工坊点赞',
  1824. announcements: '社区通知',
  1825. steamCommunity: 'Steam社区',
  1826. steamStore: 'Steam商店',
  1827. licenses: '入库免费游戏',
  1828. playtests: '请求访问权限',
  1829. needLoginSteamStore: '请先<a href="https://store.steampowered.com/login/" target="_blank">登录Steam商店</a>',
  1830. needLoginSteamCommunity: '请先<a href="https://steamcommunity.com/login/home/" target="_blank">登录Steam社区</a>',
  1831. joiningSteamGroup: '正在加入Steam组',
  1832. leavingSteamGroup: '正在退出Steam组',
  1833. gettingSteamGroupId: '正在获取Steam组Id',
  1834. joiningSteamOfficialGroup: '正在加入Steam官方组',
  1835. leavingSteamOfficialGroup: '正在退出Steam官方组',
  1836. gettingSteamOfficialGroupId: '正在获取Steam官方组Id',
  1837. subscribingForum: '正在订阅Steam论坛',
  1838. unsubscribingForum: '正在取消订阅Steam论坛',
  1839. gettingForumId: '正在获取Steam论坛Id',
  1840. followingCurator: '正在关注Steam鉴赏家',
  1841. unfollowingCurator: '正在取关Steam鉴赏家',
  1842. gettingCuratorId: '正在获取Steam鉴赏家Id',
  1843. addingToWishlist: '正在添加游戏到Steam愿望单',
  1844. removingFromWishlist: '正在从Steam愿望单移除游戏',
  1845. followingGame: '正在关注Steam游戏',
  1846. unfollowingGame: '正在取关Steam游戏',
  1847. favoritingWorkshop: '正在收藏Steam创意工坊物品',
  1848. unfavoritingWorkshop: '正在取消收藏Steam创意工坊物品',
  1849. gettingWorkshopAppId: '正在获取Steam创意工坊物品Id',
  1850. votingUpWorkshop: '正在点赞Steam创意工坊物品',
  1851. gettingAnnouncementParams: '正在获取Steam通知信息',
  1852. likingAnnouncement: '正在点赞Steam通知',
  1853. changingArea: '正在更换Steam地区: %0...',
  1854. notNeededChangeArea: '当前地区不需要更换',
  1855. noAnotherArea: '请检测是否开启正确开启代理',
  1856. gettingAreaInfo: '正在获取Steam地区信息...',
  1857. changeAreaNotice: '疑似锁区游戏,尝试换区执行',
  1858. steamFinishNotice: 'Steam任务完成,尝试将购物车地区换回',
  1859. gettingSubid: '正在获取游戏subid',
  1860. addingFreeLicense: '正在入库',
  1861. missParams: '缺少参数',
  1862. gettingLicenses: '正在获取Licenses...',
  1863. requestingPlayTestAccess: '正在请求访问权限',
  1864. tryChangeAreaNotice: '此功能无法检测游戏是否限区,因此会尝试换区后再入库,换区失败也不影响后续入库',
  1865. gettingUserLink: '正在获取Steam用户社区链接...',
  1866. retry: '重试',
  1867. owned: '已拥有',
  1868. redirect: '重定向',
  1869. noSubid: '无法获取,跳过',
  1870. initingASF: '正在初始化ASF...',
  1871. servers: '服务器',
  1872. joiningDiscordServer: '正在加入Discord服务器',
  1873. leavingDiscordServer: '正在退出Discord服务器',
  1874. gettingDiscordGuild: '正在获取Discord服务器Id',
  1875. getDiscordAuthFailed: '获取Discord凭证失败,请检测Discord帐号是否已登录',
  1876. discordImportantNotice: '重要提醒!!!',
  1877. discordImportantNoticeText: '由于Discord网站后台更新,目前使用此脚本加组后可能会导致Discord帐号被强制退出,且需要两步验证才能正常登录,请谨慎使用!!!',
  1878. continue: '继续',
  1879. skipDiscordTask: '跳过Discord任务',
  1880. continueAndDontRemindAgain: '继续且不再提醒',
  1881. users: '用户',
  1882. loginIns: '请先<a href="https://www.instagram.com/accounts/login/" target="_blank">登录Instagram</a>',
  1883. insBanned: '您的Instagram账户已被封禁',
  1884. verifyingInsAuth: '正在验证Instagram凭证...',
  1885. gettingInsUserId: '正在获取Instagram用户Id',
  1886. followingIns: '正在关注Instagram用户',
  1887. unfollowingIns: '正在取关Instagram用户',
  1888. reddits: '社区/用户',
  1889. loginReddit: '请先<a href="https://www.reddit.com/login/" target="_blank">登录Reddit</a>',
  1890. changingRedditVersion: '正在切换Reddit为新版页面...',
  1891. joiningReddit: '正在加入Reddit社区',
  1892. leavingReddit: '正在退出Reddit社区',
  1893. followingRedditUser: '正在关注Reddit用户',
  1894. unfollowingRedditUser: '正在取关Reddit用户',
  1895. channels: '频道',
  1896. followingTwitchChannel: '正在关注Twitch频道',
  1897. unfollowingTwitchChannel: '正在取关Twitch频道',
  1898. gettingTwitchChannelId: '正在获取Twitch频道Id',
  1899. checkingTwitchIntegrity: '正在检查Twitch完整性...',
  1900. twitterUser: '推特用户',
  1901. retweets: '转推',
  1902. gettingTwitterUserId: '正在获取推特用户Id',
  1903. followingTwitterUser: '正在关注推特用户',
  1904. unfollowingTwitterUser: '正在取关推特用户',
  1905. retweetting: '正在转推',
  1906. unretweetting: '正在撤销转推',
  1907. names: '组/社区/动态',
  1908. loginVk: '请先<a href="https://vk.com/login/" target="_blank">登录Vk</a>',
  1909. gettingVkId: '正在获取Vk任务Id',
  1910. joiningVkGroup: '正在加入Vk组',
  1911. leavingVkGroup: '正在退出Vk组',
  1912. joiningVkPublic: '正在加入Vk社区',
  1913. leavingVkPublic: '正在退出Vk社区',
  1914. sendingVkWall: '正在转发Vk动态',
  1915. deletingVkWall: '正在撤销转发Vk动态',
  1916. youtubeChannel: 'YouTube频道',
  1917. likes: '点赞',
  1918. loginYtb: '请先<a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">登录YouTube</a>',
  1919. tryUpdateYtbAuth: '请尝试<a href="https://www.youtube.com/#auth" target="_blank">更新YouTube凭证</a>',
  1920. gettingYtbToken: '正在获取YouTube Token...',
  1921. followingYtbChannel: '正在订阅YouTube频道',
  1922. unfollowingYtbChannel: '正在退订YouTube频道',
  1923. likingYtbVideo: '正在点赞YouTube视频',
  1924. unlikingYtbVideo: '正在取消点赞YouTube视频',
  1925. giveKeyNoticeBefore: '每次验证间隔15s',
  1926. giveKeyNoticeAfter: '如果没有key, 请在<a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>查看',
  1927. noPoints: '点数不够,跳过抽奖',
  1928. getNeedPointsFailed: '获取所需点数失败,跳过抽奖',
  1929. joiningLottery: '正在加入抽奖',
  1930. doingGleamTask: '正在做Gleam任务...',
  1931. gettingGleamLink: '正在获取Gleam任务链接...',
  1932. gleamTaskNotice: '如果此页面长时间未关闭,请完成任一任务后自行关闭!',
  1933. verifiedGleamTasks: '已尝试验证所有任务,验证失败的任务请尝试手动验证或完成!',
  1934. campaign: '检测到人机验证,请完成验证后重新验证任务!',
  1935. gsNotice: '为避免得到"0000-0000-0000"key, 已自动屏蔽"Grab Key"按钮,获取key时请关闭脚本!',
  1936. giveeClubVerifyNotice: '正在验证任务...',
  1937. giveeClubVerifyFinished: '请等待验证完成后自行加入赠Key',
  1938. doingKeyhubTask: '正在做Keyhub任务...',
  1939. SweepWidgetNotice: '正在处理并验证任务,每次验证任务有1~3s间隔防止触发验证过快警告...',
  1940. tasksNotCompleted: '任务未完成',
  1941. notConnect: '社交平台未连接,跳过任务',
  1942. tgTaskNotice: '检测到Telegram任务,需要手动完成',
  1943. confirmingTask: '正在跳过警告页面...'
  1944. };
  1945. const zh_CN = data;
  1946. const en_US_data = {
  1947. website: 'Website',
  1948. type: 'Type',
  1949. edit: 'Edit',
  1950. whiteList: 'Whitelist',
  1951. skipTask: 'Skip undo task',
  1952. whiteListOptions: 'Whitelist options',
  1953. changeWhiteListOption: 'Whitelist option(%0)',
  1954. whiteListNotFound: 'Cannot find this whitelist: %0',
  1955. changeWhiteListSuccess: 'The whitelist is successfully modified, and the page refresh will take effect!',
  1956. changeWebsiteOptions: 'Website options',
  1957. changeGlobalOptions: 'Global options',
  1958. ok: 'OK',
  1959. save: 'Save',
  1960. close: 'Close',
  1961. return: 'Return',
  1962. option: 'Option',
  1963. value: 'Value',
  1964. websiteOptions: 'Current website settings',
  1965. changeWebsiteOptionsSuccess: 'The current website setting is changed successfully, and the page refresh will take effect!',
  1966. changeGlobalOptionsSuccess: 'The global setting is changed successfully, and the refresh will take effect!',
  1967. needLogin: 'Please log in first!',
  1968. getTasksInfo: 'Obtaining and processing task information...',
  1969. gettingKey: 'Getting Key...',
  1970. verifyingTask: 'Verifying task',
  1971. notice: 'Automatic task script notice',
  1972. noKeysLeft: 'There are no more keys left on this page. Do you want to close it?',
  1973. giveawayEnded: 'This event has ended, do you want to close it?',
  1974. 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?',
  1975. confirm: 'Confirm',
  1976. cancel: 'Cancel',
  1977. unKnown: 'Unknown',
  1978. unKnownTaskType: 'Unrecognized task',
  1979. doing: 'Doing a task',
  1980. allTasksComplete: 'All tasks have been completed!',
  1981. getTaskIdFailed: 'Failed to obtain task Id!',
  1982. initSuccess: '%0 was initialized successfully!',
  1983. initFailed: '%0 initialization failed!',
  1984. errorLink: 'Link error: %0',
  1985. needInit: 'Please initialize first',
  1986. verifyingAuth: 'Verifying %0 token...',
  1987. updatingAuth: 'Update %0 token...',
  1988. refreshingToken: 'Refreshing %0 token...',
  1989. settingToken: 'Setting %0 token...',
  1990. steamStoreTab: 'Steam store (new tab)',
  1991. steamCommunityTab: 'Steam community(new tab)',
  1992. initing: 'Initializing...',
  1993. getFailed: 'Failed to get %0!',
  1994. checkLoginFailed: 'Failed to detect login status!',
  1995. checkLeftKeyFailed: 'Failed to detect the remaining keys!',
  1996. userId: 'User Id',
  1997. joiningGiveaway: 'Joining giveaway',
  1998. needJoinGiveaway: 'Need to join the giveaway first',
  1999. cannotUndo: 'This website does not support canceling tasks',
  2000. verifyAuth: 'Verifying %0 token...',
  2001. closePageNotice: 'f this page does not close automatically, please close this page yourself.',
  2002. errorReport: 'A script error is detected, do you want to report the BUG?',
  2003. visitingLink: 'Visiting link ...',
  2004. doTask: 'DoTask',
  2005. undoTask: 'UndoTask',
  2006. verifyTask: 'Verify',
  2007. getKey: 'GetKey',
  2008. selectAll: 'SelectAll',
  2009. selectNone: 'SelectNone',
  2010. invertSelect: 'InvertSelect',
  2011. doFreeTask: 'FreeTask',
  2012. doPointTask: 'PointTask',
  2013. skipTaskOption: 'Skip task has been configured in the settings',
  2014. other: 'Other',
  2015. globalOptions: 'Global Options',
  2016. checkLogin: 'Login detection</br>Need to log in to the website automatically log in, part of this website supports.',
  2017. checkLeftKey: 'Key remaining detection</br>The end of the giveaway event prompts whether to close or not, part of this website supports.',
  2018. 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.',
  2019. 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.',
  2020. 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.',
  2021. saveGlobalOptions: 'SaveSettings',
  2022. settingPage: 'Setting Page',
  2023. name: 'Name',
  2024. version: 'Version',
  2025. scriptManager: 'Script Manager',
  2026. script: 'Script',
  2027. environment: 'Environment',
  2028. os: 'OS',
  2029. browser: 'Browser',
  2030. getId: 'Get %0 id',
  2031. getTwitterUserId: 'Get Twitter user id (Get id function is only available on the settings page).',
  2032. getYoutubeChannelId: 'Get Youtube channel id (Get id function is only available on the settings page).',
  2033. showButton: 'ShowButton',
  2034. hideButton: 'HideButton',
  2035. showLog: 'ShowLog',
  2036. hideLog: 'HideLog',
  2037. defaultShowButton: 'Default display button',
  2038. defaultShowLog: 'Display log by default',
  2039. debug: 'Output debug log, do not enable this option!',
  2040. receivePreview: 'Receive preview updates',
  2041. position: 'Component position',
  2042. buttonSideX: 'Horizontal positioning of the button area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  2043. 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',
  2044. 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',
  2045. showButtonSideX: 'ShowButton horizontal positioning (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  2046. showButtonSideY: 'ShowButton vertical positioning (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  2047. 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',
  2048. logSideX: 'Horizontal positioning of the log area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  2049. logSideY: 'Vertical positioning of the log area (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  2050. 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',
  2051. hotKey: 'Shortcut key',
  2052. doTaskKey: 'DoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  2053. undoTaskKey: 'UndoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  2054. toggleLogKey: 'ShowLog/HideLog shortcut keys</br> (real-time preview function is only available on the settings page).',
  2055. tasksHistory: 'TasksHistory',
  2056. clearHistory: 'Clear history',
  2057. clearHistoryFinished: 'The mission history has been cleared!',
  2058. deleteTask: 'Delete task',
  2059. lastChangeTime: 'Last Change Time',
  2060. clearTaskFinished: 'Delete the following tasks completed!',
  2061. clearTaskFailed: 'Failed to delete the task, the task name was not found!',
  2062. syncData: 'DataSync',
  2063. settingData: 'Uploading data...',
  2064. gettingData: 'Getting data...',
  2065. help: 'Help',
  2066. fileName: 'Filename',
  2067. upload2gist: 'Sync to Gist',
  2068. downloadFromGist: 'Sync from Gist',
  2069. saveAndTest: 'Save configuration and test',
  2070. testSuccess: 'Test success!',
  2071. testFailed: 'Test failed!',
  2072. saveAndTestNotice: 'Please save the configuration and test first!',
  2073. processingData: 'Processing data...',
  2074. updatingData: 'Uploading data...',
  2075. syncDataSuccess: 'Synchronized data successfully!',
  2076. syncDataFailed: 'Failed to synchronize data, please check the error message on the console!',
  2077. downloadingData: 'Downloading data...',
  2078. checkedNoData: 'No remote data is detected, please confirm whether the configuration is correct!',
  2079. savingData: 'Saving data...',
  2080. syncHistory: 'Synchronize tasks history',
  2081. checkUpdateFailed: 'Check update failed',
  2082. newVersionNotice: 'Checked a new version V%0, <a class="high-light" href="%1" target="_blank">click to update</a>',
  2083. language: 'Language</br> Currently only supports zh: Chinese, en: English',
  2084. gistOptions: 'Gist Settings',
  2085. 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!',
  2086. 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!',
  2087. noticeLink: 'https://auto-task-doc.js.org/en/guide/#read-me-first',
  2088. toGithub: 'Feedback(Github)',
  2089. toKeylol: 'Feedback(Keylol)',
  2090. copySuccess: 'The error message has been copied to the clipboard. Do you want to go to the Keylol forum to give feedback?',
  2091. copyFailed: 'Please copy the error information below and report back to the Keylol forum!',
  2092. updateText: 'Updates in version %0:',
  2093. Active: 'Active',
  2094. Ended: 'Ended',
  2095. Banned: 'Banned',
  2096. Paused: 'Paused',
  2097. notStart: 'notStart',
  2098. noRemoteData: 'No data remotely',
  2099. errorRemoteDataFormat: 'Remote data has wrong format',
  2100. updateHistory: '<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">Click here</a>' + ' to view the historical update record.',
  2101. AsfEnabled: 'Use ASF to do Steam related tasks (requires <a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a> plugin)',
  2102. AsfIpcUrl: 'ASF IPC URL',
  2103. AsfIpcPassword: 'ASF IPC Password',
  2104. groups: 'Group',
  2105. officialGroups: 'Official Group',
  2106. wishlists: 'Wishlist',
  2107. follows: 'Follow Game',
  2108. forums: 'Forum',
  2109. workshops: 'Favorite Workshop',
  2110. curators: 'Curator',
  2111. workshopVotes: 'Voteup Workshop',
  2112. announcements: 'Announcement',
  2113. steamCommunity: 'Steam Community',
  2114. steamStore: 'Steam Store',
  2115. licenses: 'Add License',
  2116. playtests: 'Playtest Access',
  2117. needLoginSteamStore: 'Please <a href="https://store.steampowered.com/login/" target="_blank">log in to the Steam Store</a>',
  2118. needLoginSteamCommunity: 'Please <a href="https://steamcommunity.com/login/home/" target="_blank">log in to the Steam Community</a>',
  2119. joiningSteamGroup: 'Joining Steam Group',
  2120. leavingSteamGroup: 'Leaving Steam Group',
  2121. gettingSteamGroupId: 'Getting Steam Group Id',
  2122. joiningSteamOfficialGroup: 'Joining Steam Official Group',
  2123. leavingSteamOfficialGroup: 'Leaving Steam Official Group',
  2124. gettingSteamOfficialGroupId: 'Getting Steam Official Group Id',
  2125. subscribingForum: 'Subscribing the Steam Forum',
  2126. unsubscribingForum: 'Unsubscribing the Steam Forum',
  2127. gettingForumId: 'Getting Steam Forum Id',
  2128. followingCurator: 'Following Steam Curator',
  2129. unfollowingCurator: 'Unfollowing Steam Curator',
  2130. gettingCuratorId: 'Getting Steam Curator Id',
  2131. addingToWishlist: 'Adding the game to the Steam wishlist',
  2132. removingFromWishlist: 'Removing the game from the Steam wishlist',
  2133. followingGame: 'Following Steam games',
  2134. unfollowingGame: 'Unfollowing Steam games',
  2135. favoritingWorkshop: 'Favouring Steam Workshop Items',
  2136. unfavoritingWorkshop: 'Unfavoriting Steam Workshop Items',
  2137. gettingWorkshopAppId: 'Getting Steam Workshop Item Id',
  2138. votingUpWorkshop: 'Liking Steam workshop items',
  2139. gettingAnnouncementParams: 'Getting Steam announcement information',
  2140. likingAnnouncement: 'Liking Steam announcement',
  2141. changingArea: 'Changing Steam area: %0...',
  2142. notNeededChangeArea: 'The current area does not need to be changed',
  2143. noAnotherArea: 'Please check whether the proxy is turned on correctly',
  2144. gettingAreaInfo: 'Getting Steam area information...',
  2145. changeAreaNotice: 'Suspected of a locked zone game, try to change the zone to execute',
  2146. steamFinishNotice: 'Steam task completed, try to change the shopping cart area back to ',
  2147. gettingSubid: 'Getting subid',
  2148. addingFreeLicense: 'Adding free license',
  2149. missParams: 'Missing parameters',
  2150. gettingLicenses: 'Getting licenses...',
  2151. requestingPlayTestAccess: 'Requesting play test access',
  2152. 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.',
  2153. versionNotMatched: 'The script manager version is too low, requiring TamperMonkey >= 5.2.0 or TamperMonkey Beta >= 5.2.6196',
  2154. gettingUserLink: 'Getting steam user community link...',
  2155. retry: 'Retry',
  2156. owned: 'Owned',
  2157. redirect: 'Redirect',
  2158. noSubid: 'skip due to unrecognized',
  2159. initingASF: 'Initing ASF...',
  2160. servers: 'Server',
  2161. joiningDiscordServer: 'Joining Discord Server',
  2162. leavingDiscordServer: 'Leaving Discord Server',
  2163. gettingDiscordGuild: 'Getting Discord server Id',
  2164. getDiscordAuthFailed: 'Failed to get Discord token, please check whether the Discord account is logged in',
  2165. discordImportantNotice: 'Important Reminder! ! !',
  2166. 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! ! !',
  2167. continue: 'Continue',
  2168. skipDiscordTask: 'Skip',
  2169. continueAndDontRemindAgain: 'Continue without Reminders',
  2170. users: 'User',
  2171. loginIns: 'Please <a href="https://www.instagram.com/accounts/login/" target="_blank">log in to Instagram</a>',
  2172. insBanned: 'Your Instagram account has been banned',
  2173. verifyingInsAuth: 'Verifying Instagram token...',
  2174. gettingInsUserId: 'Getting Instagram user Id',
  2175. followingIns: 'Following Instagram user',
  2176. unfollowingIns: 'Unfollowing Instagram user',
  2177. reddits: 'Reddit/User',
  2178. loginReddit: 'Please <a href="https://www.reddit.com/login/" target="_blank">log in to Reddit</a>',
  2179. changingRedditVersion: 'Switching Reddit to a new version page...',
  2180. joiningReddit: 'Joining the Reddit',
  2181. leavingReddit: 'Leaving the Reddit',
  2182. followingRedditUser: 'Following Reddit User',
  2183. unfollowingRedditUser: 'Unfollowing Reddit User',
  2184. channels: 'Channel',
  2185. followingTwitchChannel: 'Following Twitch Channel',
  2186. unfollowingTwitchChannel: 'Unfollowing Twitch Channel',
  2187. gettingTwitchChannelId: 'Getting Twitch Channel Id',
  2188. checkingTwitchIntegrity: 'Checking Twitch integrity...',
  2189. twitterUser: 'Twitter User',
  2190. retweets: 'Retweet',
  2191. gettingTwitterUserId: 'Getting Twitter User Id',
  2192. followingTwitterUser: 'Following Twitter User',
  2193. unfollowingTwitterUser: 'Unfollowing Twitter User',
  2194. retweetting: 'Retweetting',
  2195. unretweetting: 'Unretweetting',
  2196. names: 'Group/Public/Wall',
  2197. loginVk: 'Please <a href="https://vk.com/login/" target="_blank">log in to Vk</a>',
  2198. gettingVkId: 'Getting Vk task Id',
  2199. joiningVkGroup: 'Joining Vk Group',
  2200. leavingVkGroup: 'Leaving Vk Group',
  2201. joiningVkPublic: 'Joining Vk Public',
  2202. leavingVkPublic: 'Leaving Vk Public',
  2203. sendingVkWall: 'Sending Vk Wall',
  2204. deletingVkWall: 'Deleting Vk Wall',
  2205. youtubeChannel: 'YouTube Channel',
  2206. likes: 'Like',
  2207. loginYtb: 'Please <a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">log in to YouTube</a>',
  2208. tryUpdateYtbAuth: 'Please try to <a href="https://www.youtube.com/#auth" target="_blank">update YouTube token</a>',
  2209. gettingYtbToken: 'Getting YouTube Token...',
  2210. followingYtbChannel: 'Subscribing to YouTube channel',
  2211. unfollowingYtbChannel: 'Unsubscribing to YouTube channel',
  2212. likingYtbVideo: 'Liking YouTube video',
  2213. unlikingYtbVideo: 'Unliking YouTube video',
  2214. giveKeyNoticeBefore: 'Each verification interval is 15s',
  2215. giveKeyNoticeAfter: 'If there is no key, please check at <a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>',
  2216. noPoints: 'Not enough points, skip the lottery',
  2217. getNeedPointsFailed: 'ailed to obtain the required points, skip the lottery',
  2218. joiningLottery: 'Joining the lottery',
  2219. doingGleamTask: 'Doing Gleam Task...',
  2220. gettingGleamLink: 'Getting Gleam task link...',
  2221. gleamTaskNotice: 'If this page has not been closed for a long time, please close it yourself after completing any task!',
  2222. verifiedGleamTasks: 'Attempted to verify all tasks. If the verification fails, please try to verify manually or complete it!',
  2223. campaign: 'ReCAPTCHA detected, please complete it and re-verify the tasks!',
  2224. 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!',
  2225. giveeClubVerifyNotice: 'Verifying task...',
  2226. giveeClubVerifyFinished: 'Wait for the verification to complete and join it by yourself',
  2227. doingKeyhubTask: 'Doing Keyhub Task...',
  2228. 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...',
  2229. tasksNotCompleted: 'Tasks Not Completed',
  2230. notConnect: 'Social platform is not connectted, skip',
  2231. tgTaskNotice: 'The telegram task is checked, need to do it yourself!',
  2232. confirmingTask: 'Confirming task...'
  2233. };
  2234. const en_US = en_US_data;
  2235. const languages = {
  2236. zh: zh_CN,
  2237. en: en_US
  2238. };
  2239. const language = [ 'zh', 'en' ].includes(globalOptions.other.language) ? globalOptions.other.language : 'en';
  2240. const I18n = (key, ...argvs) => {
  2241. if (!languages[language]?.[key]) {
  2242. return key;
  2243. }
  2244. return languages[language][key].replace(/%([\d]+)/g, (match, index) => argvs[parseInt(index, 10)]);
  2245. };
  2246. const i18n = I18n;
  2247. function throwError(error, name) {
  2248. if (window.TRACE) {
  2249. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  2250. }
  2251. external_Swal_default().fire({
  2252. title: i18n('errorReport'),
  2253. icon: 'error',
  2254. showCancelButton: true,
  2255. confirmButtonText: i18n('toGithub'),
  2256. showDenyButton: true,
  2257. denyButtonText: i18n('toKeylol'),
  2258. cancelButtonText: i18n('close')
  2259. }).then(({
  2260. isDenied,
  2261. isConfirmed
  2262. }) => {
  2263. if (isConfirmed) {
  2264. 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,
  2265. 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'))}`, {
  2266. active: true
  2267. });
  2268. } else if (isDenied) {
  2269. const text = `错误链接: [url=${window.location.href}]${window.location.href}[/url]
  2270.  
  2271. 环境:
  2272.  
  2273. [code]${JSON.stringify((0, javascript_utils_umd_min.ua)(), null, 4)}[/code]
  2274.  
  2275. 脚本管理器: ${GM_info.scriptHandler} ${GM_info.version}
  2276. 脚本版本: ${GM_info.script.version}
  2277.  
  2278. 报错信息:
  2279. [code]${error.stack}[/code]
  2280.  
  2281. 执行日志:
  2282. [code]${$.makeArray($('#auto-task-info>li')).map(element => element.innerText).join('\n')}[/code]`;
  2283. GM_setClipboard(text);
  2284. external_Swal_default().fire({
  2285. title: i18n('copySuccess'),
  2286. icon: 'success',
  2287. confirmButtonText: i18n('ok')
  2288. }).then(() => {
  2289. GM_openInTab('https://keylol.com/forum.php?mod=post&action=reply&fid=319&tid=777450', {
  2290. active: true
  2291. });
  2292. });
  2293. }
  2294. });
  2295. console.log('%c%s', 'color:white;background:red', `Auto-Task[Error]: ${name}\n${error.stack}`);
  2296. }
  2297. class Social {
  2298. tasks;
  2299. getRealParams(name, links, doTask, link2param) {
  2300. try {
  2301. let realParams = [];
  2302. if (links.length > 0) {
  2303. realParams = [ ...realParams, ...links.map(link => link2param(link)).filter(link => link) ];
  2304. }
  2305. if (!doTask && this.tasks[name].length > 0) {
  2306. realParams = [ ...realParams, ...this.tasks[name] ];
  2307. }
  2308. return unique(realParams);
  2309. } catch (error) {
  2310. throwError(error, 'Social.getRealParams');
  2311. return [];
  2312. }
  2313. }
  2314. }
  2315. const social_Social = Social;
  2316. class Discord extends social_Social {
  2317. tasks;
  2318. whiteList;
  2319. #auth = GM_getValue('discordAuth') || {};
  2320. #cache = GM_getValue('discordCache') || {};
  2321. #initialized = false;
  2322. constructor() {
  2323. super();
  2324. const defaultTasksTemplate = {
  2325. servers: []
  2326. };
  2327. this.tasks = defaultTasksTemplate;
  2328. this.whiteList = {
  2329. ...defaultTasksTemplate,
  2330. ...GM_getValue('whiteList')?.discord || {}
  2331. };
  2332. }
  2333. async init(action) {
  2334. try {
  2335. if (!GM_getValue('dontRemindDiscordAgain')) {
  2336. const result = await external_Swal_default().fire({
  2337. title: i18n('discordImportantNotice'),
  2338. text: i18n('discordImportantNoticeText'),
  2339. showCancelButton: true,
  2340. showDenyButton: true,
  2341. confirmButtonText: i18n('continue'),
  2342. cancelButtonText: i18n('skipDiscordTask'),
  2343. denyButtonText: i18n('continueAndDontRemindAgain')
  2344. }).then(({
  2345. isConfirmed,
  2346. isDenied
  2347. }) => {
  2348. if (isConfirmed) {
  2349. return true;
  2350. }
  2351. if (isDenied) {
  2352. GM_setValue('dontRemindDiscordAgain', true);
  2353. return true;
  2354. }
  2355. return false;
  2356. });
  2357. if (!result) {
  2358. this.#initialized = false;
  2359. return 'skip';
  2360. }
  2361. }
  2362. if (GM_getValue('dontRemindDiscordAgain') || action === 'do' && !globalOptions.doTask.discord.servers || action === 'undo' && !globalOptions.undoTask.discord.servers) {
  2363. this.#initialized = false;
  2364. return 'skip';
  2365. }
  2366. if (this.#initialized) {
  2367. return true;
  2368. }
  2369. if (!this.#auth.auth) {
  2370. if (await this.#updateAuth()) {
  2371. this.#initialized = true;
  2372. return true;
  2373. }
  2374. return false;
  2375. }
  2376. const isVerified = await this.#verifyAuth();
  2377. if (isVerified) {
  2378. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  2379. this.#initialized = true;
  2380. return true;
  2381. }
  2382. GM_setValue('discordAuth', {
  2383. auth: null
  2384. });
  2385. if (await this.#updateAuth()) {
  2386. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  2387. this.#initialized = true;
  2388. return true;
  2389. }
  2390. scripts_echoLog({}).error(i18n('initFailed', 'Discord'));
  2391. return false;
  2392. } catch (error) {
  2393. throwError(error, 'Discord.init');
  2394. return false;
  2395. }
  2396. }
  2397. async #verifyAuth() {
  2398. try {
  2399. const logStatus = scripts_echoLog({
  2400. text: i18n('verifyingAuth', 'Discord')
  2401. });
  2402. const {
  2403. result,
  2404. statusText,
  2405. status,
  2406. data
  2407. } = await tools_httpRequest({
  2408. url: 'https://discord.com/api/v6/users/@me',
  2409. method: 'HEAD',
  2410. headers: {
  2411. authorization: this.#auth.auth
  2412. }
  2413. });
  2414. if (result === 'Success') {
  2415. if (data?.status === 200) {
  2416. logStatus.success();
  2417. return true;
  2418. }
  2419. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2420. return false;
  2421. }
  2422. logStatus.error(`${result}:${statusText}(${status})`);
  2423. return false;
  2424. } catch (error) {
  2425. throwError(error, 'Discord.verifyAuth');
  2426. return false;
  2427. }
  2428. }
  2429. async #updateAuth() {
  2430. try {
  2431. const logStatus = scripts_echoLog({
  2432. text: i18n('updatingAuth', 'Discord')
  2433. });
  2434. return await new Promise(resolve => {
  2435. const newTab = GM_openInTab('https://discord.com/channels/@me', {
  2436. active: true,
  2437. insert: true,
  2438. setParent: true
  2439. });
  2440. newTab.name = 'ATv4_discordAuth';
  2441. newTab.onclose = async () => {
  2442. const auth = GM_getValue('discordAuth')?.auth;
  2443. if (auth) {
  2444. this.#auth = {
  2445. auth: auth
  2446. };
  2447. logStatus.success();
  2448. resolve(await this.#verifyAuth());
  2449. } else {
  2450. logStatus.error('Error: Update discord auth failed!');
  2451. resolve(false);
  2452. }
  2453. };
  2454. });
  2455. } catch (error) {
  2456. throwError(error, 'Discord.updateAuth');
  2457. return false;
  2458. }
  2459. }
  2460. async #joinServer(inviteId) {
  2461. try {
  2462. const logStatus = scripts_echoLog({
  2463. type: 'joiningDiscordServer',
  2464. text: inviteId
  2465. });
  2466. const {
  2467. result,
  2468. statusText,
  2469. status,
  2470. data
  2471. } = await tools_httpRequest({
  2472. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2473. method: 'POST',
  2474. dataType: 'json',
  2475. headers: {
  2476. authorization: this.#auth.auth,
  2477. origin: 'https://discord.com',
  2478. referer: `https://discord.com/invite/${inviteId}`
  2479. }
  2480. });
  2481. if (result === 'Success' && data?.status === 200) {
  2482. logStatus.success();
  2483. const guild = String(data.response?.guild?.id);
  2484. if (guild) {
  2485. this.#setCache(inviteId, guild);
  2486. this.tasks.servers = unique([ ...this.tasks.servers, inviteId ]);
  2487. }
  2488. return true;
  2489. }
  2490. logStatus.error(`${result}:${statusText}(${status})`);
  2491. return false;
  2492. } catch (error) {
  2493. throwError(error, 'Discord.joinServer');
  2494. return false;
  2495. }
  2496. }
  2497. async #leaveServer(inviteId) {
  2498. try {
  2499. if (this.whiteList.servers.includes(inviteId)) {
  2500. scripts_echoLog({
  2501. type: 'whiteList',
  2502. text: 'Discord.leaveServer',
  2503. id: inviteId
  2504. });
  2505. return true;
  2506. }
  2507. const guild = await this.#getGuild(inviteId);
  2508. if (!guild) {
  2509. return false;
  2510. }
  2511. const logStatus = scripts_echoLog({
  2512. type: 'leavingDiscordServer',
  2513. text: guild
  2514. });
  2515. const {
  2516. result,
  2517. statusText,
  2518. status,
  2519. data
  2520. } = await tools_httpRequest({
  2521. url: `https://discord.com/api/v9/users/@me/guilds/${guild}`,
  2522. method: 'DELETE',
  2523. headers: {
  2524. authorization: this.#auth.auth
  2525. }
  2526. });
  2527. if (result === 'Success' && data?.status === 204) {
  2528. logStatus.success();
  2529. return true;
  2530. }
  2531. logStatus.error(`${result}:${statusText}(${status})`);
  2532. return false;
  2533. } catch (error) {
  2534. throwError(error, 'Discord.leaveServer');
  2535. return false;
  2536. }
  2537. }
  2538. async #getGuild(inviteId) {
  2539. try {
  2540. const logStatus = scripts_echoLog({
  2541. type: 'gettingDiscordGuild',
  2542. text: inviteId
  2543. });
  2544. const guild = this.#cache[inviteId];
  2545. if (guild) {
  2546. logStatus.success();
  2547. return guild;
  2548. }
  2549. const {
  2550. result,
  2551. statusText,
  2552. status,
  2553. data
  2554. } = await tools_httpRequest({
  2555. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2556. responseType: 'json',
  2557. method: 'GET'
  2558. });
  2559. if (result === 'Success' && data?.status === 200) {
  2560. const guild = data.response?.guild?.id;
  2561. if (guild) {
  2562. logStatus.success();
  2563. this.#setCache(inviteId, guild);
  2564. return guild;
  2565. }
  2566. logStatus.error(`${result}:${statusText}(${status})`);
  2567. return false;
  2568. }
  2569. logStatus.error(`${result}:${statusText}(${status})`);
  2570. return false;
  2571. } catch (error) {
  2572. throwError(error, 'Discord.getGuild');
  2573. return false;
  2574. }
  2575. }
  2576. async toggle({
  2577. doTask = true,
  2578. serverLinks = []
  2579. }) {
  2580. try {
  2581. if (!this.#initialized) {
  2582. scripts_echoLog({
  2583. text: i18n('needInit')
  2584. });
  2585. return false;
  2586. }
  2587. const prom = [];
  2588. if (doTask && !globalOptions.doTask.discord.servers || !doTask && !globalOptions.undoTask.discord.servers) {
  2589. scripts_echoLog({
  2590. type: 'globalOptionsSkip',
  2591. text: 'discord.servers'
  2592. });
  2593. } else {
  2594. const realServers = this.getRealParams('servers', serverLinks, doTask, link => link.match(/invite\/(.+)/)?.[1]);
  2595. if (realServers.length > 0) {
  2596. for (const server of realServers) {
  2597. if (doTask) {
  2598. prom.push(this.#joinServer(server));
  2599. } else {
  2600. prom.push(this.#leaveServer(server));
  2601. }
  2602. await delay(1e3);
  2603. }
  2604. }
  2605. }
  2606. return await Promise.all(prom).then(() => true);
  2607. } catch (error) {
  2608. throwError(error, 'Discord.toggleServers');
  2609. return false;
  2610. }
  2611. }
  2612. #setCache(inviteId, guild) {
  2613. try {
  2614. this.#cache[inviteId] = guild;
  2615. GM_setValue('discordCache', this.#cache);
  2616. } catch (error) {
  2617. throwError(error, 'Discord.setCache');
  2618. }
  2619. }
  2620. }
  2621. const social_Discord = Discord;
  2622. class Instagram extends social_Social {
  2623. tasks;
  2624. whiteList;
  2625. #cache = GM_getValue('instagramCache') || {};
  2626. #auth = {};
  2627. #initialized = false;
  2628. constructor() {
  2629. super();
  2630. const defaultTasksTemplate = {
  2631. users: []
  2632. };
  2633. this.tasks = defaultTasksTemplate;
  2634. this.whiteList = {
  2635. ...defaultTasksTemplate,
  2636. ...GM_getValue('whiteList')?.instagram || {}
  2637. };
  2638. }
  2639. async init() {
  2640. try {
  2641. if (this.#initialized) {
  2642. return true;
  2643. }
  2644. const isVerified = await this.#getUserInfo();
  2645. if (isVerified) {
  2646. scripts_echoLog({}).success(i18n('initSuccess', 'Instagram'));
  2647. this.#initialized = true;
  2648. return true;
  2649. }
  2650. scripts_echoLog({}).error(i18n('initFailed', 'Instagram'));
  2651. return false;
  2652. } catch (error) {
  2653. throwError(error, 'Instagram.init');
  2654. return false;
  2655. }
  2656. }
  2657. async #getUserInfo(name = 'instagram') {
  2658. try {
  2659. const logStatus = scripts_echoLog({
  2660. type: name === 'instagram' ? 'verifyingInsAuth' : 'gettingInsUserId',
  2661. text: name
  2662. });
  2663. const userId = this.#cache[name];
  2664. if (userId && name !== 'instagram') {
  2665. logStatus.success();
  2666. return userId;
  2667. }
  2668. const {
  2669. result,
  2670. statusText,
  2671. status,
  2672. data
  2673. } = await tools_httpRequest({
  2674. url: `https://www.instagram.com/${name}/`,
  2675. method: 'GET'
  2676. });
  2677. if (result === 'Success') {
  2678. if (data?.finalUrl.includes('accounts/login')) {
  2679. logStatus.error(`Error:${i18n('loginIns')}`, true);
  2680. return false;
  2681. } else if (data?.finalUrl.includes('www.instagram.com/challenge')) {
  2682. logStatus.error(`Error:${i18n('insBanned')}`);
  2683. return false;
  2684. }
  2685. if (data?.status === 200) {
  2686. const csrftoken = data.responseText.match(/"csrf_token":"(.+?)"/)?.[1];
  2687. const hash = data.responseText.match(/"rollout_hash":"(.+?)"/)?.[1];
  2688. if (name === 'instagram') {
  2689. if (csrftoken && hash) {
  2690. this.#auth = {
  2691. csrftoken: csrftoken,
  2692. hash: hash
  2693. };
  2694. return true;
  2695. }
  2696. return false;
  2697. }
  2698. const id = data.responseText.match(/"profilePage_([\d]+?)"/)?.[1];
  2699. if (id) {
  2700. this.#setCache(name, id);
  2701. logStatus.success();
  2702. return id;
  2703. }
  2704. logStatus.error('Error: Get ins data error!');
  2705. return false;
  2706. }
  2707. logStatus.error(`${result}:${statusText}(${status})`);
  2708. return false;
  2709. }
  2710. return false;
  2711. } catch (error) {
  2712. throwError(error, 'Instagram.getUserInfo');
  2713. return false;
  2714. }
  2715. }
  2716. async #followUser(name) {
  2717. try {
  2718. const id = await this.#getUserInfo(name);
  2719. if (!id) {
  2720. return false;
  2721. }
  2722. const logStatus = scripts_echoLog({
  2723. type: 'followingIns',
  2724. text: name
  2725. });
  2726. const {
  2727. result,
  2728. statusText,
  2729. status,
  2730. data
  2731. } = await tools_httpRequest({
  2732. url: `https://www.instagram.com/web/friendships/${id}/follow/`,
  2733. method: 'POST',
  2734. dataType: 'json',
  2735. headers: {
  2736. 'x-csrftoken': this.#auth.csrftoken,
  2737. origin: 'https://www.instagram.com',
  2738. referer: `https://www.instagram.com/${name}/`,
  2739. 'content-type': 'application/x-www-form-urlencoded',
  2740. 'sec-fetch-site': 'same-origin',
  2741. 'x-instagram-ajax': this.#auth.hash
  2742. }
  2743. });
  2744. if (result === 'Success') {
  2745. if (data?.status === 200 && data.response?.result === 'following') {
  2746. logStatus.success();
  2747. this.tasks.users = unique([ ...this.tasks.users, name ]);
  2748. return true;
  2749. }
  2750. logStatus.error(`Error:${data?.response?.feedback_message || `${data?.statusText}(${data?.status})`}`);
  2751. return false;
  2752. }
  2753. logStatus.error(`${result}:${statusText}(${status})`);
  2754. return false;
  2755. } catch (error) {
  2756. throwError(error, 'Instagram.followUser');
  2757. return false;
  2758. }
  2759. }
  2760. async #unfollowUser(name) {
  2761. try {
  2762. if (this.whiteList.users.includes(name)) {
  2763. scripts_echoLog({
  2764. type: 'whiteList',
  2765. text: 'Instagram.unfollowUser',
  2766. id: name
  2767. });
  2768. return true;
  2769. }
  2770. const id = await this.#getUserInfo(name);
  2771. if (!id) {
  2772. return false;
  2773. }
  2774. const logStatus = scripts_echoLog({
  2775. type: 'unfollowingIns',
  2776. text: name
  2777. });
  2778. const {
  2779. result,
  2780. statusText,
  2781. status,
  2782. data
  2783. } = await tools_httpRequest({
  2784. url: `https://www.instagram.com/web/friendships/${id}/unfollow/`,
  2785. method: 'POST',
  2786. dataType: 'json',
  2787. headers: {
  2788. 'x-csrftoken': this.#auth.csrftoken,
  2789. origin: 'https://www.instagram.com',
  2790. referer: `https://www.instagram.com/${name}/`,
  2791. 'content-type': 'application/x-www-form-urlencoded',
  2792. 'sec-fetch-site': 'same-origin',
  2793. 'x-instagram-ajax': this.#auth.hash
  2794. }
  2795. });
  2796. if (result === 'Success') {
  2797. if (data?.status === 200 && data.response?.status === 'ok') {
  2798. logStatus.success();
  2799. return true;
  2800. }
  2801. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2802. return false;
  2803. }
  2804. logStatus.error(`${result}:${statusText}(${status})`);
  2805. return false;
  2806. } catch (error) {
  2807. throwError(error, 'Instagram.unfollowUser');
  2808. return false;
  2809. }
  2810. }
  2811. async toggle({
  2812. doTask = true,
  2813. userLinks = []
  2814. }) {
  2815. try {
  2816. if (!this.#initialized) {
  2817. scripts_echoLog({
  2818. text: i18n('needInit')
  2819. });
  2820. return false;
  2821. }
  2822. const prom = [];
  2823. if (doTask && !globalOptions.doTask.instagram.users || !doTask && !globalOptions.undoTask.instagram.users) {
  2824. scripts_echoLog({
  2825. type: 'globalOptionsSkip',
  2826. text: 'instagram.users'
  2827. });
  2828. } else {
  2829. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1]);
  2830. if (realUsers.length > 0) {
  2831. for (const username of realUsers) {
  2832. if (doTask) {
  2833. prom.push(this.#followUser(username));
  2834. } else {
  2835. prom.push(this.#unfollowUser(username));
  2836. }
  2837. await delay(1e3);
  2838. }
  2839. }
  2840. }
  2841. return await Promise.all(prom).then(() => true);
  2842. } catch (error) {
  2843. throwError(error, 'Instagram.toggleUsers');
  2844. return false;
  2845. }
  2846. }
  2847. #setCache(name, id) {
  2848. try {
  2849. this.#cache[name] = id;
  2850. GM_setValue('instagramCache', this.#cache);
  2851. } catch (error) {
  2852. throwError(error, 'Instagram.setCache');
  2853. }
  2854. }
  2855. }
  2856. const social_Instagram = Instagram;
  2857. class Reddit extends social_Social {
  2858. tasks;
  2859. whiteList;
  2860. #auth;
  2861. #initialized = false;
  2862. constructor() {
  2863. super();
  2864. const defaultTasksTemplate = {
  2865. reddits: []
  2866. };
  2867. this.tasks = defaultTasksTemplate;
  2868. this.whiteList = {
  2869. ...defaultTasksTemplate,
  2870. ...GM_getValue('whiteList')?.reddit || {}
  2871. };
  2872. }
  2873. async init() {
  2874. try {
  2875. if (this.#initialized) {
  2876. return true;
  2877. }
  2878. const isVerified = await this.#updateAuth();
  2879. if (isVerified) {
  2880. scripts_echoLog({}).success(i18n('initSuccess', 'Reddit'));
  2881. this.#initialized = true;
  2882. return true;
  2883. }
  2884. scripts_echoLog({}).error(i18n('initFailed', 'Reddit'));
  2885. return false;
  2886. } catch (error) {
  2887. throwError(error, 'Reddit.init');
  2888. return false;
  2889. }
  2890. }
  2891. async #useBeta() {
  2892. try {
  2893. const logStatus = scripts_echoLog({
  2894. text: i18n('changingRedditVersion')
  2895. });
  2896. return await new Promise(resolve => {
  2897. const newTab = GM_openInTab('https://www.reddit.com/', {
  2898. active: true,
  2899. insert: true,
  2900. setParent: true
  2901. });
  2902. newTab.name = 'ATv4_redditAuth';
  2903. newTab.onclose = async () => {
  2904. logStatus.success();
  2905. resolve(await this.#updateAuth(true));
  2906. };
  2907. });
  2908. } catch (error) {
  2909. throwError(error, 'Reddit.useBeta');
  2910. return false;
  2911. }
  2912. }
  2913. async #updateAuth(beta = false) {
  2914. try {
  2915. const logStatus = scripts_echoLog({
  2916. text: i18n('updatingAuth', 'Reddit')
  2917. });
  2918. const {
  2919. result,
  2920. statusText,
  2921. status,
  2922. data
  2923. } = await tools_httpRequest({
  2924. url: 'https://www.reddit.com/',
  2925. method: 'GET',
  2926. nochche: true,
  2927. headers: {
  2928. 'Cache-Control': 'no-cache'
  2929. }
  2930. });
  2931. if (result === 'Success') {
  2932. if (data?.responseText.includes('www.reddit.com/login/')) {
  2933. logStatus.error(`Error:${i18n('loginReddit')}`, true);
  2934. return false;
  2935. }
  2936. if (data?.status === 200) {
  2937. if (data.responseText.includes('redesign-beta-optin-btn') && !beta) {
  2938. return await this.#useBeta();
  2939. }
  2940. const accessToken = data.responseText.match(/"accessToken":"(.*?)","expires":"(.*?)"/)?.[1];
  2941. if (accessToken) {
  2942. this.#auth = {
  2943. token: accessToken
  2944. };
  2945. logStatus.success();
  2946. return true;
  2947. }
  2948. logStatus.error('Error: Parameter "accessToken" not found!');
  2949. return false;
  2950. }
  2951. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2952. return false;
  2953. }
  2954. logStatus.error(`${result}:${statusText}(${status})`);
  2955. return false;
  2956. } catch (error) {
  2957. throwError(error, 'Reddit.updateAuth');
  2958. return false;
  2959. }
  2960. }
  2961. async #toggleTask({
  2962. name,
  2963. doTask = true
  2964. }) {
  2965. try {
  2966. if (!doTask && this.whiteList.reddits.includes(name)) {
  2967. scripts_echoLog({
  2968. type: 'whiteList',
  2969. text: 'Reddit.undoTask',
  2970. id: name
  2971. });
  2972. return true;
  2973. }
  2974. let type = doTask ? 'joiningReddit' : 'leavingReddit';
  2975. if (/^u_/.test(name)) {
  2976. type = doTask ? 'followingRedditUser' : 'unfollowingRedditUser';
  2977. }
  2978. const logStatus = scripts_echoLog({
  2979. type: type,
  2980. text: name
  2981. });
  2982. const {
  2983. result,
  2984. statusText,
  2985. status,
  2986. data
  2987. } = await tools_httpRequest({
  2988. url: 'https://oauth.reddit.com/api/subscribe?redditWebClient=desktop2x&app=desktop2x-client-production&raw_json=1&gilding_detail=1',
  2989. method: 'POST',
  2990. headers: {
  2991. authorization: `Bearer ${this.#auth.token}`,
  2992. 'content-type': 'application/x-www-form-urlencoded'
  2993. },
  2994. data: $.param({
  2995. action: doTask ? 'sub' : 'unsub',
  2996. sr_name: name,
  2997. api_type: 'json'
  2998. })
  2999. });
  3000. if (result === 'Success') {
  3001. if (data?.status === 200) {
  3002. logStatus.success();
  3003. if (doTask) {
  3004. this.tasks.reddits = unique([ ...this.tasks.reddits, name ]);
  3005. }
  3006. return true;
  3007. }
  3008. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3009. return false;
  3010. }
  3011. logStatus.error(`${result}:${statusText}(${status})`);
  3012. return false;
  3013. } catch (error) {
  3014. throwError(error, 'Reddit.toggleTask');
  3015. return false;
  3016. }
  3017. }
  3018. async toggle({
  3019. doTask = true,
  3020. redditLinks = []
  3021. }) {
  3022. try {
  3023. if (!this.#initialized) {
  3024. scripts_echoLog({
  3025. text: i18n('needInit')
  3026. });
  3027. return false;
  3028. }
  3029. const prom = [];
  3030. if (doTask && !globalOptions.doTask.reddit.reddits || !doTask && !globalOptions.undoTask.reddit.reddits) {
  3031. scripts_echoLog({
  3032. type: 'globalOptionsSkip',
  3033. text: 'reddit.reddits'
  3034. });
  3035. } else {
  3036. const realReddits = this.getRealParams('reddits', redditLinks, doTask, link => {
  3037. const name = link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1];
  3038. const userName = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1];
  3039. if (userName) {
  3040. return name || userName;
  3041. }
  3042. return name;
  3043. });
  3044. if (realReddits.length > 0) {
  3045. for (const name of realReddits) {
  3046. prom.push(this.#toggleTask({
  3047. name: name,
  3048. doTask: doTask
  3049. }));
  3050. await delay(1e3);
  3051. }
  3052. }
  3053. }
  3054. return await Promise.all(prom).then(() => true);
  3055. } catch (error) {
  3056. throwError(error, 'Reddit.toggle');
  3057. return false;
  3058. }
  3059. }
  3060. }
  3061. const social_Reddit = Reddit;
  3062. class Twitch extends social_Social {
  3063. tasks;
  3064. whiteList;
  3065. #auth = GM_getValue('twitchAuth') || {};
  3066. #cache = GM_getValue('twitchCache') || {};
  3067. #initialized = false;
  3068. #integrityToken;
  3069. constructor() {
  3070. super();
  3071. const defaultTasksTemplate = {
  3072. channels: []
  3073. };
  3074. this.tasks = defaultTasksTemplate;
  3075. this.whiteList = {
  3076. ...defaultTasksTemplate,
  3077. ...GM_getValue('whiteList')?.twitch || {}
  3078. };
  3079. }
  3080. async init() {
  3081. try {
  3082. if (this.#initialized) {
  3083. return true;
  3084. }
  3085. if (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId) {
  3086. if (await this.#updateAuth()) {
  3087. this.#initialized = true;
  3088. return true;
  3089. }
  3090. return false;
  3091. }
  3092. const isVerified = await this.#verifyAuth(true);
  3093. if (isVerified) {
  3094. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  3095. this.#initialized = true;
  3096. return true;
  3097. }
  3098. GM_setValue('twitchAuth', null);
  3099. if (await this.#updateAuth()) {
  3100. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  3101. this.#initialized = true;
  3102. return true;
  3103. }
  3104. scripts_echoLog({}).error(i18n('initFailed', 'Twitch'));
  3105. return false;
  3106. } catch (error) {
  3107. throwError(error, 'Twitch.init');
  3108. return false;
  3109. }
  3110. }
  3111. async #verifyAuth(isFirst) {
  3112. try {
  3113. const logStatus = scripts_echoLog({
  3114. text: i18n('verifyingAuth', 'Twitch')
  3115. });
  3116. const {
  3117. result,
  3118. statusText,
  3119. status,
  3120. data
  3121. } = await tools_httpRequest({
  3122. url: 'https://gql.twitch.tv/gql',
  3123. method: 'POST',
  3124. dataType: 'json',
  3125. headers: {
  3126. Authorization: `OAuth ${this.#auth.authToken}`,
  3127. 'Client-Id': this.#auth.clientId
  3128. },
  3129. data: '[{"operationName":"FrontPageNew_User","variables":{"limit":1},"extensions":{"persistedQuery":{"version":1,' + '"sha256Hash":"64bd07a2cbaca80699d62636d966cf6395a5d14a1f0a14282067dcb28b13eb11"}}}]'
  3130. });
  3131. if (result === 'Success') {
  3132. if (data?.status === 200 && data.response?.[0]?.data?.currentUser) {
  3133. await this.#integrity(isFirst);
  3134. logStatus.success();
  3135. return true;
  3136. }
  3137. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3138. return false;
  3139. }
  3140. logStatus.error(`${result}:${statusText}(${status})`);
  3141. return false;
  3142. } catch (error) {
  3143. throwError(error, 'Twitch.verifyAuth');
  3144. return false;
  3145. }
  3146. }
  3147. async #integrity(isFirst = true, ct = '') {
  3148. try {
  3149. const logStatus = scripts_echoLog({
  3150. text: i18n('checkingTwitchIntegrity')
  3151. });
  3152. if (isFirst && (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId)) {
  3153. return await this.#updateAuth(false);
  3154. }
  3155. const {
  3156. result,
  3157. statusText,
  3158. status,
  3159. data
  3160. } = await tools_httpRequest({
  3161. url: 'https://gql.twitch.tv/integrity',
  3162. method: 'POST',
  3163. dataType: 'json',
  3164. anonymous: true,
  3165. headers: {
  3166. Origin: 'https://www.twitch.tv',
  3167. Referer: 'https://www.twitch.tv/',
  3168. Authorization: `OAuth ${this.#auth.authToken}`,
  3169. 'Client-Id': this.#auth.clientId,
  3170. 'Client-Version': this.#auth.clientVersion,
  3171. 'X-Device-Id': this.#auth.deviceId,
  3172. 'Client-Session-Id': this.#auth.clientSessionId,
  3173. 'x-kpsdk-ct': ct
  3174. }
  3175. });
  3176. if (result === 'Success') {
  3177. if (!ct && data?.responseHeaders?.['x-kpsdk-ct']) {
  3178. return await this.#integrity(isFirst, data.responseHeaders['x-kpsdk-ct']);
  3179. }
  3180. if (data?.status === 200 && data.response?.token) {
  3181. this.#integrityToken = data.response.token;
  3182. logStatus.success();
  3183. return true;
  3184. }
  3185. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3186. return false;
  3187. }
  3188. logStatus.error(`${result}:${statusText}(${status})`);
  3189. return false;
  3190. } catch (error) {
  3191. throwError(error, 'Twitch.integrity');
  3192. return false;
  3193. }
  3194. }
  3195. async #updateAuth(isFirst = true) {
  3196. try {
  3197. const logStatus = scripts_echoLog({
  3198. text: i18n('updatingAuth', 'Twitch')
  3199. });
  3200. return await new Promise(resolve => {
  3201. const newTab = GM_openInTab('https://www.twitch.tv/', {
  3202. active: true,
  3203. insert: true,
  3204. setParent: true
  3205. });
  3206. newTab.name = 'ATv4_twitchAuth';
  3207. newTab.onclose = async () => {
  3208. const auth = GM_getValue('twitchAuth');
  3209. if (auth) {
  3210. this.#auth = auth;
  3211. logStatus.success();
  3212. resolve(await this.#verifyAuth(isFirst));
  3213. } else {
  3214. logStatus.error('Error: Update twitch auth failed!');
  3215. resolve(false);
  3216. }
  3217. };
  3218. });
  3219. } catch (error) {
  3220. throwError(error, 'Twitch.updateAuth');
  3221. return false;
  3222. }
  3223. }
  3224. async #toggleChannel({
  3225. name,
  3226. doTask = true
  3227. }) {
  3228. try {
  3229. if (!doTask && this.whiteList.channels.includes(name)) {
  3230. scripts_echoLog({
  3231. type: 'whiteList',
  3232. text: 'Twitch.unfollowChannel',
  3233. id: name
  3234. });
  3235. return true;
  3236. }
  3237. const channelId = await this.#getChannelId(name);
  3238. if (!channelId) {
  3239. return false;
  3240. }
  3241. const logStatus = scripts_echoLog({
  3242. type: `${doTask ? '' : 'un'}followingTwitchChannel`,
  3243. text: name
  3244. });
  3245. const followData = `[{"operationName":"FollowButton_FollowUser","variables":{"input":{"disableNotifications":false,"targetID":"${channelId}` + '"}},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"800e7346bdf7e5278a3c1d3f21b2b56e2639928f86815677a7126b093b2fdd08"}}}]';
  3246. const unfollowData = `[{"operationName":"FollowButton_UnfollowUser","variables":{"input":{"targetID":"${channelId}"}},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"f7dae976ebf41c755ae2d758546bfd176b4eeb856656098bb40e0a672ca0d880"}}}]';
  3247. const {
  3248. result,
  3249. statusText,
  3250. status,
  3251. data
  3252. } = await tools_httpRequest({
  3253. url: 'https://gql.twitch.tv/gql',
  3254. method: 'POST',
  3255. dataType: 'json',
  3256. anonymous: true,
  3257. headers: {
  3258. Origin: 'https://www.twitch.tv',
  3259. Referer: 'https://www.twitch.tv/',
  3260. Authorization: `OAuth ${this.#auth.authToken}`,
  3261. 'Client-Id': this.#auth.clientId,
  3262. 'Client-Version': this.#auth.clientVersion,
  3263. 'X-Device-Id': this.#auth.deviceId,
  3264. 'Client-Session-Id': this.#auth.clientSessionId,
  3265. 'Client-Integrity': this.#integrityToken
  3266. },
  3267. data: doTask ? followData : unfollowData
  3268. });
  3269. if (result === 'Success') {
  3270. if (data?.status === 200 && data.response?.[0] && !data.response[0].errors) {
  3271. logStatus.success();
  3272. if (doTask) {
  3273. this.tasks.channels = unique([ ...this.tasks.channels, name ]);
  3274. }
  3275. return true;
  3276. }
  3277. logStatus.error(`Error:${data?.response?.[0].errors?.[0]?.message || `${data?.statusText}(${data?.status})`}`);
  3278. return false;
  3279. }
  3280. logStatus.error(`${result}:${statusText}(${status})`);
  3281. return false;
  3282. } catch (error) {
  3283. throwError(error, 'Twitch.toggleChannel');
  3284. return false;
  3285. }
  3286. }
  3287. async #getChannelId(name) {
  3288. try {
  3289. const logStatus = scripts_echoLog({
  3290. type: 'gettingTwitchChannelId',
  3291. text: name
  3292. });
  3293. const channelId = this.#cache[name];
  3294. if (channelId) {
  3295. logStatus.success();
  3296. return channelId;
  3297. }
  3298. const {
  3299. result,
  3300. statusText,
  3301. status,
  3302. data
  3303. } = await tools_httpRequest({
  3304. url: 'https://gql.twitch.tv/gql',
  3305. method: 'POST',
  3306. headers: {
  3307. Authorization: `OAuth ${this.#auth.authToken}`,
  3308. 'Client-Id': this.#auth.clientId
  3309. },
  3310. responseType: 'json',
  3311. data: `[{"operationName":"ActiveWatchParty","variables":{"channelLogin":"${name}"},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"4a8156c97b19e3a36e081cf6d6ddb5dbf9f9b02ae60e4d2ff26ed70aebc80a30"}}}]'
  3312. });
  3313. if (result === 'Success') {
  3314. if (data?.status === 200) {
  3315. const channelId = data.response?.[0]?.data?.user?.id;
  3316. if (channelId) {
  3317. this.#setCache(name, String(channelId));
  3318. logStatus.success();
  3319. return channelId;
  3320. }
  3321. logStatus.error(`Error:${data.statusText}(${data.status})`);
  3322. return false;
  3323. }
  3324. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3325. return false;
  3326. }
  3327. logStatus.error(`${result}:${statusText}(${status})`);
  3328. return false;
  3329. } catch (error) {
  3330. throwError(error, 'Twitch.getChannelId');
  3331. return false;
  3332. }
  3333. }
  3334. async toggle({
  3335. doTask = true,
  3336. channelLinks = []
  3337. }) {
  3338. try {
  3339. if (!this.#initialized) {
  3340. scripts_echoLog({
  3341. text: i18n('needInit')
  3342. });
  3343. return false;
  3344. }
  3345. const prom = [];
  3346. if (doTask && !globalOptions.doTask.twitch.channels || !doTask && !globalOptions.undoTask.twitch.channels) {
  3347. scripts_echoLog({
  3348. type: 'globalOptionsSkip',
  3349. text: 'twitch.channels'
  3350. });
  3351. } else {
  3352. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2]);
  3353. if (realChannels.length > 0) {
  3354. for (const channel of realChannels) {
  3355. prom.push(this.#toggleChannel({
  3356. name: channel,
  3357. doTask: doTask
  3358. }));
  3359. await delay(1e3);
  3360. }
  3361. }
  3362. }
  3363. return Promise.all(prom).then(() => true);
  3364. } catch (error) {
  3365. throwError(error, 'Twitch.toggle');
  3366. return false;
  3367. }
  3368. }
  3369. #setCache(name, id) {
  3370. try {
  3371. this.#cache[name] = id;
  3372. GM_setValue('twitchCache', this.#cache);
  3373. } catch (error) {
  3374. throwError(error, 'Twitch.setCache');
  3375. }
  3376. }
  3377. }
  3378. const social_Twitch = Twitch;
  3379. var main = __webpack_require__(356);
  3380. class Twitter extends social_Social {
  3381. tasks;
  3382. whiteList;
  3383. #verifyId = globalOptions.other.twitterVerifyId;
  3384. #auth = GM_getValue('twitterAuth') || {};
  3385. #cache = GM_getValue('twitterCache') || {};
  3386. #initialized = false;
  3387. #session;
  3388. constructor() {
  3389. super();
  3390. const defaultTasksTemplate = {
  3391. users: [],
  3392. retweets: [],
  3393. likes: []
  3394. };
  3395. this.tasks = defaultTasksTemplate;
  3396. this.whiteList = {
  3397. ...defaultTasksTemplate,
  3398. ...GM_getValue('whiteList')?.twitter || {}
  3399. };
  3400. }
  3401. async init() {
  3402. try {
  3403. if (this.#initialized) {
  3404. return true;
  3405. }
  3406. if (!this.#auth.ct0) {
  3407. if (await this.#updateAuth()) {
  3408. this.#initialized = true;
  3409. return true;
  3410. }
  3411. return false;
  3412. }
  3413. this.#session = await (0, main.createSession)();
  3414. const isVerified = await this.#verifyAuth();
  3415. if (isVerified) {
  3416. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  3417. this.#initialized = true;
  3418. return true;
  3419. }
  3420. GM_setValue('twitterAuth', null);
  3421. if (await this.#updateAuth()) {
  3422. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  3423. this.#initialized = true;
  3424. return true;
  3425. }
  3426. scripts_echoLog({}).error(i18n('initFailed', 'Twitter'));
  3427. return false;
  3428. } catch (error) {
  3429. throwError(error, 'Twitter.init');
  3430. return false;
  3431. }
  3432. }
  3433. async #verifyAuth() {
  3434. try {
  3435. return await this.#toggleUser({
  3436. name: 'verify',
  3437. doTask: true,
  3438. verify: true
  3439. });
  3440. } catch (error) {
  3441. throwError(error, 'Twitter.verifyAuth');
  3442. return false;
  3443. }
  3444. }
  3445. async #updateAuth() {
  3446. try {
  3447. const logStatus = scripts_echoLog({
  3448. text: i18n('updatingAuth', 'Twitter')
  3449. });
  3450. return await new Promise(resolve => {
  3451. GM_cookie.list({
  3452. url: 'https://x.com/settings/account'
  3453. }, async (cookies, error) => {
  3454. if (!error) {
  3455. const [ ct0, isLogin ] = cookies.map(cookie => [ 'ct0', 'twid' ].includes(cookie.name) ? cookie.value : null).filter(cookie => cookie);
  3456. if (isLogin && ct0) {
  3457. GM_setValue('twitterAuth', {
  3458. ct0: ct0
  3459. });
  3460. this.#auth = {
  3461. ct0: ct0
  3462. };
  3463. logStatus.success();
  3464. resolve(await this.#verifyAuth());
  3465. } else {
  3466. logStatus.error(i18n('needLogin'));
  3467. resolve(false);
  3468. }
  3469. } else {
  3470. logStatus.error('Error: Update twitter auth failed!');
  3471. resolve(false);
  3472. }
  3473. });
  3474. });
  3475. } catch (error) {
  3476. throwError(error, 'Twitter.updateToken');
  3477. return false;
  3478. }
  3479. }
  3480. async #toggleUser({
  3481. name,
  3482. doTask = true,
  3483. verify = false,
  3484. retry = false
  3485. }) {
  3486. try {
  3487. if (!doTask && !verify && this.whiteList.users.includes(name)) {
  3488. scripts_echoLog({
  3489. type: 'whiteList',
  3490. text: 'Twitter.unfollowUser',
  3491. id: name
  3492. });
  3493. return true;
  3494. }
  3495. const userId = verify ? this.#verifyId : await this.userName2id(name);
  3496. if (!userId) {
  3497. return false;
  3498. }
  3499. const logStatus = verify ? scripts_echoLog({
  3500. text: i18n('verifyingAuth', 'Twitter')
  3501. }) : scripts_echoLog({
  3502. type: `${doTask ? '' : 'un'}followingTwitterUser`,
  3503. text: name
  3504. });
  3505. const {
  3506. result,
  3507. statusText,
  3508. status,
  3509. data
  3510. } = await tools_httpRequest({
  3511. url: `https://x.com/i/api/1.1/friendships/${doTask ? 'create' : 'destroy'}.json`,
  3512. method: 'POST',
  3513. headers: {
  3514. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3515. 'Content-Type': 'application/x-www-form-urlencoded',
  3516. 'x-csrf-token': this.#auth.ct0,
  3517. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3518. 'X-Twitter-Active-User': 'yes',
  3519. 'x-client-transaction-id': await this.#session.get('POST', `/i/api/1.1/friendships/${doTask ? 'create' : 'destroy'}.json`)
  3520. },
  3521. responseType: 'json',
  3522. data: $.param({
  3523. include_profile_interstitial_type: 1,
  3524. include_blocking: 1,
  3525. include_blocked_by: 1,
  3526. include_followed_by: 1,
  3527. include_want_retweets: 1,
  3528. include_mute_edge: 1,
  3529. include_can_dm: 1,
  3530. include_can_media_tag: 1,
  3531. skip_status: 1,
  3532. id: userId
  3533. })
  3534. });
  3535. if (result === 'Success') {
  3536. if (data?.status === 200) {
  3537. logStatus.success();
  3538. if (doTask && !verify) {
  3539. this.tasks.users = unique([ ...this.tasks.users, name ]);
  3540. }
  3541. return true;
  3542. }
  3543. if (verify && data?.status === 403) {
  3544. if (data.response?.errors?.[0]?.code === 158) {
  3545. logStatus.success();
  3546. return true;
  3547. }
  3548. if (data.response?.errors?.[0]?.code === 353 && !retry && data.responseHeaders?.['set-cookie']) {
  3549. this.#auth.ct0 = data.responseHeaders['set-cookie']?.find(cookie => cookie.includes('ct0='))?.split(';')?.at(0)?.split('=')?.at(-1) || this.#auth.ct0;
  3550. logStatus.warning(i18n('retry'));
  3551. return this.#toggleUser({
  3552. name: name,
  3553. doTask: doTask,
  3554. verify: verify,
  3555. retry: true
  3556. });
  3557. }
  3558. }
  3559. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3560. return false;
  3561. }
  3562. logStatus.error(`${result}:${statusText}(${status})`);
  3563. return false;
  3564. } catch (error) {
  3565. throwError(error, 'Twitter.toggleUser');
  3566. return false;
  3567. }
  3568. }
  3569. async userName2id(name) {
  3570. try {
  3571. const logStatus = scripts_echoLog({
  3572. type: 'gettingTwitterUserId',
  3573. text: name
  3574. });
  3575. const userId = this.#cache[name];
  3576. if (userId) {
  3577. logStatus.success();
  3578. return userId;
  3579. }
  3580. const {
  3581. result,
  3582. statusText,
  3583. status,
  3584. data
  3585. } = await tools_httpRequest({
  3586. 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`,
  3587. method: 'GET',
  3588. headers: {
  3589. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3590. 'content-type': 'application/json',
  3591. referer: `https://x.com/${name}`,
  3592. 'x-csrf-token': this.#auth.ct0,
  3593. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3594. 'X-Twitter-Active-User': 'yes',
  3595. '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`)
  3596. },
  3597. responseType: 'json'
  3598. });
  3599. if (result === 'Success') {
  3600. if (data?.status === 200) {
  3601. let response = data.response || (typeof data.responseText === 'object' ? data.responseText : null);
  3602. if (!response) {
  3603. try {
  3604. response = JSON.parse(data.responseText);
  3605. } catch (error) {
  3606. response = null;
  3607. }
  3608. }
  3609. const userId = String(response?.data?.user?.result?.rest_id);
  3610. if (userId) {
  3611. this.#setCache(name, userId);
  3612. logStatus.success();
  3613. return userId;
  3614. }
  3615. logStatus.error(`Error:${data.statusText}(${data.status})`);
  3616. return false;
  3617. }
  3618. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3619. return false;
  3620. }
  3621. logStatus.error(`${result}:${statusText}(${status})`);
  3622. return false;
  3623. } catch (error) {
  3624. throwError(error, 'Twitter.getUserId');
  3625. return false;
  3626. }
  3627. }
  3628. async #toggleRetweet({
  3629. retweetId,
  3630. doTask = true
  3631. }) {
  3632. try {
  3633. if (!doTask && this.whiteList.retweets.includes(retweetId)) {
  3634. scripts_echoLog({
  3635. type: 'whiteList',
  3636. text: 'Twitter.unretweet',
  3637. id: retweetId
  3638. });
  3639. return true;
  3640. }
  3641. const logStatus = scripts_echoLog({
  3642. type: `${doTask ? '' : 'un'}retweetting`,
  3643. text: retweetId
  3644. });
  3645. const {
  3646. result,
  3647. statusText,
  3648. status,
  3649. data
  3650. } = await tools_httpRequest({
  3651. url: `https://x.com/i/api/graphql/${doTask ? 'ojPdsZsimiJrUGLR1sjUtA/CreateRetweet' : 'iQtK4dl5hBmXewYZuEOKVw/DeleteRetweet'}`,
  3652. method: 'POST',
  3653. headers: {
  3654. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3655. 'Content-Type': 'application/json',
  3656. origin: 'https://x.com',
  3657. referer: 'https://x.com/home',
  3658. 'x-csrf-token': this.#auth.ct0,
  3659. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3660. 'X-Twitter-Active-User': 'yes',
  3661. 'x-client-transaction-id': await this.#session.get('POST', `/i/api/graphql/${doTask ? 'ojPdsZsimiJrUGLR1sjUtA/CreateRetweet' : 'iQtK4dl5hBmXewYZuEOKVw/DeleteRetweet'}`)
  3662. },
  3663. data: `{"variables":{"${doTask ? '' : 'source_'}tweet_id":"${retweetId}","dark_request":false},"queryId":"${doTask ? 'ojPdsZsimiJrUGLR1sjUtA' : 'iQtK4dl5hBmXewYZuEOKVw'}"}`,
  3664. responseType: 'json'
  3665. });
  3666. if (result === 'Success') {
  3667. if (data?.status === 200 || data?.status === 403 && data.response?.errors?.[0]?.code === 327) {
  3668. if (data.response?.errors) {
  3669. logStatus.error(`Error:${data.response?.errors?.[0]?.message}`);
  3670. return false;
  3671. }
  3672. logStatus.success();
  3673. if (doTask) {
  3674. this.tasks.retweets = unique([ ...this.tasks.retweets, retweetId ]);
  3675. }
  3676. return true;
  3677. }
  3678. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3679. return false;
  3680. }
  3681. logStatus.error(`${result}:${statusText}(${status})`);
  3682. return false;
  3683. } catch (error) {
  3684. throwError(error, 'Twitter.toggleRetweet');
  3685. return false;
  3686. }
  3687. }
  3688. async toggle({
  3689. doTask = true,
  3690. userLinks = [],
  3691. retweetLinks = []
  3692. }) {
  3693. try {
  3694. if (!this.#initialized) {
  3695. scripts_echoLog({
  3696. text: i18n('needInit')
  3697. });
  3698. return false;
  3699. }
  3700. const prom = [];
  3701. if (doTask && !globalOptions.doTask.twitter.users || !doTask && !globalOptions.undoTask.twitter.users) {
  3702. scripts_echoLog({
  3703. type: 'globalOptionsSkip',
  3704. text: 'twitter.users'
  3705. });
  3706. } else {
  3707. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/x\.com\/(.+)/)?.[1] || link.match(/https:\/\/twitter\.com\/(.+)/)?.[1]);
  3708. if (realUsers.length > 0) {
  3709. for (const user of realUsers) {
  3710. prom.push(this.#toggleUser({
  3711. name: user,
  3712. doTask: doTask
  3713. }));
  3714. await delay(1e3);
  3715. }
  3716. }
  3717. }
  3718. if (doTask && !globalOptions.doTask.twitter.retweets || !doTask && !globalOptions.undoTask.twitter.retweets) {
  3719. scripts_echoLog({
  3720. type: 'globalOptionsSkip',
  3721. text: 'twitter.retweets'
  3722. });
  3723. } else {
  3724. const realRetweets = this.getRealParams('retweets', retweetLinks, doTask, link => link.match(/https:\/\/x\.com\/.*?\/status\/([\d]+)/)?.[1] || link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1]);
  3725. if (realRetweets.length > 0) {
  3726. for (const retweet of realRetweets) {
  3727. prom.push(this.#toggleRetweet({
  3728. retweetId: retweet,
  3729. doTask: doTask
  3730. }));
  3731. await delay(1e3);
  3732. }
  3733. }
  3734. }
  3735. return Promise.all(prom).then(() => true);
  3736. } catch (error) {
  3737. throwError(error, 'Twitter.toggle');
  3738. return false;
  3739. }
  3740. }
  3741. #setCache(name, id) {
  3742. try {
  3743. this.#cache[name] = id;
  3744. GM_setValue('twitterCache', this.#cache);
  3745. } catch (error) {
  3746. throwError(error, 'Twitter.setCache');
  3747. }
  3748. }
  3749. }
  3750. const social_Twitter = Twitter;
  3751. class Vk extends social_Social {
  3752. tasks;
  3753. whiteList;
  3754. #username = '';
  3755. #cache = GM_getValue('vkCache') || {};
  3756. #initialized = false;
  3757. constructor() {
  3758. super();
  3759. const defaultTasksTemplate = {
  3760. names: []
  3761. };
  3762. this.tasks = defaultTasksTemplate;
  3763. this.whiteList = {
  3764. ...defaultTasksTemplate,
  3765. ...GM_getValue('whiteList')?.vk || {}
  3766. };
  3767. }
  3768. async init() {
  3769. try {
  3770. if (this.#initialized) {
  3771. return true;
  3772. }
  3773. const isVerified = await this.#verifyAuth();
  3774. if (isVerified) {
  3775. scripts_echoLog({}).success(i18n('initSuccess', 'Vk'));
  3776. this.#initialized = true;
  3777. return true;
  3778. }
  3779. scripts_echoLog({}).error(i18n('initFailed', 'Vk'));
  3780. return false;
  3781. } catch (error) {
  3782. throwError(error, 'Vk.init');
  3783. return false;
  3784. }
  3785. }
  3786. async #verifyAuth() {
  3787. try {
  3788. const logStatus = scripts_echoLog({
  3789. text: i18n('verifyAuth', 'Vk')
  3790. });
  3791. const {
  3792. result,
  3793. statusText,
  3794. status,
  3795. data
  3796. } = await tools_httpRequest({
  3797. url: 'https://vk.com/im',
  3798. method: 'GET'
  3799. });
  3800. if (result === 'Success') {
  3801. if (data?.finalUrl.includes('vk.com/login')) {
  3802. logStatus.error(`Error:${i18n('loginVk')}`, true);
  3803. return false;
  3804. }
  3805. if (data?.status === 200) {
  3806. this.#username = data.responseText.match(/TopNavBtn__profileLink" href="\/(.*?)"/)?.[1] || '';
  3807. logStatus.success();
  3808. return true;
  3809. }
  3810. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3811. return false;
  3812. }
  3813. logStatus.error(`${result}:${statusText}(${status})`);
  3814. return false;
  3815. } catch (error) {
  3816. throwError(error, 'Vk.verifyAuth');
  3817. return false;
  3818. }
  3819. }
  3820. async #toggleGroup(name, dataParam, doTask = true) {
  3821. try {
  3822. const logStatus = scripts_echoLog({
  3823. type: doTask ? 'joiningVkGroup' : 'leavingVkGroup',
  3824. text: name
  3825. });
  3826. if (dataParam.groupAct === 'enter' && !doTask || dataParam.groupAct === 'leave' && doTask) {
  3827. logStatus.success();
  3828. return true;
  3829. }
  3830. const reqData = {
  3831. act: doTask ? 'enter' : 'leave',
  3832. al: 1,
  3833. gid: dataParam.groupId,
  3834. hash: dataParam.groupHash
  3835. };
  3836. if (doTask) {
  3837. reqData.context = '_';
  3838. }
  3839. const {
  3840. result,
  3841. statusText,
  3842. status,
  3843. data
  3844. } = await tools_httpRequest({
  3845. url: 'https://vk.com/al_groups.php',
  3846. method: 'POST',
  3847. headers: {
  3848. origin: 'https://vk.com',
  3849. referer: `https://vk.com/${name}`,
  3850. 'content-type': 'application/x-www-form-urlencoded'
  3851. },
  3852. data: $.param(reqData)
  3853. });
  3854. if (result === 'Success') {
  3855. if (data?.status === 200) {
  3856. logStatus.success();
  3857. if (doTask) {
  3858. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3859. }
  3860. return true;
  3861. }
  3862. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3863. return false;
  3864. }
  3865. logStatus.error(`${result}:${statusText}(${status})`);
  3866. return false;
  3867. } catch (error) {
  3868. throwError(error, 'Vk.toggleGroup');
  3869. return false;
  3870. }
  3871. }
  3872. async #togglePublic(name, dataParam, doTask = true) {
  3873. try {
  3874. const logStatus = scripts_echoLog({
  3875. type: doTask ? 'joiningVkPublic' : 'leavingVkPublic',
  3876. text: name
  3877. });
  3878. if (dataParam.publicJoined && doTask || !dataParam.publicJoined && !doTask) {
  3879. logStatus.success();
  3880. return true;
  3881. }
  3882. const {
  3883. result,
  3884. statusText,
  3885. status,
  3886. data
  3887. } = await tools_httpRequest({
  3888. url: 'https://vk.com/al_public.php',
  3889. method: 'POST',
  3890. headers: {
  3891. origin: 'https://vk.com',
  3892. referer: `https://vk.com/${name}`,
  3893. 'content-type': 'application/x-www-form-urlencoded'
  3894. },
  3895. data: $.param({
  3896. act: doTask ? 'a_enter' : 'a_leave',
  3897. al: 1,
  3898. pid: dataParam.publicPid,
  3899. hash: dataParam.publicHash
  3900. })
  3901. });
  3902. if (result === 'Success') {
  3903. if (data?.status === 200) {
  3904. logStatus.success();
  3905. if (doTask) {
  3906. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3907. }
  3908. return true;
  3909. }
  3910. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3911. return false;
  3912. }
  3913. logStatus.error(`${result}:${statusText}(${status})`);
  3914. return false;
  3915. } catch (error) {
  3916. throwError(error, 'Vk.togglePublic');
  3917. return false;
  3918. }
  3919. }
  3920. async #toggleLikeWall(name, dataParam, doTask = true) {
  3921. try {
  3922. const logStatus = scripts_echoLog({
  3923. type: doTask ? 'likingVkPublic' : 'unlikingVkPublic',
  3924. text: name
  3925. });
  3926. const postData = {
  3927. act: 'a_set_reaction',
  3928. al: 1,
  3929. event_subtype: 'post_modal',
  3930. from: 'wall_page',
  3931. hash: dataParam.hash,
  3932. object: dataParam.object,
  3933. track_code: dataParam.trackCode,
  3934. wall: 2
  3935. };
  3936. if (doTask) {
  3937. postData.reaction_id = 0;
  3938. }
  3939. const {
  3940. result: resultR,
  3941. statusText: statusTextR,
  3942. status: statusR,
  3943. data: dataR
  3944. } = await tools_httpRequest({
  3945. url: 'https://vk.com/like.php?act=a_set_reaction',
  3946. method: 'POST',
  3947. headers: {
  3948. origin: 'https://vk.com',
  3949. referer: `https://vk.com/${name}`,
  3950. 'content-type': 'application/x-www-form-urlencoded'
  3951. },
  3952. data: $.param(postData)
  3953. });
  3954. if (resultR === 'Success') {
  3955. if (dataR?.status === 200) {
  3956. if (dataR.response?.payload?.[1]?.[1]?.like_my === true) {
  3957. logStatus.success();
  3958. return true;
  3959. }
  3960. }
  3961. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  3962. return false;
  3963. }
  3964. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  3965. return false;
  3966. } catch (error) {
  3967. throwError(error, 'Vk.sendWall');
  3968. return false;
  3969. }
  3970. }
  3971. async #sendWall(name) {
  3972. try {
  3973. const logStatus = scripts_echoLog({
  3974. type: 'sendingVkWall',
  3975. text: name
  3976. });
  3977. const {
  3978. result,
  3979. statusText,
  3980. status,
  3981. data
  3982. } = await tools_httpRequest({
  3983. url: 'https://vk.com/like.php',
  3984. method: 'POST',
  3985. headers: {
  3986. origin: 'https://vk.com',
  3987. referer: `https://vk.com/${name}`,
  3988. 'content-type': 'application/x-www-form-urlencoded'
  3989. },
  3990. data: $.param({
  3991. act: 'publish_box',
  3992. al: 1,
  3993. object: name
  3994. })
  3995. });
  3996. if (result === 'Success') {
  3997. if (data?.status === 200) {
  3998. const hash = data.responseText.match(/shHash:[\s]*'(.*?)'/)?.[1];
  3999. if (hash) {
  4000. const {
  4001. result: resultR,
  4002. statusText: statusTextR,
  4003. status: statusR,
  4004. data: dataR
  4005. } = await tools_httpRequest({
  4006. url: 'https://vk.com/like.php',
  4007. method: 'POST',
  4008. headers: {
  4009. origin: 'https://vk.com',
  4010. referer: `https://vk.com/${name}`,
  4011. 'content-type': 'application/x-www-form-urlencoded'
  4012. },
  4013. data: $.param({
  4014. Message: '',
  4015. act: 'a_do_publish',
  4016. al: 1,
  4017. close_comments: 0,
  4018. friends_only: 0,
  4019. from: 'box',
  4020. hash: hash,
  4021. list: '',
  4022. mark_as_ads: 0,
  4023. mute_notifications: 0,
  4024. object: name,
  4025. ret_data: 1,
  4026. to: 0
  4027. })
  4028. });
  4029. if (resultR === 'Success') {
  4030. if (dataR?.status === 200) {
  4031. const jsonData = JSON.parse(dataR.responseText?.replace('\x3c!--', '') || '{}');
  4032. if (jsonData?.payload?.[1]?.[1]?.share_my === true) {
  4033. logStatus.success();
  4034. const postId = String(jsonData?.payload?.[1]?.[1]?.post_id);
  4035. const ownerId = String(jsonData?.payload?.[1]?.[1]?.owner_id);
  4036. if (postId && ownerId) {
  4037. this.#setCache(name, `${ownerId}_${postId}`);
  4038. }
  4039. this.tasks.names = unique([ ...this.tasks.names, name ]);
  4040. return true;
  4041. }
  4042. }
  4043. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  4044. return false;
  4045. }
  4046. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  4047. return false;
  4048. }
  4049. logStatus.error('Error: Get "hash" failed');
  4050. return false;
  4051. }
  4052. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4053. return false;
  4054. }
  4055. logStatus.error(`${result}:${statusText}(${status})`);
  4056. return false;
  4057. } catch (error) {
  4058. throwError(error, 'Vk.sendWall');
  4059. return false;
  4060. }
  4061. }
  4062. async #deleteWall(name, dataParams) {
  4063. try {
  4064. const logStatus = scripts_echoLog({
  4065. type: 'deletingVkWall',
  4066. text: name
  4067. });
  4068. const {
  4069. result,
  4070. statusText,
  4071. status,
  4072. data
  4073. } = await tools_httpRequest({
  4074. url: 'https://vk.com/al_wall.php?act=delete',
  4075. method: 'POST',
  4076. headers: {
  4077. origin: 'https://vk.com',
  4078. referer: `https://vk.com/${this.#username}?w=wall${this.#cache[name]}%2Fall`,
  4079. 'content-type': 'application/x-www-form-urlencoded'
  4080. },
  4081. data: $.param({
  4082. act: 'delete',
  4083. al: 1,
  4084. confirm: 0,
  4085. from: 'wkview',
  4086. hash: dataParams.wallHash,
  4087. post: this.#cache[name]
  4088. })
  4089. });
  4090. if (result === 'Success') {
  4091. if (data?.status === 200) {
  4092. const jsonData = JSON.parse(data.responseText?.replace('\x3c!--', '') || '{}');
  4093. if (jsonData?.payload?.[1]?.[1]) {
  4094. logStatus.success();
  4095. return true;
  4096. }
  4097. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4098. return false;
  4099. }
  4100. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4101. return false;
  4102. }
  4103. logStatus.error(`${result}:${statusText}(${status})`);
  4104. return false;
  4105. } catch (error) {
  4106. throwError(error, 'Vk.deleteWall');
  4107. return false;
  4108. }
  4109. }
  4110. async #getId(name, doTask) {
  4111. try {
  4112. let url = `https://vk.com/${name}`;
  4113. if (/^wall-/.test(name)) {
  4114. if (doTask) {
  4115. return {
  4116. type: 'sendWall'
  4117. };
  4118. }
  4119. if (!this.#cache[name]) {
  4120. return {
  4121. type: 'unSupport'
  4122. };
  4123. }
  4124. url = `https://vk.com/${this.#username}?w=wall${this.#cache[name]}`;
  4125. }
  4126. const logStatus = scripts_echoLog({
  4127. type: 'gettingVkId',
  4128. text: name
  4129. });
  4130. const {
  4131. result,
  4132. statusText,
  4133. status,
  4134. data
  4135. } = await tools_httpRequest({
  4136. url: url,
  4137. method: 'GET'
  4138. });
  4139. if (result === 'Success') {
  4140. if (data?.status === 200) {
  4141. const [ , groupAct, groupId, , groupHash ] = data.responseText.match(/Groups.(enter|leave)\(.*?,.*?([\d]+?), (&#39;|')(.*?)(&#39;|')/) || [];
  4142. const publicHash = data.responseText.match(/"enterHash":"(.*?)"/)?.[1];
  4143. const publicPid = data.responseText.match(/"public_id":([\d]+?),/)?.[1];
  4144. const publicJoined = !data.responseText.includes('Public.subscribe');
  4145. if (groupAct && groupId && groupHash) {
  4146. logStatus.success();
  4147. return {
  4148. groupAct: groupAct,
  4149. groupId: groupId,
  4150. groupHash: groupHash,
  4151. type: 'group'
  4152. };
  4153. } else if (publicHash && publicPid) {
  4154. logStatus.success();
  4155. return {
  4156. publicHash: publicHash,
  4157. publicPid: publicPid,
  4158. publicJoined: publicJoined,
  4159. type: 'public'
  4160. };
  4161. } else if (name.includes('action=like')) {
  4162. const hash = data.responseText.match(/data-reaction-hash="(.*?)"/)?.[1];
  4163. const trackCode = data.responseText.match(/data-post-track-code="(.*?)"/)?.[1];
  4164. const object = name.match(/wall-[\w_]+/)?.[0];
  4165. if (hash && trackCode && object) {
  4166. logStatus.success();
  4167. return {
  4168. type: 'likeWall',
  4169. hash: hash,
  4170. trackCode: trackCode,
  4171. object: object
  4172. };
  4173. }
  4174. } else if (data.responseText.includes('wall.deletePost') && !doTask) {
  4175. const wallHash = data.responseText.match(/wall\.deletePost\(this, '.*?', '(.*?)'\)/)?.[1];
  4176. if (wallHash) {
  4177. logStatus.success();
  4178. return {
  4179. type: 'deleteWall',
  4180. wallHash: wallHash
  4181. };
  4182. }
  4183. } else if (name.includes('wall') && doTask) {
  4184. logStatus.success();
  4185. return {
  4186. type: 'sendWall'
  4187. };
  4188. }
  4189. logStatus.error('Error: Parameters not found!');
  4190. return false;
  4191. }
  4192. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4193. return false;
  4194. }
  4195. logStatus.error(`${result}:${statusText}(${status})`);
  4196. return false;
  4197. } catch (error) {
  4198. throwError(error, 'Vk.getId');
  4199. return false;
  4200. }
  4201. }
  4202. async #toggleVk({
  4203. name,
  4204. doTask = true
  4205. }) {
  4206. try {
  4207. if (!doTask && this.whiteList.names.includes(name)) {
  4208. scripts_echoLog({
  4209. type: 'whiteList',
  4210. text: 'Vk.undoTask',
  4211. id: name
  4212. });
  4213. return true;
  4214. }
  4215. const formatName = name.replace(/\/$/, '');
  4216. const data = await this.#getId(formatName, doTask);
  4217. if (!data) {
  4218. return false;
  4219. }
  4220. switch (data.type) {
  4221. case 'group':
  4222. return await this.#toggleGroup(formatName, data, doTask);
  4223.  
  4224. case 'public':
  4225. return await this.#togglePublic(formatName, data, doTask);
  4226.  
  4227. case 'likeWall':
  4228. return await this.#toggleLikeWall(formatName, data, doTask);
  4229.  
  4230. case 'sendWall':
  4231. return doTask ? await this.#sendWall(formatName) : true;
  4232.  
  4233. case 'deleteWall':
  4234. return doTask ? true : await this.#deleteWall(formatName, data);
  4235.  
  4236. default:
  4237. return false;
  4238. }
  4239. } catch (error) {
  4240. throwError(error, 'Vk.toggleVk');
  4241. return false;
  4242. }
  4243. }
  4244. async toggle({
  4245. doTask = true,
  4246. nameLinks = []
  4247. }) {
  4248. try {
  4249. if (!this.#initialized) {
  4250. scripts_echoLog({
  4251. text: i18n('needInit')
  4252. });
  4253. return false;
  4254. }
  4255. const prom = [];
  4256. if (doTask && !globalOptions.doTask.vk.names || !doTask && !globalOptions.undoTask.vk.names) {
  4257. scripts_echoLog({
  4258. type: 'globalOptionsSkip',
  4259. text: 'vk.names'
  4260. });
  4261. } else {
  4262. const realNames = this.getRealParams('names', nameLinks, doTask, link => link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1]);
  4263. if (realNames.length > 0) {
  4264. for (const name of realNames) {
  4265. prom.push(this.#toggleVk({
  4266. name: name,
  4267. doTask: doTask
  4268. }));
  4269. await delay(1e3);
  4270. }
  4271. }
  4272. }
  4273. return Promise.all(prom).then(() => true);
  4274. } catch (error) {
  4275. throwError(error, 'Vk.toggle');
  4276. return false;
  4277. }
  4278. }
  4279. #setCache(name, postId) {
  4280. try {
  4281. this.#cache[name] = postId;
  4282. GM_setValue('vkCache', this.#cache);
  4283. } catch (error) {
  4284. throwError(error, 'Vk.setCache');
  4285. }
  4286. }
  4287. }
  4288. const social_Vk = Vk;
  4289. const getInfo = async function(link, type) {
  4290. try {
  4291. const logStatus = scripts_echoLog({
  4292. text: i18n('gettingYtbToken')
  4293. });
  4294. const {
  4295. result,
  4296. statusText,
  4297. status,
  4298. data
  4299. } = await tools_httpRequest({
  4300. url: link,
  4301. method: 'GET'
  4302. });
  4303. if (result === 'Success') {
  4304. if (data?.status === 200) {
  4305. if (data.responseText.includes('accounts.google.com/ServiceLogin?service=youtube')) {
  4306. logStatus.error(`Error:${i18n('loginYtb')}`, true);
  4307. return {
  4308. needLogin: true
  4309. };
  4310. }
  4311. const apiKey = data.responseText.match(/"INNERTUBE_API_KEY":"(.*?)"/)?.[1];
  4312. const context = (data.responseText.match(/\(\{"INNERTUBE_CONTEXT":([\w\W]*?)\}\)/) || data.responseText.match(/"INNERTUBE_CONTEXT":([\w\W]*?\}),"INNERTUBE/))?.[1] || '{}';
  4313. const {
  4314. client,
  4315. request
  4316. } = JSON.parse(context);
  4317. if (apiKey && client && request) {
  4318. client.hl = 'en';
  4319. if (type === 'channel') {
  4320. const channelId = data.responseText.match(/"channelId":"(.+?)"/)?.[1];
  4321. if (channelId) {
  4322. logStatus.success();
  4323. return {
  4324. params: {
  4325. apiKey: apiKey,
  4326. client: client,
  4327. request: request,
  4328. channelId: channelId
  4329. }
  4330. };
  4331. }
  4332. logStatus.error('Error: Get "channelId" failed!');
  4333. return {};
  4334. } else if (type === 'likeVideo') {
  4335. const videoId = data.responseText.match(/<link rel="shortlinkUrl" href="https:\/\/youtu\.be\/(.*?)">/)?.[1];
  4336. const likeParams = data.responseText.match(/"likeParams":"(.*?)"/)?.[1];
  4337. if (videoId) {
  4338. logStatus.success();
  4339. return {
  4340. params: {
  4341. apiKey: apiKey,
  4342. client: client,
  4343. request: request,
  4344. videoId: videoId,
  4345. likeParams: likeParams
  4346. }
  4347. };
  4348. }
  4349. logStatus.error('Error: Get "videoId" failed!');
  4350. return {};
  4351. }
  4352. logStatus.error('Error: Unknown type');
  4353. return {};
  4354. }
  4355. logStatus.error('Error: Parameter "apiKey" not found!');
  4356. return {};
  4357. }
  4358. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4359. return {};
  4360. }
  4361. logStatus.error(`${result}:${statusText}(${status})`);
  4362. return {};
  4363. } catch (error) {
  4364. throwError(error, 'Youtube.getInfo');
  4365. return {};
  4366. }
  4367. };
  4368. class Youtube extends social_Social {
  4369. tasks;
  4370. whiteList;
  4371. #auth = GM_getValue('youtubeAuth') || {};
  4372. #initialized = false;
  4373. #verifyChannel = `https://www.youtube.com/channel/${globalOptions.other.youtubeVerifyChannel}`;
  4374. constructor() {
  4375. super();
  4376. const defaultTasksTemplate = {
  4377. channels: [],
  4378. likes: []
  4379. };
  4380. this.tasks = defaultTasksTemplate;
  4381. this.whiteList = {
  4382. ...defaultTasksTemplate,
  4383. ...GM_getValue('whiteList')?.youtube || {}
  4384. };
  4385. }
  4386. async init() {
  4387. try {
  4388. if (this.#initialized) {
  4389. return true;
  4390. }
  4391. if (!this.#auth.PAPISID) {
  4392. if (await this.#updateAuth()) {
  4393. this.#initialized = true;
  4394. return true;
  4395. }
  4396. return false;
  4397. }
  4398. const isVerified = await this.#verifyAuth();
  4399. if (isVerified) {
  4400. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  4401. this.#initialized = true;
  4402. return true;
  4403. }
  4404. GM_setValue('youtubeAuth', null);
  4405. if (await this.#updateAuth()) {
  4406. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  4407. this.#initialized = true;
  4408. return true;
  4409. }
  4410. scripts_echoLog({}).error(i18n('initFailed', 'Youtube'));
  4411. return false;
  4412. } catch (error) {
  4413. throwError(error, 'Youtube.init');
  4414. return false;
  4415. }
  4416. }
  4417. async #verifyAuth() {
  4418. try {
  4419. return await this.#toggleChannel({
  4420. link: this.#verifyChannel,
  4421. doTask: true,
  4422. verify: true
  4423. });
  4424. } catch (error) {
  4425. throwError(error, 'Youtube.verifyAuth');
  4426. return false;
  4427. }
  4428. }
  4429. async #updateAuth() {
  4430. try {
  4431. const logStatus = scripts_echoLog({
  4432. text: i18n('updatingAuth', 'Youtube')
  4433. });
  4434. return await new Promise(resolve => {
  4435. GM_cookie.list({
  4436. url: 'https://www.youtube.com/@YouTube'
  4437. }, async (cookies, error) => {
  4438. if (!error) {
  4439. const PAPISID = cookies.find(cookie => cookie.name === '__Secure-3PAPISID')?.value;
  4440. if (PAPISID) {
  4441. GM_setValue('youtubeAuth', {
  4442. PAPISID: PAPISID
  4443. });
  4444. this.#auth = {
  4445. PAPISID: PAPISID
  4446. };
  4447. logStatus.success();
  4448. resolve(await this.#verifyAuth());
  4449. } else {
  4450. logStatus.error(i18n('needLogin'));
  4451. resolve(false);
  4452. }
  4453. } else {
  4454. logStatus.error('Error: Update youtube auth failed!');
  4455. resolve(false);
  4456. }
  4457. });
  4458. });
  4459. } catch (error) {
  4460. throwError(error, 'Youtube.updateAuth');
  4461. return false;
  4462. }
  4463. }
  4464. #getInfo(link, type) {
  4465. return getInfo(link, type);
  4466. }
  4467. async #toggleChannel({
  4468. link,
  4469. doTask = true,
  4470. verify = false
  4471. }) {
  4472. try {
  4473. const {
  4474. params,
  4475. needLogin
  4476. } = await this.#getInfo(link, 'channel');
  4477. const {
  4478. apiKey,
  4479. client,
  4480. request,
  4481. channelId
  4482. } = params || {};
  4483. if (needLogin) {
  4484. scripts_echoLog({
  4485. html: i18n('loginYtb')
  4486. });
  4487. return false;
  4488. }
  4489. if (!(apiKey && client && request && channelId)) {
  4490. scripts_echoLog({
  4491. text: '"getYtbToken" failed'
  4492. });
  4493. return false;
  4494. }
  4495. if (!doTask && !verify && this.whiteList.channels.includes(channelId)) {
  4496. scripts_echoLog({
  4497. type: 'whiteList',
  4498. text: 'Youtube.unfollowChannel',
  4499. id: channelId
  4500. });
  4501. return true;
  4502. }
  4503. const logStatus = verify ? scripts_echoLog({
  4504. text: i18n('verifyingAuth', 'Youtube')
  4505. }) : scripts_echoLog({
  4506. type: doTask ? 'followingYtbChannel' : 'unfollowingYtbChannel',
  4507. text: channelId
  4508. });
  4509. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  4510. const {
  4511. result,
  4512. statusText,
  4513. status,
  4514. data
  4515. } = await tools_httpRequest({
  4516. url: `https://www.youtube.com/youtubei/v1/subscription/${doTask ? '' : 'un'}subscribe?key=${apiKey}&prettyPrint=false`,
  4517. method: 'POST',
  4518. headers: {
  4519. origin: 'https://www.youtube.com',
  4520. referer: `https://www.youtube.com/channel/${channelId}`,
  4521. 'content-type': 'application/json',
  4522. 'x-goog-authuser': '0',
  4523. 'x-goog-visitor-id': client?.visitorData,
  4524. 'x-origin': 'https://www.youtube.com',
  4525. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  4526. },
  4527. data: JSON.stringify({
  4528. context: {
  4529. client: client,
  4530. request: {
  4531. sessionId: request?.sessionId,
  4532. internalExperimentFlags: [],
  4533. consistencyTokenJars: []
  4534. },
  4535. user: {}
  4536. },
  4537. channelIds: [ channelId ],
  4538. params: doTask ? 'EgIIAhgA' : 'CgIIAhgA'
  4539. })
  4540. });
  4541. if (result === 'Success') {
  4542. if (data?.status === 200) {
  4543. if (doTask && (/"subscribed":true/.test(data.responseText) || data.responseText.includes('The subscription already exists')) || !doTask && /"subscribed":false/.test(data.responseText)) {
  4544. logStatus.success();
  4545. if (doTask && !verify) {
  4546. this.tasks.channels = unique([ ...this.tasks.channels, link ]);
  4547. }
  4548. return true;
  4549. }
  4550. if (verify && data.responseText.includes('You may not subscribe to yourself')) {
  4551. logStatus.success();
  4552. return true;
  4553. }
  4554. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4555. return false;
  4556. }
  4557. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4558. return false;
  4559. }
  4560. logStatus.error(`${result}:${statusText}(${status})`);
  4561. return false;
  4562. } catch (error) {
  4563. throwError(error, 'Youtube.toggleChannel');
  4564. return false;
  4565. }
  4566. }
  4567. async #toggleLikeVideo({
  4568. link,
  4569. doTask = true
  4570. }) {
  4571. try {
  4572. const {
  4573. params,
  4574. needLogin
  4575. } = await this.#getInfo(link, 'likeVideo');
  4576. const {
  4577. apiKey,
  4578. client,
  4579. request,
  4580. videoId,
  4581. likeParams
  4582. } = params || {};
  4583. if (needLogin) {
  4584. scripts_echoLog({
  4585. html: `${i18n('loginYtb')}`
  4586. });
  4587. return false;
  4588. }
  4589. if (!(apiKey && client && request && videoId && likeParams)) {
  4590. scripts_echoLog({
  4591. text: '"getYtbToken" failed'
  4592. });
  4593. return false;
  4594. }
  4595. if (!doTask && this.whiteList.likes.includes(videoId)) {
  4596. scripts_echoLog({
  4597. type: 'whiteList',
  4598. text: 'Youtube.unlikeVideo',
  4599. id: videoId
  4600. });
  4601. return true;
  4602. }
  4603. const logStatus = scripts_echoLog({
  4604. type: doTask ? 'likingYtbVideo' : 'unlikingYtbVideo',
  4605. text: videoId
  4606. });
  4607. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  4608. const likeVideoData = {
  4609. context: {
  4610. client: client,
  4611. request: {
  4612. sessionId: request.sessionId,
  4613. internalExperimentFlags: [],
  4614. consistencyTokenJars: []
  4615. },
  4616. user: {}
  4617. },
  4618. target: {
  4619. videoId: videoId
  4620. }
  4621. };
  4622. if (doTask) {
  4623. if (likeParams) {
  4624. likeVideoData.params = likeParams;
  4625. } else {
  4626. logStatus.error('Empty likeParams');
  4627. return false;
  4628. }
  4629. }
  4630. const {
  4631. result,
  4632. statusText,
  4633. status,
  4634. data
  4635. } = await tools_httpRequest({
  4636. url: `https://www.youtube.com/youtubei/v1/like/${doTask ? '' : 'remove'}like?key=${apiKey}`,
  4637. method: 'POST',
  4638. headers: {
  4639. origin: 'https://www.youtube.com',
  4640. referer: `https://www.youtube.com/watch?v=${videoId}`,
  4641. 'content-type': 'application/json',
  4642. 'x-goog-authuser': '0',
  4643. 'x-goog-visitor-id': client.visitorData,
  4644. 'x-origin': 'https://www.youtube.com',
  4645. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  4646. },
  4647. data: JSON.stringify(likeVideoData)
  4648. });
  4649. if (result === 'Success') {
  4650. if (data?.status === 200) {
  4651. if (doTask && data.responseText.includes('Added to Liked videos') || !doTask && (data.responseText.includes('Removed from Liked videos') || data.responseText.includes('Dislike removed'))) {
  4652. logStatus.success();
  4653. if (doTask) {
  4654. this.tasks.likes = unique([ ...this.tasks.likes, link ]);
  4655. }
  4656. return true;
  4657. }
  4658. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4659. return false;
  4660. }
  4661. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4662. return false;
  4663. }
  4664. logStatus.error(`${result}:${statusText}(${status})`);
  4665. return false;
  4666. } catch (error) {
  4667. throwError(error, 'Youtube.toggleLikeVideo');
  4668. return false;
  4669. }
  4670. }
  4671. async toggle({
  4672. doTask = true,
  4673. channelLinks = [],
  4674. videoLinks = []
  4675. }) {
  4676. try {
  4677. if (!this.#initialized) {
  4678. scripts_echoLog({
  4679. text: i18n('needInit')
  4680. });
  4681. return false;
  4682. }
  4683. const prom = [];
  4684. if (doTask && !globalOptions.doTask.youtube.channels || !doTask && !globalOptions.undoTask.youtube.channels) {
  4685. scripts_echoLog({
  4686. type: 'globalOptionsSkip',
  4687. text: 'youtube.channels'
  4688. });
  4689. } else {
  4690. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => {
  4691. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4692. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4693. }
  4694. return link;
  4695. });
  4696. if (realChannels.length > 0) {
  4697. for (const channel of realChannels) {
  4698. prom.push(this.#toggleChannel({
  4699. link: channel,
  4700. doTask: doTask
  4701. }));
  4702. await delay(1e3);
  4703. }
  4704. }
  4705. }
  4706. if (doTask && !globalOptions.doTask.youtube.likes || !doTask && !globalOptions.undoTask.youtube.likes) {
  4707. scripts_echoLog({
  4708. type: 'globalOptionsSkip',
  4709. text: 'youtube.likes'
  4710. });
  4711. } else {
  4712. const realLikes = this.getRealParams('likes', videoLinks, doTask, link => {
  4713. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4714. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4715. }
  4716. return link;
  4717. });
  4718. if (realLikes.length > 0) {
  4719. for (const video of realLikes) {
  4720. prom.push(this.#toggleLikeVideo({
  4721. link: video,
  4722. doTask: doTask
  4723. }));
  4724. await delay(1e3);
  4725. }
  4726. }
  4727. }
  4728. return Promise.all(prom).then(() => true);
  4729. } catch (error) {
  4730. throwError(error, 'Youtube.toggle');
  4731. return false;
  4732. }
  4733. }
  4734. }
  4735. class SteamASF {
  4736. #asfOptions;
  4737. #botName = 'asf';
  4738. #groupInfo;
  4739. async init() {
  4740. try {
  4741. const asfCommandsUrl = new URL('/Api/Command/', globalOptions.ASF.AsfIpcUrl);
  4742. this.#asfOptions = {
  4743. url: asfCommandsUrl.href,
  4744. method: 'POST',
  4745. responseType: 'json',
  4746. headers: {
  4747. accept: 'application/json',
  4748. 'Content-Type': 'application/json',
  4749. Host: asfCommandsUrl.host,
  4750. Origin: asfCommandsUrl.origin,
  4751. Referer: asfCommandsUrl.href,
  4752. Authentication: globalOptions.ASF.AsfIpcPassword
  4753. }
  4754. };
  4755. if (globalOptions.ASF.AsfBotname) {
  4756. this.#botName = globalOptions.ASF.AsfBotname;
  4757. }
  4758. const logStatus = scripts_echoLog({
  4759. text: i18n('initingASF')
  4760. });
  4761. const {
  4762. result,
  4763. statusText,
  4764. status,
  4765. data
  4766. } = await tools_httpRequest({
  4767. ...this.#asfOptions,
  4768. data: '{"Command":"!stats"}'
  4769. });
  4770. if (result === 'Success') {
  4771. if (data?.response?.Success === true && data.response.Message === 'OK' && data.response.Result) {
  4772. logStatus.success();
  4773. return true;
  4774. }
  4775. if (data?.response?.Result || data?.response?.Message) {
  4776. logStatus.error(data?.response?.Result || data.response.Message);
  4777. return false;
  4778. }
  4779. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4780. return false;
  4781. }
  4782. logStatus.error(`${result}:${statusText}(${status})`);
  4783. return false;
  4784. } catch (error) {
  4785. throwError(error, 'SteamASF.init');
  4786. return false;
  4787. }
  4788. }
  4789. async joinGroup(groupName) {
  4790. try {
  4791. const logStatus = scripts_echoLog({
  4792. type: 'joiningSteamGroup',
  4793. text: groupName
  4794. });
  4795. const {
  4796. result,
  4797. statusText,
  4798. status,
  4799. data
  4800. } = await tools_httpRequest({
  4801. ...this.#asfOptions,
  4802. data: JSON.stringify({
  4803. Command: `!JOINGROUP ${this.#botName} ${groupName}`
  4804. })
  4805. });
  4806. if (result === 'Success') {
  4807. if (data?.status === 200 && [ '已加入', '已申请', 'Joined', 'Applied', 'Присоединился', 'costs' ].find(text => data.response?.Result?.includes(text))) {
  4808. logStatus.success();
  4809. return true;
  4810. }
  4811. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4812. return false;
  4813. }
  4814. logStatus.error(`${result}:${statusText}(${status})`);
  4815. return false;
  4816. } catch (error) {
  4817. throwError(error, 'SteamASF.joinGroup');
  4818. return false;
  4819. }
  4820. }
  4821. async leaveGroup(groupName) {
  4822. try {
  4823. if (!this.#groupInfo) {
  4824. if (!await this.#getGroupId()) {
  4825. return false;
  4826. }
  4827. }
  4828. const groupId = await this.#groupInfo[groupName];
  4829. if (!groupId) {
  4830. return false;
  4831. }
  4832. const logStatus = scripts_echoLog({
  4833. type: 'leavingSteamGroup',
  4834. text: groupName
  4835. });
  4836. const {
  4837. result,
  4838. statusText,
  4839. status,
  4840. data
  4841. } = await tools_httpRequest({
  4842. ...this.#asfOptions,
  4843. data: JSON.stringify({
  4844. Command: `!LEAVEGROUP ${this.#botName} ${groupId}`
  4845. })
  4846. });
  4847. if (result === 'Success') {
  4848. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4849. logStatus.success();
  4850. return true;
  4851. }
  4852. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4853. return false;
  4854. }
  4855. logStatus.error(`${result}:${statusText}(${status})`);
  4856. return false;
  4857. } catch (error) {
  4858. throwError(error, 'SteamASF.leaveGroup');
  4859. return false;
  4860. }
  4861. }
  4862. async #getGroupId() {
  4863. try {
  4864. const logStatus = scripts_echoLog({
  4865. type: 'gettingSteamGroupId',
  4866. text: 'All'
  4867. });
  4868. const {
  4869. result,
  4870. statusText,
  4871. status,
  4872. data
  4873. } = await tools_httpRequest({
  4874. ...this.#asfOptions,
  4875. data: JSON.stringify({
  4876. Command: `!GROUPLIST ${this.#botName}`
  4877. })
  4878. });
  4879. if (result === 'Success') {
  4880. if (data?.status === 200 && data.response?.Result?.includes('|')) {
  4881. this.#groupInfo = Object.fromEntries(data.response.Result.split('\n').map(line => {
  4882. const [ , name, id ] = line.trim().split('|');
  4883. if (name && id) {
  4884. return [ name, id ];
  4885. }
  4886. return null;
  4887. }).filter(ele => ele));
  4888. logStatus.success();
  4889. return true;
  4890. }
  4891. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4892. return false;
  4893. }
  4894. logStatus.error(`${result}:${statusText}(${status})`);
  4895. return false;
  4896. } catch (error) {
  4897. throwError(error, 'SteamASF.getGroupID');
  4898. return false;
  4899. }
  4900. }
  4901. async addToWishlist(gameId) {
  4902. try {
  4903. const logStatus = scripts_echoLog({
  4904. type: 'addingToWishlist',
  4905. text: gameId
  4906. });
  4907. if ((await this.#checkGame(gameId)).wishlist === true) {
  4908. logStatus.success();
  4909. return true;
  4910. }
  4911. const {
  4912. result,
  4913. statusText,
  4914. status,
  4915. data
  4916. } = await tools_httpRequest({
  4917. ...this.#asfOptions,
  4918. data: JSON.stringify({
  4919. Command: `!ADDWISHLIST ${this.#botName} ${gameId}`
  4920. })
  4921. });
  4922. if (result === 'Success') {
  4923. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4924. logStatus.success();
  4925. return true;
  4926. }
  4927. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4928. return false;
  4929. }
  4930. logStatus.error(`${result}:${statusText}(${status})`);
  4931. return false;
  4932. } catch (error) {
  4933. throwError(error, 'SteamASF.addToWishlist');
  4934. return false;
  4935. }
  4936. }
  4937. async removeFromWishlist(gameId) {
  4938. try {
  4939. const logStatus = scripts_echoLog({
  4940. type: 'removingFromWishlist',
  4941. text: gameId
  4942. });
  4943. if ((await this.#checkGame(gameId)).wishlist === false) {
  4944. logStatus.success();
  4945. return true;
  4946. }
  4947. const {
  4948. result,
  4949. statusText,
  4950. status,
  4951. data
  4952. } = await tools_httpRequest({
  4953. ...this.#asfOptions,
  4954. data: JSON.stringify({
  4955. Command: `!REMOVEWISHLIST ${this.#botName} ${gameId}`
  4956. })
  4957. });
  4958. if (result === 'Success') {
  4959. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4960. logStatus.success();
  4961. return true;
  4962. }
  4963. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4964. return false;
  4965. }
  4966. logStatus.error(`${result}:${statusText}(${status})`);
  4967. return false;
  4968. } catch (error) {
  4969. throwError(error, 'SteamASF.removeFromWishlist');
  4970. return false;
  4971. }
  4972. }
  4973. async toggleFollowGame(gameId, doTask) {
  4974. try {
  4975. const logStatus = scripts_echoLog({
  4976. type: `${doTask ? '' : 'un'}followingGame`,
  4977. text: gameId
  4978. });
  4979. if (doTask && (await this.#checkGame(gameId)).followed === true || !doTask && (await this.#checkGame(gameId)).followed === false) {
  4980. logStatus.success();
  4981. return true;
  4982. }
  4983. const {
  4984. result,
  4985. statusText,
  4986. status,
  4987. data
  4988. } = await tools_httpRequest({
  4989. ...this.#asfOptions,
  4990. data: JSON.stringify({
  4991. Command: `!${doTask ? '' : 'UN'}FOLLOWGAME ${this.#botName} ${gameId}`
  4992. })
  4993. });
  4994. if (result === 'Success') {
  4995. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4996. logStatus.success();
  4997. return true;
  4998. }
  4999. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5000. return false;
  5001. }
  5002. logStatus.error(`${result}:${statusText}(${status})`);
  5003. return false;
  5004. } catch (error) {
  5005. throwError(error, 'SteamASF.toggleFollowGame');
  5006. return false;
  5007. }
  5008. }
  5009. async #checkGame(gameId) {
  5010. try {
  5011. const {
  5012. result,
  5013. data
  5014. } = await tools_httpRequest({
  5015. ...this.#asfOptions,
  5016. data: JSON.stringify({
  5017. Command: `!CHECK ${this.#botName} ${gameId}`
  5018. })
  5019. });
  5020. if (result === 'Success') {
  5021. if (data?.status === 200 && data.response?.Result?.includes(gameId)) {
  5022. const matchedResult = data.response.Result.split('\n').find(result => result.includes(gameId))?.split('|');
  5023. if (matchedResult?.length > 3) {
  5024. return {
  5025. wishlist: matchedResult.at(-3).trim() === '√' || matchedResult.at(-2).trim() === '√',
  5026. followed: matchedResult.at(-1).trim() === '√'
  5027. };
  5028. }
  5029. return {};
  5030. }
  5031. return {};
  5032. }
  5033. return {};
  5034. } catch (error) {
  5035. throwError(error, 'SteamASF.checkGame');
  5036. return {};
  5037. }
  5038. }
  5039. async toggleCurator(curatorId, doTask = true) {
  5040. try {
  5041. const logStatus = scripts_echoLog({
  5042. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  5043. text: curatorId
  5044. });
  5045. const {
  5046. result,
  5047. statusText,
  5048. status,
  5049. data
  5050. } = await tools_httpRequest({
  5051. ...this.#asfOptions,
  5052. data: JSON.stringify({
  5053. Command: `!${doTask ? '' : 'UN'}FOLLOWCURATOR ${this.#botName} ${curatorId}`
  5054. })
  5055. });
  5056. if (result === 'Success') {
  5057. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  5058. logStatus.success();
  5059. return true;
  5060. }
  5061. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5062. return false;
  5063. }
  5064. logStatus.error(`${result}:${statusText}(${status})`);
  5065. return false;
  5066. } catch (error) {
  5067. throwError(error, 'Steam.toggleCurator');
  5068. return false;
  5069. }
  5070. }
  5071. async addLicense(id) {
  5072. try {
  5073. const [ type, ids ] = id.split('-');
  5074. if (type === 'appid') {
  5075. const logStatus = scripts_echoLog({
  5076. type: 'addingFreeLicense',
  5077. text: ids
  5078. });
  5079. const {
  5080. result,
  5081. statusText,
  5082. status,
  5083. data
  5084. } = await tools_httpRequest({
  5085. ...this.#asfOptions,
  5086. data: JSON.stringify({
  5087. Command: `!addlicense ${this.#botName} app/${ids}`
  5088. })
  5089. });
  5090. if (result === 'Success') {
  5091. if (data?.status === 200 && [ 'AlreadyPurchased', 'OK' ].find(text => data.response?.Result?.includes(text))) {
  5092. logStatus.success();
  5093. return true;
  5094. }
  5095. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5096. return false;
  5097. }
  5098. logStatus.error(`${result}:${statusText}(${status})`);
  5099. return false;
  5100. } else if (type === 'subid') {
  5101. const idsArr = ids.split(',');
  5102. const logStatus = scripts_echoLog({
  5103. type: 'addingFreeLicenseSubid',
  5104. text: ids
  5105. });
  5106. const {
  5107. result,
  5108. statusText,
  5109. status,
  5110. data
  5111. } = await tools_httpRequest({
  5112. ...this.#asfOptions,
  5113. data: JSON.stringify({
  5114. Command: `!addlicense ${this.#botName} ${idsArr.map(id => `sub/${id}`).join(',')}`
  5115. })
  5116. });
  5117. if (result === 'Success') {
  5118. if (data?.status === 200 && data.response?.Result) {
  5119. const resultLines = data.response.Result.split('\n');
  5120. idsArr.forEach(subid => {
  5121. const targetLine = resultLines.find(text => text.includes(subid));
  5122. if (targetLine && [ '成功', 'Success', 'Успех' ].find(text => targetLine.includes(text))) {
  5123. scripts_echoLog({}).success(targetLine);
  5124. } else {
  5125. scripts_echoLog({}).error(targetLine);
  5126. }
  5127. });
  5128. return true;
  5129. }
  5130. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5131. return false;
  5132. }
  5133. logStatus.error(`${result}:${statusText}(${status})`);
  5134. return false;
  5135. }
  5136. return false;
  5137. } catch (error) {
  5138. throwError(error, 'SteamASF.addLicense');
  5139. return false;
  5140. }
  5141. }
  5142. async requestPlayTestAccess(id) {
  5143. try {
  5144. const logStatus = scripts_echoLog({
  5145. type: 'requestingPlayTestAccess',
  5146. text: id
  5147. });
  5148. const {
  5149. result,
  5150. statusText,
  5151. status,
  5152. data
  5153. } = await tools_httpRequest({
  5154. ...this.#asfOptions,
  5155. data: JSON.stringify({
  5156. Command: `!REQUESTACCESS ${this.#botName} ${id}`
  5157. })
  5158. });
  5159. if (result === 'Success') {
  5160. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  5161. logStatus.success();
  5162. return true;
  5163. }
  5164. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5165. return false;
  5166. }
  5167. logStatus.error(`${result}:${statusText}(${status})`);
  5168. return false;
  5169. } catch (error) {
  5170. throwError(error, 'Steam.requestPlayTestAccess');
  5171. return false;
  5172. }
  5173. }
  5174. }
  5175. const social_SteamASF = SteamASF;
  5176. class Steam extends social_Social {
  5177. tasks;
  5178. whiteList;
  5179. #cache = {
  5180. ...{
  5181. group: {},
  5182. officialGroup: {},
  5183. forum: {},
  5184. workshop: {},
  5185. curator: {}
  5186. },
  5187. ...GM_getValue('steamCache')
  5188. };
  5189. #auth = {};
  5190. #storeInitialized = false;
  5191. #communityInitialized = false;
  5192. #area = 'CN';
  5193. #oldArea;
  5194. #areaStatus = 'end';
  5195. #ASF;
  5196. constructor() {
  5197. super();
  5198. const defaultTasksTemplate = {
  5199. groups: [],
  5200. officialGroups: [],
  5201. wishlists: [],
  5202. follows: [],
  5203. forums: [],
  5204. workshops: [],
  5205. workshopVotes: [],
  5206. curators: [],
  5207. curatorLikes: [],
  5208. announcements: [],
  5209. licenses: [],
  5210. playtests: []
  5211. };
  5212. this.tasks = defaultTasksTemplate;
  5213. this.whiteList = {
  5214. ...defaultTasksTemplate,
  5215. ...GM_getValue('whiteList')?.steam || {}
  5216. };
  5217. }
  5218. async init(type = 'all') {
  5219. try {
  5220. if (globalOptions.ASF.AsfEnabled && globalOptions.ASF.AsfIpcUrl && globalOptions.ASF.AsfIpcPassword) {
  5221. this.#ASF = new social_SteamASF();
  5222. if (await this.#ASF.init()) {
  5223. this.#storeInitialized = true;
  5224. this.#communityInitialized = true;
  5225. return true;
  5226. }
  5227. return false;
  5228. }
  5229. if (type === 'store') {
  5230. if (this.#storeInitialized) {
  5231. return true;
  5232. }
  5233. let storeInitialized = await this.#updateStoreAuth();
  5234. if (!storeInitialized) {
  5235. storeInitialized = await this.#updateStoreAuthTab();
  5236. }
  5237. this.#storeInitialized = storeInitialized;
  5238. if (!this.#storeInitialized) {
  5239. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  5240. return false;
  5241. }
  5242. scripts_echoLog({}).success(i18n('initSuccess', 'SteamStore'));
  5243. return true;
  5244. }
  5245. if (type === 'community') {
  5246. if (this.#communityInitialized) {
  5247. return true;
  5248. }
  5249. let communityInitialized = await this.#updateCommunityAuth();
  5250. if (!communityInitialized) {
  5251. communityInitialized = await this.#updateCommunityAuthTab();
  5252. GM_setValue('steamCommunityAuth', null);
  5253. }
  5254. this.#communityInitialized = communityInitialized;
  5255. if (!this.#communityInitialized) {
  5256. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  5257. return false;
  5258. }
  5259. scripts_echoLog({}).success(i18n('initSuccess', 'SteamCommunity'));
  5260. return true;
  5261. }
  5262. if (this.#storeInitialized && this.#communityInitialized) {
  5263. scripts_echoLog({}).success(i18n('initSuccess', 'Steam'));
  5264. return true;
  5265. }
  5266. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  5267. return false;
  5268. } catch (error) {
  5269. throwError(error, 'Steam.init');
  5270. return false;
  5271. }
  5272. }
  5273. async #refreshToken(type = 'steamStore') {
  5274. try {
  5275. const host = {
  5276. steamStore: 'store.steampowered.com',
  5277. steamCommunity: 'steamcommunity.com'
  5278. };
  5279. const logStatus = scripts_echoLog({
  5280. text: i18n('refreshingToken', i18n(type))
  5281. });
  5282. const formData = new FormData();
  5283. formData.append('redir', `https://${host[type]}/`);
  5284. const {
  5285. result,
  5286. statusText,
  5287. status,
  5288. data
  5289. } = await tools_httpRequest({
  5290. url: 'https://login.steampowered.com/jwt/ajaxrefresh',
  5291. method: 'POST',
  5292. responseType: 'json',
  5293. headers: {
  5294. Host: 'login.steampowered.com',
  5295. Origin: `https://${host[type]}`,
  5296. Referer: `https://${host[type]}/`
  5297. },
  5298. data: formData
  5299. });
  5300. if (result === 'Success') {
  5301. if (data?.response?.success) {
  5302. if (await this.#setStoreToken(data.response, type)) {
  5303. logStatus.success();
  5304. return true;
  5305. }
  5306. logStatus.error('Error');
  5307. return false;
  5308. }
  5309. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5310. return false;
  5311. }
  5312. logStatus.error(`${result}:${statusText}(${status})`);
  5313. return false;
  5314. } catch (error) {
  5315. throwError(error, 'Steam.refreshToken');
  5316. return false;
  5317. }
  5318. }
  5319. async #setStoreToken(param, type) {
  5320. try {
  5321. const host = {
  5322. steamStore: 'store.steampowered.com',
  5323. steamCommunity: 'steamcommunity.com'
  5324. };
  5325. const logStatus = scripts_echoLog({
  5326. text: i18n('settingToken', i18n(type))
  5327. });
  5328. const formData = new FormData();
  5329. formData.append('steamID', param.steamID);
  5330. formData.append('nonce', param.nonce);
  5331. formData.append('redir', param.redir);
  5332. formData.append('auth', param.auth);
  5333. const {
  5334. result,
  5335. statusText,
  5336. status,
  5337. data
  5338. } = await tools_httpRequest({
  5339. url: `https://${host[type]}/login/settoken`,
  5340. method: 'POST',
  5341. headers: {
  5342. Accept: 'application/json, text/plain, */*',
  5343. Host: host[type],
  5344. Origin: `https://${host[type]}`
  5345. },
  5346. data: formData
  5347. });
  5348. if (result === 'Success') {
  5349. if (data?.status === 200) {
  5350. logStatus.success();
  5351. return true;
  5352. }
  5353. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5354. return false;
  5355. }
  5356. logStatus.error(`${result}:${statusText}(${status})`);
  5357. return false;
  5358. } catch (error) {
  5359. throwError(error, 'Steam.setStoreToken');
  5360. return false;
  5361. }
  5362. }
  5363. async #updateStoreAuth(retry = false) {
  5364. try {
  5365. const logStatus = scripts_echoLog({
  5366. text: i18n('updatingAuth', i18n('steamStore'))
  5367. });
  5368. const {
  5369. result,
  5370. statusText,
  5371. status,
  5372. data
  5373. } = await tools_httpRequest({
  5374. url: 'https://store.steampowered.com/',
  5375. method: 'GET',
  5376. headers: {
  5377. 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',
  5378. 'Sec-Fetch-Dest': 'document',
  5379. 'Sec-Fetch-Mode': 'navigate',
  5380. 'Upgrade-Insecure-Requests': '1'
  5381. },
  5382. fetch: false,
  5383. redirect: 'manual'
  5384. });
  5385. if (data?.status === 200) {
  5386. if (!data.responseText.includes('data-miniprofile=')) {
  5387. if (await this.#refreshToken('steamStore')) {
  5388. logStatus.warning(i18n('retry'));
  5389. if (retry) {
  5390. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  5391. return false;
  5392. }
  5393. return this.#updateStoreAuth(true);
  5394. }
  5395. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  5396. return false;
  5397. }
  5398. const storeSessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  5399. if (storeSessionID) {
  5400. this.#auth.storeSessionID = storeSessionID;
  5401. logStatus.success();
  5402. return true;
  5403. }
  5404. logStatus.error('Error: Get "sessionID" failed');
  5405. return false;
  5406. }
  5407. if ([ 301, 302 ].includes(data?.status)) {
  5408. if (await this.#refreshToken('steamStore')) {
  5409. logStatus.warning(i18n('retry'));
  5410. if (retry) {
  5411. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  5412. return false;
  5413. }
  5414. return this.#updateStoreAuth(true);
  5415. }
  5416. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  5417. return false;
  5418. }
  5419. logStatus.error(`${result}:${statusText}(${status})`);
  5420. return false;
  5421. } catch (error) {
  5422. throwError(error, 'Steam.updateStoreAuth');
  5423. return false;
  5424. }
  5425. }
  5426. async #updateStoreAuthTab() {
  5427. try {
  5428. const logStatus = scripts_echoLog({
  5429. text: i18n('updatingAuth', i18n('steamStoreTab'))
  5430. });
  5431. return await new Promise(resolve => {
  5432. GM_deleteValue('steamStoreAuth');
  5433. GM_setValue('ATv4_updateStoreAuth', true);
  5434. const newTab = GM_openInTab('https://store.steampowered.com/', {
  5435. active: true,
  5436. setParent: true
  5437. });
  5438. newTab.name = 'ATv4_updateStoreAuth';
  5439. const listenerId = GM_addValueChangeListener('steamStoreAuth', (key, oldValue, newValue) => {
  5440. GM_removeValueChangeListener(listenerId);
  5441. GM_deleteValue('ATv4_updateStoreAuth');
  5442. newTab?.close();
  5443. window.focus();
  5444. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  5445. this.#auth.storeSessionID = newValue.storeSessionID;
  5446. logStatus.success();
  5447. resolve(true);
  5448. return;
  5449. }
  5450. logStatus.error('Failed');
  5451. resolve(false);
  5452. });
  5453. newTab.onclose = () => {
  5454. GM_deleteValue('ATv4_updateStoreAuth');
  5455. };
  5456. });
  5457. } catch (error) {
  5458. throwError(error, 'Steam.updateStoreAuthTab');
  5459. return false;
  5460. }
  5461. }
  5462. async #updateCommunityAuthTab() {
  5463. try {
  5464. const logStatus = scripts_echoLog({
  5465. text: i18n('updatingAuth', i18n('steamCommunityTab'))
  5466. });
  5467. return await new Promise(resolve => {
  5468. GM_deleteValue('steamCommunityAuth');
  5469. GM_setValue('ATv4_updateCommunityAuth', true);
  5470. const newTab = GM_openInTab('https://steamcommunity.com/my', {
  5471. active: true,
  5472. setParent: true
  5473. });
  5474. newTab.name = 'ATv4_updateCommunityAuth';
  5475. const listenerId = GM_addValueChangeListener('steamCommunityAuth', (key, oldValue, newValue) => {
  5476. GM_removeValueChangeListener(listenerId);
  5477. GM_deleteValue('ATv4_updateCommunityAuth');
  5478. newTab?.close();
  5479. window.focus();
  5480. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  5481. this.#auth.steam64Id = newValue.steam64Id;
  5482. this.#auth.communitySessionID = newValue.communitySessionID;
  5483. logStatus.success();
  5484. resolve(true);
  5485. return;
  5486. }
  5487. logStatus.error('Failed');
  5488. resolve(false);
  5489. });
  5490. newTab.onclose = () => {
  5491. GM_deleteValue('ATv4_updateCommunityAuth');
  5492. };
  5493. });
  5494. } catch (error) {
  5495. throwError(error, 'Steam.updateCommunityAuthTab');
  5496. return false;
  5497. }
  5498. }
  5499. async #updateCommunityAuth() {
  5500. try {
  5501. const logStatus = scripts_echoLog({
  5502. text: i18n('gettingUserLink')
  5503. });
  5504. const {
  5505. result,
  5506. statusText,
  5507. status,
  5508. data
  5509. } = await tools_httpRequest({
  5510. url: 'https://steamcommunity.com/my',
  5511. method: 'GET',
  5512. headers: {
  5513. 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',
  5514. Host: 'steamcommunity.com',
  5515. 'Sec-Fetch-Dest': 'document',
  5516. 'Sec-Fetch-Mode': 'navigate'
  5517. },
  5518. fetch: false
  5519. });
  5520. if (data?.status === 200) {
  5521. if (data.finalUrl.includes('https://steamcommunity.com/login/home')) {
  5522. logStatus.error(`Error:${i18n('needLoginSteamCommunity')}`, true);
  5523. return false;
  5524. }
  5525. const steam64Id = data.responseText.match(/g_steamID = "(.+?)";/)?.[1];
  5526. const communitySessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  5527. if (steam64Id && communitySessionID) {
  5528. this.#auth.steam64Id = steam64Id;
  5529. this.#auth.communitySessionID = communitySessionID;
  5530. logStatus.success();
  5531. return true;
  5532. }
  5533. logStatus.error('Error: Get "sessionID" failed');
  5534. return false;
  5535. }
  5536. logStatus.error(`${result}:${statusText}(${status})`);
  5537. return false;
  5538. } catch (error) {
  5539. throwError(error, 'Steam.updateCommunityAuth');
  5540. return false;
  5541. }
  5542. }
  5543. async #getAreaInfo() {
  5544. try {
  5545. const logStatus = scripts_echoLog({
  5546. text: i18n('gettingAreaInfo')
  5547. });
  5548. const {
  5549. result,
  5550. statusText,
  5551. status,
  5552. data
  5553. } = await tools_httpRequest({
  5554. url: 'https://store.steampowered.com/cart/',
  5555. method: 'GET'
  5556. });
  5557. if (result === 'Success') {
  5558. if (data?.status === 200) {
  5559. const cartConfigRaw = data.responseText.match(/data-cart_config="(.*?)"/)?.[1];
  5560. const temp = document.createElement('div');
  5561. temp.innerHTML = cartConfigRaw || '{}';
  5562. const cartConfigStr = temp.textContent || temp.innerText;
  5563. let cartConfig;
  5564. try {
  5565. cartConfig = JSON.parse(cartConfigStr);
  5566. } catch (error) {
  5567. logStatus.error('Error: get country info filed');
  5568. console.error(error);
  5569. return {};
  5570. }
  5571. if (!cartConfig.rgUserCountryOptions) {
  5572. logStatus.warning('Warning: Area cannot be changed');
  5573. return {};
  5574. }
  5575. const userInfoRaw = data.responseText.match(/data-userinfo="(.*?)"/)?.[1];
  5576. const temp1 = document.createElement('div');
  5577. temp1.innerHTML = userInfoRaw || '{}';
  5578. const userInfoStr = temp1.textContent || temp1.innerText;
  5579. let userInfo;
  5580. try {
  5581. userInfo = JSON.parse(userInfoStr);
  5582. } catch (error) {
  5583. logStatus.error('Error: get country info filed');
  5584. console.error(error);
  5585. return {};
  5586. }
  5587. const currentArea = userInfo.country_code;
  5588. const areas = Object.keys(cartConfig.rgUserCountryOptions).filter(area => area !== 'help');
  5589. if (currentArea && areas.length > 0) {
  5590. this.#area = currentArea;
  5591. logStatus.success();
  5592. return {
  5593. currentArea: currentArea,
  5594. areas: areas
  5595. };
  5596. }
  5597. logStatus.error('Error: get country info filed');
  5598. return {};
  5599. }
  5600. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5601. return {};
  5602. }
  5603. logStatus.error(`${result}:${statusText}(${status})`);
  5604. return {};
  5605. } catch (error) {
  5606. throwError(error, 'Steam.getAreaInfo');
  5607. return {};
  5608. }
  5609. }
  5610. async #changeArea(area) {
  5611. try {
  5612. if (this.#areaStatus === 'waiting') {
  5613. await new Promise(resolve => {
  5614. const checker = setInterval(() => {
  5615. if (this.#areaStatus !== 'waiting') {
  5616. clearInterval(checker);
  5617. resolve(true);
  5618. }
  5619. });
  5620. });
  5621. }
  5622. if (this.#area === area || !area && this.#area !== 'CN') {
  5623. return true;
  5624. }
  5625. this.#areaStatus = 'waiting';
  5626. let aimedArea = area;
  5627. if (!aimedArea) {
  5628. const {
  5629. currentArea,
  5630. areas
  5631. } = await this.#getAreaInfo();
  5632. if (!currentArea || !areas) {
  5633. this.#areaStatus = 'error';
  5634. return false;
  5635. }
  5636. if (currentArea !== 'CN') {
  5637. this.#areaStatus = 'skip';
  5638. scripts_echoLog({
  5639. text: 'notNeededChangeArea'
  5640. });
  5641. return 'skip';
  5642. }
  5643. const anotherArea = areas.filter(area => area && area !== 'CN');
  5644. if (!anotherArea || anotherArea.length === 0) {
  5645. this.#areaStatus = 'noAnotherArea';
  5646. scripts_echoLog({
  5647. text: 'noAnotherArea'
  5648. });
  5649. return false;
  5650. }
  5651. [ aimedArea ] = anotherArea;
  5652. }
  5653. const logStatus = scripts_echoLog({
  5654. text: i18n('changingArea', aimedArea)
  5655. });
  5656. const {
  5657. result,
  5658. statusText,
  5659. status,
  5660. data
  5661. } = await tools_httpRequest({
  5662. url: 'https://store.steampowered.com/country/setcountry',
  5663. method: 'POST',
  5664. headers: {
  5665. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5666. },
  5667. data: $.param({
  5668. cc: aimedArea,
  5669. sessionid: this.#auth.storeSessionID
  5670. })
  5671. });
  5672. if (result === 'Success') {
  5673. if (data?.status === 200 && data.responseText === 'true') {
  5674. const {
  5675. currentArea
  5676. } = await this.#getAreaInfo();
  5677. if (currentArea) {
  5678. this.#area = currentArea;
  5679. if (!this.#oldArea) {
  5680. this.#oldArea = currentArea;
  5681. }
  5682. }
  5683. if (currentArea === aimedArea) {
  5684. this.#areaStatus = 'success';
  5685. logStatus.success();
  5686. return currentArea;
  5687. }
  5688. this.#areaStatus = 'error';
  5689. logStatus.error('Error: change country filed');
  5690. return 'CN';
  5691. }
  5692. this.#areaStatus = 'error';
  5693. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5694. return 'CN';
  5695. }
  5696. this.#areaStatus = 'error';
  5697. logStatus.error(`${result}:${statusText}(${status})`);
  5698. return 'CN';
  5699. } catch (error) {
  5700. this.#areaStatus = 'error';
  5701. throwError(error, 'Steam.changeArea');
  5702. return false;
  5703. }
  5704. }
  5705. async #joinGroup(groupName) {
  5706. try {
  5707. if (this.#ASF) {
  5708. if (await this.#ASF.joinGroup(groupName)) {
  5709. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5710. return true;
  5711. }
  5712. return false;
  5713. }
  5714. const logStatus = scripts_echoLog({
  5715. type: 'joiningSteamGroup',
  5716. text: groupName
  5717. });
  5718. const {
  5719. result,
  5720. statusText,
  5721. status,
  5722. data
  5723. } = await tools_httpRequest({
  5724. url: `https://steamcommunity.com/groups/${groupName}`,
  5725. method: 'POST',
  5726. headers: {
  5727. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5728. },
  5729. data: $.param({
  5730. action: 'join',
  5731. sessionID: this.#auth.communitySessionID
  5732. })
  5733. });
  5734. if (result === 'Success') {
  5735. if (data?.status === 200 && !data.responseText.includes('grouppage_join_area')) {
  5736. logStatus.success();
  5737. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5738. return true;
  5739. }
  5740. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5741. return false;
  5742. }
  5743. logStatus.error(`${result}:${statusText}(${status})`);
  5744. return false;
  5745. } catch (error) {
  5746. throwError(error, 'Steam.joinGroup');
  5747. return false;
  5748. }
  5749. }
  5750. async #leaveGroup(groupName) {
  5751. try {
  5752. if (this.whiteList.groups.includes(groupName)) {
  5753. scripts_echoLog({
  5754. type: 'whiteList',
  5755. text: 'Steam.leaveGroup',
  5756. id: groupName
  5757. });
  5758. return true;
  5759. }
  5760. if (this.#ASF) {
  5761. return await this.#ASF.leaveGroup(groupName);
  5762. }
  5763. const groupId = await this.#getGroupId(groupName);
  5764. if (!groupId) {
  5765. return false;
  5766. }
  5767. const logStatus = scripts_echoLog({
  5768. type: 'leavingSteamGroup',
  5769. text: groupName
  5770. });
  5771. const {
  5772. result,
  5773. statusText,
  5774. status,
  5775. data
  5776. } = await tools_httpRequest({
  5777. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5778. method: 'POST',
  5779. headers: {
  5780. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5781. },
  5782. data: $.param({
  5783. sessionID: this.#auth.communitySessionID,
  5784. action: 'leaveGroup',
  5785. groupId: groupId
  5786. })
  5787. });
  5788. if (result === 'Success') {
  5789. 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) {
  5790. logStatus.success();
  5791. return true;
  5792. }
  5793. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5794. return false;
  5795. }
  5796. logStatus.error(`${result}:${statusText}(${status})`);
  5797. return false;
  5798. } catch (error) {
  5799. throwError(error, 'Steam.leaveGroup');
  5800. return false;
  5801. }
  5802. }
  5803. async #getGroupId(groupName) {
  5804. try {
  5805. const logStatus = scripts_echoLog({
  5806. type: 'gettingSteamGroupId',
  5807. text: groupName
  5808. });
  5809. const groupId = this.#cache.group[groupName];
  5810. if (groupId) {
  5811. logStatus.success();
  5812. return groupId;
  5813. }
  5814. const {
  5815. result,
  5816. statusText,
  5817. status,
  5818. data
  5819. } = await tools_httpRequest({
  5820. url: `https://steamcommunity.com/groups/${groupName}`,
  5821. method: 'GET',
  5822. headers: {
  5823. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5824. }
  5825. });
  5826. if (result === 'Success') {
  5827. if (data?.status === 200) {
  5828. const groupId = data.responseText.match(/OpenGroupChat\( '([0-9]+)'/)?.[1];
  5829. if (groupId) {
  5830. this.#setCache('group', groupName, groupId);
  5831. logStatus.success();
  5832. return groupId;
  5833. }
  5834. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5835. return false;
  5836. }
  5837. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5838. return false;
  5839. }
  5840. logStatus.error(`${result}:${statusText}(${status})`);
  5841. return false;
  5842. } catch (error) {
  5843. throwError(error, 'Steam.getGroupID');
  5844. return false;
  5845. }
  5846. }
  5847. async #joinOfficialGroup(gameId) {
  5848. try {
  5849. if (this.#ASF) {
  5850. if (await this.#ASF.joinGroup(gameId)) {
  5851. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5852. return true;
  5853. }
  5854. return false;
  5855. }
  5856. const logStatus = scripts_echoLog({
  5857. type: 'joiningSteamOfficialGroup',
  5858. text: gameId
  5859. });
  5860. const {
  5861. result,
  5862. statusText,
  5863. status,
  5864. data
  5865. } = await tools_httpRequest({
  5866. url: `https://steamcommunity.com/games/${gameId}?action=join&sessionID=${this.#auth.communitySessionID}`,
  5867. method: 'GET',
  5868. headers: {
  5869. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5870. }
  5871. });
  5872. if (result === 'Success') {
  5873. if (data?.status === 200 && !data.responseText.includes('id="publicGroupJoin"')) {
  5874. logStatus.success();
  5875. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5876. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5877. if (groupId) {
  5878. this.#setCache('officialGroup', gameId, groupId);
  5879. }
  5880. return true;
  5881. }
  5882. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5883. return false;
  5884. }
  5885. logStatus.error(`${result}:${statusText}(${status})`);
  5886. return false;
  5887. } catch (error) {
  5888. throwError(error, 'Steam.joinOfficialGroup');
  5889. return false;
  5890. }
  5891. }
  5892. async #leaveOfficialGroup(gameId) {
  5893. try {
  5894. if (this.whiteList.officialGroups.includes(gameId)) {
  5895. scripts_echoLog({
  5896. type: 'whiteList',
  5897. text: 'Steam.leaveOfficialGroup',
  5898. id: gameId
  5899. });
  5900. return true;
  5901. }
  5902. if (this.#ASF) {
  5903. return await this.#ASF.leaveGroup(gameId);
  5904. }
  5905. const groupId = await this.#getOfficialGroupId(gameId);
  5906. if (!groupId) {
  5907. return false;
  5908. }
  5909. const logStatus = scripts_echoLog({
  5910. type: 'leavingSteamOfficialGroup',
  5911. text: gameId
  5912. });
  5913. const {
  5914. result,
  5915. statusText,
  5916. status,
  5917. data
  5918. } = await tools_httpRequest({
  5919. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5920. method: 'POST',
  5921. headers: {
  5922. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5923. },
  5924. data: $.param({
  5925. sessionID: this.#auth.communitySessionID,
  5926. action: 'leaveGroup',
  5927. groupId: groupId
  5928. })
  5929. });
  5930. if (result === 'Success') {
  5931. if (data?.status === 200) {
  5932. const {
  5933. result: resultR,
  5934. statusText: statusTextR,
  5935. status: statusR,
  5936. data: dataR
  5937. } = await tools_httpRequest({
  5938. url: `https://steamcommunity.com/games/${gameId}`,
  5939. method: 'GET',
  5940. headers: {
  5941. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5942. }
  5943. });
  5944. if (resultR === 'Success') {
  5945. if (dataR?.status === 200 && dataR.responseText.includes('id="publicGroupJoin"')) {
  5946. logStatus.success();
  5947. return true;
  5948. }
  5949. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  5950. return false;
  5951. }
  5952. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  5953. return false;
  5954. }
  5955. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5956. return false;
  5957. }
  5958. logStatus.error(`${result}:${statusText}(${status})`);
  5959. return false;
  5960. } catch (error) {
  5961. throwError(error, 'Steam.leaveOfficialGroup');
  5962. return false;
  5963. }
  5964. }
  5965. async #getOfficialGroupId(gameId) {
  5966. try {
  5967. const logStatus = scripts_echoLog({
  5968. type: 'gettingSteamOfficialGroupId',
  5969. text: gameId
  5970. });
  5971. const groupId = this.#cache.officialGroup[gameId];
  5972. if (groupId) {
  5973. logStatus.success();
  5974. return groupId;
  5975. }
  5976. const {
  5977. result,
  5978. statusText,
  5979. status,
  5980. data
  5981. } = await tools_httpRequest({
  5982. url: `https://steamcommunity.com/games/${gameId}`,
  5983. method: 'GET',
  5984. headers: {
  5985. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5986. }
  5987. });
  5988. if (result === 'Success') {
  5989. if (data?.status === 200) {
  5990. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5991. if (groupId) {
  5992. this.#setCache('officialGroup', gameId, groupId);
  5993. logStatus.success();
  5994. return groupId;
  5995. }
  5996. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5997. return false;
  5998. }
  5999. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6000. return false;
  6001. }
  6002. logStatus.error(`${result}:${statusText}(${status})`);
  6003. return false;
  6004. } catch (error) {
  6005. throwError(error, 'Steam.getGroupID');
  6006. return false;
  6007. }
  6008. }
  6009. async #addToWishlist(gameId) {
  6010. try {
  6011. if (this.#ASF) {
  6012. if (await this.#ASF.addToWishlist(gameId)) {
  6013. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  6014. return true;
  6015. }
  6016. return false;
  6017. }
  6018. const logStatus = scripts_echoLog({
  6019. type: 'addingToWishlist',
  6020. text: gameId
  6021. });
  6022. const {
  6023. result,
  6024. data
  6025. } = await tools_httpRequest({
  6026. url: 'https://store.steampowered.com/api/addtowishlist',
  6027. method: 'POST',
  6028. headers: {
  6029. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6030. },
  6031. data: $.param({
  6032. sessionid: this.#auth.storeSessionID,
  6033. appid: gameId
  6034. }),
  6035. dataType: 'json'
  6036. });
  6037. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  6038. logStatus.success();
  6039. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  6040. return true;
  6041. }
  6042. const {
  6043. result: resultR,
  6044. statusText: statusTextR,
  6045. status: statusR,
  6046. data: dataR
  6047. } = await tools_httpRequest({
  6048. url: `https://store.steampowered.com/app/${gameId}`,
  6049. method: 'GET'
  6050. });
  6051. if (resultR === 'Success') {
  6052. if (dataR?.status === 200) {
  6053. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  6054. logStatus.warning(i18n('changeAreaNotice'));
  6055. if (!await this.#changeArea()) {
  6056. return false;
  6057. }
  6058. return await this.#addToWishlist(gameId);
  6059. }
  6060. if (dataR.responseText.includes('class="queue_actions_ctn"') && dataR.responseText.includes('class="already_in_library"')) {
  6061. logStatus.success();
  6062. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  6063. return true;
  6064. } 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"')) {
  6065. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  6066. return false;
  6067. }
  6068. logStatus.success();
  6069. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  6070. return true;
  6071. }
  6072. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  6073. return false;
  6074. }
  6075. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  6076. return false;
  6077. } catch (error) {
  6078. throwError(error, 'Steam.addToWishlist');
  6079. return false;
  6080. }
  6081. }
  6082. async #removeFromWishlist(gameId) {
  6083. try {
  6084. if (this.whiteList.wishlists.includes(gameId)) {
  6085. scripts_echoLog({
  6086. type: 'whiteList',
  6087. text: 'Steam.removeFromWishlist',
  6088. id: gameId
  6089. });
  6090. return true;
  6091. }
  6092. if (this.#ASF) {
  6093. return await this.#ASF.removeFromWishlist(gameId);
  6094. }
  6095. const logStatus = scripts_echoLog({
  6096. type: 'removingFromWishlist',
  6097. text: gameId
  6098. });
  6099. const {
  6100. result,
  6101. data
  6102. } = await tools_httpRequest({
  6103. url: 'https://store.steampowered.com/api/removefromwishlist',
  6104. method: 'POST',
  6105. headers: {
  6106. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6107. },
  6108. data: $.param({
  6109. sessionid: this.#auth.storeSessionID,
  6110. appid: gameId
  6111. }),
  6112. dataType: 'json'
  6113. });
  6114. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  6115. logStatus.success();
  6116. return true;
  6117. }
  6118. const {
  6119. result: resultR,
  6120. statusText: statusTextR,
  6121. status: statusR,
  6122. data: dataR
  6123. } = await tools_httpRequest({
  6124. url: `https://store.steampowered.com/app/${gameId}`,
  6125. method: 'GET'
  6126. });
  6127. if (resultR === 'Success') {
  6128. if (dataR?.status === 200) {
  6129. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  6130. logStatus.warning(i18n('changeAreaNotice'));
  6131. const result = await this.#changeArea();
  6132. if (!result || result === 'CN' || result === 'skip') {
  6133. return false;
  6134. }
  6135. return await this.#removeFromWishlist(gameId);
  6136. }
  6137. if (dataR.responseText.includes('class="queue_actions_ctn"') && (dataR.responseText.includes('ds_owned_flag ds_flag') || dataR.responseText.includes('add_to_wishlist_area'))) {
  6138. logStatus.success();
  6139. return true;
  6140. }
  6141. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  6142. return false;
  6143. }
  6144. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  6145. return false;
  6146. }
  6147. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  6148. return false;
  6149. } catch (error) {
  6150. throwError(error, 'Steam.removeFromWishlist');
  6151. return false;
  6152. }
  6153. }
  6154. async #toggleFollowGame(gameId, doTask) {
  6155. try {
  6156. if (!doTask && this.whiteList.follows.includes(gameId)) {
  6157. scripts_echoLog({
  6158. type: 'whiteList',
  6159. text: 'Steam.unfollowGame',
  6160. id: gameId
  6161. });
  6162. return true;
  6163. }
  6164. if (this.#ASF) {
  6165. if (await this.#ASF.toggleFollowGame(gameId, doTask)) {
  6166. if (doTask) {
  6167. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  6168. }
  6169. return true;
  6170. }
  6171. return false;
  6172. }
  6173. const logStatus = scripts_echoLog({
  6174. type: `${doTask ? '' : 'un'}followingGame`,
  6175. text: gameId
  6176. });
  6177. const requestData = {
  6178. sessionid: this.#auth.storeSessionID,
  6179. appid: gameId
  6180. };
  6181. if (!doTask) {
  6182. requestData.unfollow = '1';
  6183. }
  6184. const {
  6185. result,
  6186. data
  6187. } = await tools_httpRequest({
  6188. url: 'https://store.steampowered.com/explore/followgame/',
  6189. method: 'POST',
  6190. headers: {
  6191. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6192. },
  6193. data: $.param(requestData)
  6194. });
  6195. if (result === 'Success' && data?.status === 200 && data.responseText === 'true') {
  6196. logStatus.success();
  6197. return true;
  6198. }
  6199. const followed = await this.#isFollowedGame(gameId);
  6200. if (this.#area === 'CN' && followed === 'areaLocked') {
  6201. logStatus.warning(i18n('changeAreaNotice'));
  6202. if (!await this.#changeArea()) {
  6203. return false;
  6204. }
  6205. return await this.#toggleFollowGame(gameId, doTask);
  6206. }
  6207. if (doTask === followed) {
  6208. logStatus.success();
  6209. if (doTask) {
  6210. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  6211. }
  6212. return true;
  6213. }
  6214. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6215. return false;
  6216. } catch (error) {
  6217. throwError(error, 'Steam.toggleFollowGame');
  6218. return false;
  6219. }
  6220. }
  6221. async #isFollowedGame(gameId) {
  6222. try {
  6223. const {
  6224. result,
  6225. data
  6226. } = await tools_httpRequest({
  6227. url: `https://store.steampowered.com/app/${gameId}`,
  6228. method: 'GET'
  6229. });
  6230. if (result === 'Success') {
  6231. if (data?.status === 200) {
  6232. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6233. return 'areaLocked';
  6234. }
  6235. if ($(data.responseText.replace(/<img.*?>/g, '')).find('.queue_control_button.queue_btn_follow>.btnv6_blue_hoverfade.btn_medium.queue_btn_active').css('display') !== 'none') {
  6236. return true;
  6237. }
  6238. return false;
  6239. }
  6240. return false;
  6241. }
  6242. return false;
  6243. } catch (error) {
  6244. throwError(error, 'Steam.isFollowedGame');
  6245. return false;
  6246. }
  6247. }
  6248. async #toggleForum(gameId, doTask = true) {
  6249. try {
  6250. if (!doTask && this.whiteList.forums.includes(gameId)) {
  6251. scripts_echoLog({
  6252. type: 'whiteList',
  6253. text: 'Steam.unsubscribeForum',
  6254. id: gameId
  6255. });
  6256. return true;
  6257. }
  6258. const forumId = await this.#getForumId(gameId);
  6259. if (!forumId) {
  6260. return false;
  6261. }
  6262. const logStatus = scripts_echoLog({
  6263. type: `${doTask ? '' : 'un'}subscribingForum`,
  6264. text: gameId
  6265. });
  6266. const [ id, feature ] = forumId.split('_');
  6267. const {
  6268. result,
  6269. statusText,
  6270. status,
  6271. data
  6272. } = await tools_httpRequest({
  6273. url: `https://steamcommunity.com/forum/${id}/General/${doTask ? '' : 'un'}subscribe/${feature || '0'}/`,
  6274. method: 'POST',
  6275. responseType: 'json',
  6276. headers: {
  6277. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6278. },
  6279. data: $.param({
  6280. sessionid: this.#auth.communitySessionID
  6281. })
  6282. });
  6283. if (result === 'Success') {
  6284. if (data?.status === 200 && (data.response?.success === 1 || data.response?.success === 29)) {
  6285. if (doTask) {
  6286. this.tasks.forums = unique([ ...this.tasks.forums, gameId ]);
  6287. }
  6288. logStatus.success();
  6289. return true;
  6290. }
  6291. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6292. return true;
  6293. }
  6294. logStatus.error(`${result}:${statusText}(${status})`);
  6295. return true;
  6296. } catch (error) {
  6297. throwError(error, 'Steam.toggleForum');
  6298. return true;
  6299. }
  6300. }
  6301. async #getForumId(gameId) {
  6302. try {
  6303. const logStatus = scripts_echoLog({
  6304. type: 'gettingForumId',
  6305. text: gameId
  6306. });
  6307. const forumId = this.#cache.forum[gameId];
  6308. if (forumId) {
  6309. logStatus.success();
  6310. return forumId;
  6311. }
  6312. const {
  6313. result,
  6314. statusText,
  6315. status,
  6316. data
  6317. } = await tools_httpRequest({
  6318. url: `https://steamcommunity.com/app/${gameId}/discussions/`,
  6319. method: 'GET'
  6320. });
  6321. if (result === 'Success') {
  6322. if (data?.status === 200) {
  6323. const forumId = data.responseText?.match(/General_([\d]+(_[\d]+)?)/)?.[1];
  6324. if (forumId) {
  6325. this.#setCache('forum', gameId, forumId);
  6326. logStatus.success();
  6327. return forumId;
  6328. }
  6329. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6330. return false;
  6331. }
  6332. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6333. return false;
  6334. }
  6335. logStatus.error(`${result}:${statusText}(${status})`);
  6336. return false;
  6337. } catch (error) {
  6338. throwError(error, 'Steam.getForumId');
  6339. return false;
  6340. }
  6341. }
  6342. async #toggleFavoriteWorkshop(id, doTask = true) {
  6343. try {
  6344. if (!doTask && this.whiteList.workshops.includes(id)) {
  6345. scripts_echoLog({
  6346. type: 'whiteList',
  6347. text: 'Steam.unfavoriteWorkshop',
  6348. id: id
  6349. });
  6350. return true;
  6351. }
  6352. const appid = await this.#getWorkshopAppId(id);
  6353. if (!appid) {
  6354. return false;
  6355. }
  6356. const logStatus = scripts_echoLog({
  6357. type: doTask ? 'favoritingWorkshop' : 'unfavoritingWorkshop',
  6358. text: id
  6359. });
  6360. const {
  6361. result,
  6362. statusText,
  6363. status,
  6364. data
  6365. } = await tools_httpRequest({
  6366. url: `https://steamcommunity.com/sharedfiles/${doTask ? '' : 'un'}favorite`,
  6367. method: 'POST',
  6368. headers: {
  6369. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6370. },
  6371. data: $.param({
  6372. id: id,
  6373. appid: appid,
  6374. sessionid: this.#auth.communitySessionID
  6375. })
  6376. });
  6377. if (result === 'Success') {
  6378. if (data?.status === 200 && !data.responseText) {
  6379. if (doTask) {
  6380. this.tasks.workshops = unique([ ...this.tasks.workshops, id ]);
  6381. }
  6382. logStatus.success();
  6383. return true;
  6384. }
  6385. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6386. return false;
  6387. }
  6388. logStatus.error(`${result}:${statusText}(${status})`);
  6389. return false;
  6390. } catch (error) {
  6391. throwError(error, 'Steam.toggleFavoriteWorkshop');
  6392. return false;
  6393. }
  6394. }
  6395. async #getWorkshopAppId(id) {
  6396. try {
  6397. const logStatus = scripts_echoLog({
  6398. type: 'gettingWorkshopAppId',
  6399. text: id
  6400. });
  6401. const appId = this.#cache.workshop[id];
  6402. if (appId) {
  6403. logStatus.success();
  6404. return appId;
  6405. }
  6406. const {
  6407. result,
  6408. statusText,
  6409. status,
  6410. data
  6411. } = await tools_httpRequest({
  6412. url: `https://steamcommunity.com/sharedfiles/filedetails/?id=${id}`,
  6413. method: 'GET'
  6414. });
  6415. if (result === 'Success') {
  6416. if (data?.status === 200) {
  6417. const appId = data.responseText.match(/<input type="hidden" name="appid" value="([\d]+?)" \/>/)?.[1];
  6418. if (appId) {
  6419. this.#setCache('workshop', id, appId);
  6420. logStatus.success();
  6421. return appId;
  6422. }
  6423. logStatus.error('Error: getWorkshopAppId failed');
  6424. return false;
  6425. }
  6426. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6427. return false;
  6428. }
  6429. logStatus.error(`${result}:${statusText}(${status})`);
  6430. return false;
  6431. } catch (error) {
  6432. throwError(error, 'Steam.getWorkshopAppId');
  6433. return false;
  6434. }
  6435. }
  6436. async #voteUpWorkshop(id) {
  6437. try {
  6438. const logStatus = scripts_echoLog({
  6439. type: 'votingUpWorkshop',
  6440. text: id
  6441. });
  6442. const {
  6443. result,
  6444. statusText,
  6445. status,
  6446. data
  6447. } = await tools_httpRequest({
  6448. url: 'https://steamcommunity.com/sharedfiles/voteup',
  6449. method: 'POST',
  6450. responseType: 'json',
  6451. headers: {
  6452. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6453. },
  6454. data: $.param({
  6455. id: id,
  6456. sessionid: this.#auth.communitySessionID
  6457. })
  6458. });
  6459. if (result === 'Success') {
  6460. if (data?.status === 200 && data.response?.success === 1) {
  6461. logStatus.success();
  6462. return true;
  6463. }
  6464. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6465. return true;
  6466. }
  6467. logStatus.error(`${result}:${statusText}(${status})`);
  6468. return true;
  6469. } catch (error) {
  6470. throwError(error, 'Steam.voteupWorkshop');
  6471. return true;
  6472. }
  6473. }
  6474. async #toggleCurator(curatorId, doTask = true) {
  6475. try {
  6476. if (!doTask && this.whiteList.curators.includes(curatorId)) {
  6477. scripts_echoLog({
  6478. type: 'whiteList',
  6479. text: 'Steam.unfollowCurator',
  6480. id: curatorId
  6481. });
  6482. return true;
  6483. }
  6484. if (this.#ASF) {
  6485. return await this.#ASF.toggleCurator(curatorId, doTask);
  6486. }
  6487. const logStatus = scripts_echoLog({
  6488. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  6489. text: curatorId
  6490. });
  6491. const {
  6492. result,
  6493. statusText,
  6494. status,
  6495. data
  6496. } = await tools_httpRequest({
  6497. url: 'https://store.steampowered.com/curators/ajaxfollow',
  6498. method: 'POST',
  6499. headers: {
  6500. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6501. },
  6502. data: $.param({
  6503. clanid: curatorId,
  6504. sessionid: this.#auth.storeSessionID,
  6505. follow: doTask
  6506. }),
  6507. dataType: 'json'
  6508. });
  6509. if (result === 'Success') {
  6510. if (data?.status === 200 && data.response?.success?.success === 1) {
  6511. logStatus.success();
  6512. return true;
  6513. }
  6514. logStatus.error(`Error:${data?.statusText}(${data?.response?.success}` || `${data?.status})`);
  6515. return false;
  6516. }
  6517. logStatus.error(`${result}:${statusText}(${status})`);
  6518. return false;
  6519. } catch (error) {
  6520. throwError(error, 'Steam.toggleCurator');
  6521. return false;
  6522. }
  6523. }
  6524. async getCuratorId(path, name) {
  6525. try {
  6526. const logStatus = scripts_echoLog({
  6527. type: 'gettingCuratorId',
  6528. text: `${path}/${name}`
  6529. });
  6530. const curatorId = this.#cache.curator[`${path}/${name}`];
  6531. if (curatorId) {
  6532. logStatus.success();
  6533. return curatorId;
  6534. }
  6535. const {
  6536. result,
  6537. statusText,
  6538. status,
  6539. data
  6540. } = await tools_httpRequest({
  6541. url: `https://store.steampowered.com/${path}/${name}`,
  6542. method: 'GET',
  6543. headers: {
  6544. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6545. }
  6546. });
  6547. if (result === 'Success') {
  6548. if (data?.status === 200) {
  6549. const curatorId = data.responseText.match(/g_pagingData.*?"clanid":([\d]+)/)?.[1];
  6550. if (curatorId) {
  6551. this.#setCache('curator', `${path}/${name}`, curatorId);
  6552. logStatus.success();
  6553. return curatorId;
  6554. }
  6555. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6556. return false;
  6557. }
  6558. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6559. return false;
  6560. }
  6561. logStatus.error(`${result}:${statusText}(${status})`);
  6562. return false;
  6563. } catch (error) {
  6564. throwError(error, 'Steam.getCuratorID');
  6565. return false;
  6566. }
  6567. }
  6568. async #toggleCuratorLike(link, doTask = true) {
  6569. try {
  6570. const [ path, name ] = link.split('/');
  6571. if (!(path && name)) {
  6572. scripts_echoLog({
  6573. text: i18n('errorLink', link)
  6574. });
  6575. return false;
  6576. }
  6577. const curatorId = await this.getCuratorId(path, name);
  6578. if (curatorId) {
  6579. return await this.#toggleCurator(curatorId, doTask);
  6580. }
  6581. return false;
  6582. } catch (error) {
  6583. throwError(error, 'Steam.toggleCuratorLike');
  6584. return false;
  6585. }
  6586. }
  6587. async #getAnnouncementParams(appId, viewId) {
  6588. try {
  6589. const logStatus = scripts_echoLog({
  6590. type: 'gettingAnnouncementParams',
  6591. text: appId,
  6592. id: viewId
  6593. });
  6594. const {
  6595. result,
  6596. statusText,
  6597. status,
  6598. data
  6599. } = await tools_httpRequest({
  6600. 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`,
  6601. method: 'GET',
  6602. responseType: 'json',
  6603. headers: {
  6604. Host: 'store.steampowered.com',
  6605. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6606. }
  6607. });
  6608. if (result === 'Success') {
  6609. if (data?.status === 200 && data?.response?.success === 1) {
  6610. const {
  6611. clanid,
  6612. gid
  6613. } = data.response.event?.announcement_body || {};
  6614. if (clanid) {
  6615. logStatus.success();
  6616. return {
  6617. clanId: clanid,
  6618. gid: gid
  6619. };
  6620. }
  6621. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6622. return {};
  6623. }
  6624. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6625. return {};
  6626. }
  6627. logStatus.error(`${result}:${statusText}(${status})`);
  6628. return {};
  6629. } catch (error) {
  6630. throwError(error, 'Steam.likeAnnouncement');
  6631. return {};
  6632. }
  6633. }
  6634. async #likeAnnouncement(id) {
  6635. try {
  6636. const [ appId, viewId ] = id.split('/');
  6637. if (!(appId && viewId)) {
  6638. scripts_echoLog({}).error(`${i18n('missParams')}(id)`);
  6639. return false;
  6640. }
  6641. const {
  6642. clanId,
  6643. gid
  6644. } = await this.#getAnnouncementParams(appId, viewId);
  6645. if (!clanId) {
  6646. return false;
  6647. }
  6648. const logStatus = scripts_echoLog({
  6649. type: 'likingAnnouncement',
  6650. text: appId,
  6651. id: viewId
  6652. });
  6653. const {
  6654. result,
  6655. statusText,
  6656. status,
  6657. data
  6658. } = await tools_httpRequest({
  6659. url: `https://store.steampowered.com/updated/ajaxrateupdate/${gid || viewId}`,
  6660. method: 'POST',
  6661. headers: {
  6662. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6663. Host: 'store.steampowered.com',
  6664. Origin: 'https://store.steampowered.com',
  6665. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6666. },
  6667. data: $.param({
  6668. sessionid: this.#auth.storeSessionID,
  6669. voteup: 1,
  6670. clanid: clanId,
  6671. ajax: 1
  6672. }),
  6673. dataType: 'json'
  6674. });
  6675. if (result === 'Success') {
  6676. if (data?.status === 200 && data.response.success === 1) {
  6677. logStatus.success();
  6678. return true;
  6679. }
  6680. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6681. return false;
  6682. }
  6683. logStatus.error(`${result}:${statusText}(${status})`);
  6684. return false;
  6685. } catch (error) {
  6686. throwError(error, 'Steam.likeAnnouncement');
  6687. return false;
  6688. }
  6689. }
  6690. async #appid2subid(id) {
  6691. try {
  6692. const logStatus = scripts_echoLog({
  6693. type: 'gettingSubid',
  6694. text: id
  6695. });
  6696. const {
  6697. result,
  6698. statusText,
  6699. status,
  6700. data
  6701. } = await tools_httpRequest({
  6702. url: `https://store.steampowered.com/app/${id}`,
  6703. method: 'GET',
  6704. headers: {
  6705. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6706. }
  6707. });
  6708. if (result === 'Success') {
  6709. if (data?.status === 200) {
  6710. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6711. logStatus.success(i18n('owned'));
  6712. return false;
  6713. }
  6714. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6715. logStatus.warning(i18n('changeAreaNotice'));
  6716. const result = await this.#changeArea();
  6717. if (!result || result === 'CN' || result === 'skip') {
  6718. return false;
  6719. }
  6720. return await this.#appid2subid(id);
  6721. }
  6722. let subid = data.responseText.match(/name="subid" value="([\d]+?)"/)?.[1];
  6723. if (subid) {
  6724. logStatus.success();
  6725. return subid;
  6726. }
  6727. subid = data.responseText.match(/AddFreeLicense\(\s*(\d+)/)?.[1];
  6728. if (subid) {
  6729. logStatus.success();
  6730. return subid;
  6731. }
  6732. logStatus.error(`Error:${i18n('noSubid')}`);
  6733. return false;
  6734. }
  6735. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6736. return false;
  6737. }
  6738. logStatus.error(`${result}:${statusText}(${status})`);
  6739. return false;
  6740. } catch (error) {
  6741. throwError(error, 'Steam.appid2subid');
  6742. return false;
  6743. }
  6744. }
  6745. async #getLicenses() {
  6746. try {
  6747. const logStatus = scripts_echoLog({
  6748. text: i18n('gettingLicenses')
  6749. });
  6750. const {
  6751. result,
  6752. statusText,
  6753. status,
  6754. data
  6755. } = await tools_httpRequest({
  6756. url: `https://store.steampowered.com/dynamicstore/userdata/?t=${new Date().getTime()}`,
  6757. method: 'GET',
  6758. responseType: 'json'
  6759. });
  6760. if (result === 'Success') {
  6761. if (data?.status === 200) {
  6762. logStatus.success();
  6763. return data.response?.rgOwnedPackages;
  6764. }
  6765. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6766. return false;
  6767. }
  6768. logStatus.error(`${result}:${statusText}(${status})`);
  6769. return false;
  6770. } catch (error) {
  6771. throwError(error, 'Steam.getLicenses');
  6772. return false;
  6773. }
  6774. }
  6775. async #addLicense(id) {
  6776. try {
  6777. if (this.#ASF) {
  6778. return await this.#ASF.addLicense(id);
  6779. }
  6780. const [ type, ids ] = id.split('-');
  6781. if (type === 'appid') {
  6782. const subid = await this.#appid2subid(ids);
  6783. if (!subid) {
  6784. return false;
  6785. }
  6786. const logStatus = scripts_echoLog({
  6787. type: 'addingFreeLicense',
  6788. text: ids
  6789. });
  6790. if (!await this.#addFreeLicense(subid, logStatus)) {
  6791. return false;
  6792. }
  6793. const {
  6794. result,
  6795. statusText,
  6796. status,
  6797. data
  6798. } = await tools_httpRequest({
  6799. url: `https://store.steampowered.com/app/${ids}`,
  6800. method: 'GET'
  6801. });
  6802. if (result === 'Success') {
  6803. if (data?.status === 200) {
  6804. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6805. logStatus.success();
  6806. return true;
  6807. }
  6808. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6809. return false;
  6810. }
  6811. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6812. return false;
  6813. }
  6814. logStatus.error(`${result}:${statusText}(${status})`);
  6815. return false;
  6816. } else if (type === 'subid') {
  6817. if (this.#area === 'CN') {
  6818. scripts_echoLog({}).success(i18n('tryChangeAreaNotice'));
  6819. await this.#changeArea();
  6820. }
  6821. const logStatusArr = {};
  6822. const idsArr = ids.split(',');
  6823. for (const subid of idsArr) {
  6824. const logStatus = scripts_echoLog({
  6825. type: 'addingFreeLicenseSubid',
  6826. text: subid
  6827. });
  6828. if (!await this.#addFreeLicense(subid, logStatus)) {
  6829. return false;
  6830. }
  6831. logStatusArr[subid] = logStatus;
  6832. }
  6833. const licenses = await this.#getLicenses();
  6834. if (!licenses) {
  6835. return false;
  6836. }
  6837. for (const subid of idsArr) {
  6838. if (licenses.includes(parseInt(subid, 10))) {
  6839. logStatusArr[subid].success();
  6840. } else {
  6841. logStatusArr[subid].error();
  6842. }
  6843. }
  6844. return true;
  6845. }
  6846. return false;
  6847. } catch (error) {
  6848. throwError(error, 'Steam.addLicense');
  6849. return false;
  6850. }
  6851. }
  6852. async #addFreeLicense(id, logStatusPre) {
  6853. try {
  6854. const logStatus = logStatusPre || scripts_echoLog({
  6855. type: 'addingFreeLicenseSubid',
  6856. text: id
  6857. });
  6858. const {
  6859. result,
  6860. statusText,
  6861. status,
  6862. data
  6863. } = await tools_httpRequest({
  6864. url: `https://store.steampowered.com/freelicense/addfreelicense/${id}`,
  6865. method: 'POST',
  6866. headers: {
  6867. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6868. Host: 'store.steampowered.com',
  6869. Origin: 'https://store.steampowered.com',
  6870. Referer: 'https://store.steampowered.com/account/licenses/'
  6871. },
  6872. data: $.param({
  6873. ajax: true,
  6874. sessionid: this.#auth.storeSessionID
  6875. }),
  6876. dataType: 'json'
  6877. });
  6878. if (result === 'Success') {
  6879. if (data?.status === 200) {
  6880. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6881. logStatus.warning(i18n('changeAreaNotice'));
  6882. const result = await this.#changeArea();
  6883. if (!result || [ 'CN', 'skip' ].includes(result)) {
  6884. return false;
  6885. }
  6886. return await this.#addFreeLicense(id);
  6887. }
  6888. logStatus.success();
  6889. return true;
  6890. }
  6891. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6892. return false;
  6893. }
  6894. logStatus.error(`${result}:${statusText}(${status})`);
  6895. return false;
  6896. } catch (error) {
  6897. throwError(error, 'Steam.addFreeLicense');
  6898. return false;
  6899. }
  6900. }
  6901. async #requestPlayTestAccess(id) {
  6902. try {
  6903. if (this.#ASF) {
  6904. return await this.#ASF.requestPlayTestAccess(id);
  6905. }
  6906. const logStatus = scripts_echoLog({
  6907. type: 'requestingPlayTestAccess',
  6908. text: id
  6909. });
  6910. const {
  6911. result,
  6912. statusText,
  6913. status,
  6914. data
  6915. } = await tools_httpRequest({
  6916. url: `https://store.steampowered.com/ajaxrequestplaytestaccess/${id}`,
  6917. method: 'POST',
  6918. headers: {
  6919. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6920. Host: 'store.steampowered.com',
  6921. Origin: 'https://store.steampowered.com',
  6922. Referer: `https://store.steampowered.com/app/${id}`
  6923. },
  6924. data: $.param({
  6925. sessionid: this.#auth.storeSessionID
  6926. }),
  6927. dataType: 'json'
  6928. });
  6929. if (result === 'Success') {
  6930. if (data?.status === 200 && data?.response?.success === 1) {
  6931. logStatus.success();
  6932. return true;
  6933. }
  6934. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6935. return false;
  6936. }
  6937. logStatus.error(`${result}:${statusText}(${status})`);
  6938. return false;
  6939. } catch (error) {
  6940. throwError(error, 'Steam.requestPlayTestAccess');
  6941. return false;
  6942. }
  6943. }
  6944. async toggle({
  6945. doTask = true,
  6946. groupLinks = [],
  6947. officialGroupLinks = [],
  6948. wishlistLinks = [],
  6949. followLinks = [],
  6950. forumLinks = [],
  6951. workshopLinks = [],
  6952. workshopVoteLinks = [],
  6953. curatorLinks = [],
  6954. curatorLikeLinks = [],
  6955. announcementLinks = [],
  6956. licenseLinks = [],
  6957. playtestLinks = []
  6958. }) {
  6959. try {
  6960. if ([ ...groupLinks, ...officialGroupLinks, ...forumLinks, ...workshopLinks, ...workshopVoteLinks ].length > 0 && !this.#communityInitialized) {
  6961. scripts_echoLog({
  6962. text: i18n('needInit')
  6963. });
  6964. return false;
  6965. }
  6966. if ([ ...wishlistLinks, ...followLinks, ...curatorLinks, ...curatorLikeLinks, ...announcementLinks, ...licenseLinks, ...playtestLinks ].length > 0 && !this.#storeInitialized) {
  6967. scripts_echoLog({
  6968. text: i18n('needInit')
  6969. });
  6970. return false;
  6971. }
  6972. const prom = [];
  6973. if (doTask && !globalOptions.doTask.steam.groups || !doTask && !globalOptions.undoTask.steam.groups) {
  6974. scripts_echoLog({
  6975. type: 'globalOptionsSkip',
  6976. text: 'steam.groups'
  6977. });
  6978. } else {
  6979. const realGroups = this.getRealParams('groups', groupLinks, doTask, link => link.match(/groups\/(.+)\/?/)?.[1]?.split('/')?.[0]);
  6980. if (realGroups.length > 0) {
  6981. for (const group of realGroups) {
  6982. if (doTask) {
  6983. prom.push(this.#joinGroup(group));
  6984. } else {
  6985. prom.push(this.#leaveGroup(group));
  6986. }
  6987. await delay(1e3);
  6988. }
  6989. }
  6990. }
  6991. if (doTask && !globalOptions.doTask.steam.officialGroups || !doTask && !globalOptions.undoTask.steam.officialGroups) {
  6992. scripts_echoLog({
  6993. type: 'globalOptionsSkip',
  6994. text: 'steam.officialGroups'
  6995. });
  6996. } else {
  6997. const realOfficialGroups = this.getRealParams('officialGroups', officialGroupLinks, doTask, link => link.match(/games\/(.+)\/?/)?.[1]);
  6998. if (realOfficialGroups.length > 0) {
  6999. for (const officialGroup of realOfficialGroups) {
  7000. if (doTask) {
  7001. prom.push(this.#joinOfficialGroup(officialGroup));
  7002. } else {
  7003. prom.push(this.#leaveOfficialGroup(officialGroup));
  7004. }
  7005. await delay(1e3);
  7006. }
  7007. }
  7008. }
  7009. if (doTask && !globalOptions.doTask.steam.wishlists || !doTask && !globalOptions.undoTask.steam.wishlists) {
  7010. scripts_echoLog({
  7011. type: 'globalOptionsSkip',
  7012. text: 'steam.wishlists'
  7013. });
  7014. } else {
  7015. const realWishlists = this.getRealParams('wishlists', wishlistLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  7016. if (realWishlists.length > 0) {
  7017. for (const game of realWishlists) {
  7018. if (doTask) {
  7019. prom.push(this.#addToWishlist(game));
  7020. } else {
  7021. prom.push(this.#removeFromWishlist(game));
  7022. }
  7023. await delay(1e3);
  7024. }
  7025. }
  7026. }
  7027. if (doTask && !globalOptions.doTask.steam.follows || !doTask && !globalOptions.undoTask.steam.follows) {
  7028. scripts_echoLog({
  7029. type: 'globalOptionsSkip',
  7030. text: 'steam.follows'
  7031. });
  7032. } else {
  7033. const realFollows = this.getRealParams('follows', followLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  7034. if (realFollows.length > 0) {
  7035. for (const game of realFollows) {
  7036. prom.push(this.#toggleFollowGame(game, doTask));
  7037. await delay(1e3);
  7038. }
  7039. }
  7040. }
  7041. if (doTask && !globalOptions.doTask.steam.forums || !doTask && !globalOptions.undoTask.steam.forums) {
  7042. scripts_echoLog({
  7043. type: 'globalOptionsSkip',
  7044. text: 'steam.forums'
  7045. });
  7046. } else {
  7047. const realForums = this.getRealParams('forums', forumLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  7048. if (realForums.length > 0) {
  7049. for (const forum of realForums) {
  7050. prom.push(this.#toggleForum(forum, doTask));
  7051. await delay(1e3);
  7052. }
  7053. }
  7054. }
  7055. if (doTask && !globalOptions.doTask.steam.workshops || !doTask && !globalOptions.undoTask.steam.workshops) {
  7056. scripts_echoLog({
  7057. type: 'globalOptionsSkip',
  7058. text: 'steam.workshops'
  7059. });
  7060. } else {
  7061. const realWorkshops = this.getRealParams('workshops', workshopLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  7062. if (realWorkshops.length > 0) {
  7063. for (const workshop of realWorkshops) {
  7064. prom.push(this.#toggleFavoriteWorkshop(workshop, doTask));
  7065. await delay(1e3);
  7066. }
  7067. }
  7068. }
  7069. if (doTask && !globalOptions.doTask.steam.workshopVotes) {
  7070. scripts_echoLog({
  7071. type: 'globalOptionsSkip',
  7072. text: 'steam.workshopVotes'
  7073. });
  7074. } else {
  7075. const realworkshopVotes = this.getRealParams('workshopVotes', workshopVoteLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  7076. if (doTask && realworkshopVotes.length > 0) {
  7077. for (const workshop of realworkshopVotes) {
  7078. prom.push(this.#voteUpWorkshop(workshop));
  7079. await delay(1e3);
  7080. }
  7081. }
  7082. }
  7083. if (doTask && !globalOptions.doTask.steam.curators || !doTask && !globalOptions.undoTask.steam.curators) {
  7084. scripts_echoLog({
  7085. type: 'globalOptionsSkip',
  7086. text: 'steam.curators'
  7087. });
  7088. } else {
  7089. const realCurators = this.getRealParams('curators', curatorLinks, doTask, link => link.match(/curator\/([\d]+)/)?.[1]);
  7090. const realCuratorLikes = this.getRealParams('curatorLikes', curatorLikeLinks, doTask, link => link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3).join('/'));
  7091. if (realCurators.length > 0) {
  7092. for (const curator of realCurators) {
  7093. prom.push(this.#toggleCurator(curator, doTask));
  7094. await delay(1e3);
  7095. }
  7096. }
  7097. if (realCuratorLikes.length > 0) {
  7098. for (const curatorLike of realCuratorLikes) {
  7099. prom.push(this.#toggleCuratorLike(curatorLike, doTask));
  7100. await delay(1e3);
  7101. }
  7102. }
  7103. }
  7104. if (doTask && !globalOptions.doTask.steam.announcements) {
  7105. scripts_echoLog({
  7106. type: 'globalOptionsSkip',
  7107. text: 'steam.announcements'
  7108. });
  7109. } else {
  7110. const realAnnouncements = this.getRealParams('announcements', announcementLinks, doTask, link => {
  7111. if (link.includes('store.steampowered.com')) {
  7112. return link.match(/store\.steampowered\.com\/news\/app\/([\d]+)\/view\/([\d]+)/)?.slice(1, 3).join('/');
  7113. }
  7114. return link.match(/steamcommunity\.com\/games\/([\d]+)\/announcements\/detail\/([\d]+)/)?.slice(1, 3).join('/');
  7115. });
  7116. if (doTask && realAnnouncements.length > 0) {
  7117. for (const id of realAnnouncements) {
  7118. prom.push(this.#likeAnnouncement(id));
  7119. await delay(1e3);
  7120. }
  7121. }
  7122. }
  7123. if (doTask && !globalOptions.doTask.steam.licenses) {
  7124. scripts_echoLog({
  7125. type: 'globalOptionsSkip',
  7126. text: 'steam.licenses'
  7127. });
  7128. } else if (doTask && globalOptions.doTask.steam.licenses && licenseLinks.length > 0) {
  7129. for (const ids of licenseLinks) {
  7130. const [ type, idsStr ] = ids.split('-');
  7131. const idsArr = idsStr.split(',');
  7132. for (const id of idsArr) {
  7133. prom.push(this.#addLicense(`${type}-${id}`));
  7134. await delay(1e3);
  7135. }
  7136. }
  7137. }
  7138. if (doTask && !globalOptions.doTask.steam.playtests) {
  7139. scripts_echoLog({
  7140. type: 'globalOptionsSkip',
  7141. text: 'steam.playtests'
  7142. });
  7143. } else {
  7144. const realPlaytests = this.getRealParams('playtests', playtestLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  7145. if (doTask && globalOptions.doTask.steam.playtests && realPlaytests.length > 0) {
  7146. for (const id of realPlaytests) {
  7147. prom.push(this.#requestPlayTestAccess(id));
  7148. await delay(1e3);
  7149. }
  7150. }
  7151. }
  7152. return Promise.all(prom).then(async () => {
  7153. if (this.#oldArea && this.#area !== this.#oldArea) {
  7154. scripts_echoLog({}).warning(i18n('steamFinishNotice') + this.#oldArea);
  7155. await this.#changeArea(this.#oldArea);
  7156. }
  7157. return true;
  7158. });
  7159. } catch (error) {
  7160. throwError(error, 'Steam.toggle');
  7161. return false;
  7162. }
  7163. }
  7164. #setCache(type, name, id) {
  7165. try {
  7166. this.#cache[type][name] = id;
  7167. GM_setValue('steamCache', this.#cache);
  7168. } catch (error) {
  7169. throwError(error, 'Steam.setCache');
  7170. }
  7171. }
  7172. }
  7173. const social_Steam = Steam;
  7174. class Website {
  7175. undoneTasks;
  7176. socialTasks;
  7177. giveawayId;
  7178. socialInitialized = {
  7179. discord: false,
  7180. instagram: false,
  7181. reddit: false,
  7182. twitch: false,
  7183. twitter: false,
  7184. vk: false,
  7185. youtube: false,
  7186. steamStore: false,
  7187. steamCommunity: false
  7188. };
  7189. initialized = false;
  7190. steamTaskType = {
  7191. steamStore: false,
  7192. steamCommunity: false
  7193. };
  7194. social = {};
  7195. async #bind(name, init) {
  7196. try {
  7197. return {
  7198. name: name,
  7199. result: await init
  7200. };
  7201. } catch (error) {
  7202. throwError(error, 'Website.bind');
  7203. return {
  7204. name: name,
  7205. result: false
  7206. };
  7207. }
  7208. }
  7209. async initSocial(action) {
  7210. try {
  7211. const pro = [];
  7212. const tasks = action === 'do' ? this.undoneTasks : this.socialTasks;
  7213. if (tasks.discord) {
  7214. const hasDiscord = Object.values(tasks.discord).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7215. if (hasDiscord && (!this.socialInitialized.discord || !this.social.discord)) {
  7216. this.social.discord = new social_Discord();
  7217. pro.push(this.#bind('discord', this.social.discord.init(action)));
  7218. }
  7219. }
  7220. if (tasks.instagram) {
  7221. const hasInstagram = Object.values(tasks.instagram).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7222. if (hasInstagram && (!this.socialInitialized.instagram || !this.social.instagram)) {
  7223. this.social.instagram = new social_Instagram();
  7224. pro.push(this.#bind('instagram', this.social.instagram.init()));
  7225. }
  7226. }
  7227. if (tasks.reddit) {
  7228. const hasReddit = Object.values(tasks.reddit).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7229. if (hasReddit && (!this.socialInitialized.reddit || !this.social.reddit)) {
  7230. this.social.reddit = new social_Reddit();
  7231. pro.push(this.#bind('reddit', this.social.reddit.init()));
  7232. }
  7233. }
  7234. if (tasks.twitch) {
  7235. const hasTwitch = Object.values(tasks.twitch).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7236. if (hasTwitch && (!this.socialInitialized.twitch || !this.social.twitch)) {
  7237. this.social.twitch = new social_Twitch();
  7238. pro.push(this.#bind('twitch', this.social.twitch.init()));
  7239. }
  7240. }
  7241. if (tasks.twitter) {
  7242. const hasTwitter = Object.values(tasks.twitter).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7243. if (hasTwitter && (!this.socialInitialized.twitter || !this.social.twitter)) {
  7244. this.social.twitter = new social_Twitter();
  7245. pro.push(this.#bind('twitter', this.social.twitter.init()));
  7246. }
  7247. }
  7248. if (tasks.vk) {
  7249. const hasVk = Object.values(tasks.vk).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7250. if (hasVk && (!this.socialInitialized.vk || !this.social.vk)) {
  7251. this.social.vk = new social_Vk();
  7252. pro.push(this.#bind('vk', this.social.vk.init()));
  7253. }
  7254. }
  7255. if (tasks.youtube) {
  7256. const hasYoutube = Object.values(tasks.youtube).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7257. if (hasYoutube && (!this.socialInitialized.youtube || !this.social.youtube)) {
  7258. this.social.youtube = new Youtube();
  7259. pro.push(this.#bind('youtube', this.social.youtube.init()));
  7260. }
  7261. }
  7262. if (tasks.steam) {
  7263. const steamLength = Object.values(tasks.steam).reduce((total, arr) => [ ...total, ...arr ]).length;
  7264. if (steamLength > 0) {
  7265. if (!this.social.steam) {
  7266. this.social.steam = new social_Steam();
  7267. }
  7268. 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);
  7269. if (steamLength - steamCommunityLength > 0) {
  7270. this.steamTaskType.steamStore = true;
  7271. if (!this.socialInitialized.steamStore) {
  7272. pro.push(this.#bind('steamStore', this.social.steam.init('store')));
  7273. }
  7274. }
  7275. if (steamCommunityLength > 0) {
  7276. if (!this.socialInitialized.steamCommunity) {
  7277. this.steamTaskType.steamCommunity = true;
  7278. pro.push(this.#bind('steamCommunity', this.social.steam.init('community')));
  7279. }
  7280. }
  7281. }
  7282. }
  7283. if (tasks.links && tasks.links.length > 0) {
  7284. this.social.visitLink = visitLink;
  7285. }
  7286. return await Promise.all(pro).then(result => {
  7287. let checked = true;
  7288. for (const data of result) {
  7289. if (data.result) {
  7290. this.socialInitialized[data.name] = data.result;
  7291. } else {
  7292. checked = false;
  7293. }
  7294. }
  7295. return checked;
  7296. });
  7297. } catch (error) {
  7298. throwError(error, 'Website.initSocial');
  7299. return false;
  7300. }
  7301. }
  7302. uniqueTasks(allTasks) {
  7303. try {
  7304. const result = {};
  7305. for (const [ social, types ] of Object.entries(allTasks)) {
  7306. result[social] = {};
  7307. for (const [ type, tasks ] of Object.entries(types)) {
  7308. result[social][type] = unique(tasks);
  7309. }
  7310. }
  7311. return result;
  7312. } catch (error) {
  7313. throwError(error, 'Website.uniqueTasks');
  7314. return allTasks;
  7315. }
  7316. }
  7317. async toggleTask(action) {
  7318. try {
  7319. if (!this.initialized && !this.init()) {
  7320. return false;
  7321. }
  7322. if (!await this.classifyTask(action)) {
  7323. return false;
  7324. }
  7325. await this.initSocial(action);
  7326. const pro = [];
  7327. const doTask = action === 'do';
  7328. const tasks = doTask ? this.undoneTasks : this.socialTasks;
  7329. if (this.socialInitialized.discord === true && this.social.discord) {
  7330. pro.push(this.social.discord.toggle({
  7331. doTask: doTask,
  7332. ...tasks.discord
  7333. }));
  7334. }
  7335. if (this.socialInitialized.instagram === true && this.social.instagram) {
  7336. pro.push(this.social.instagram.toggle({
  7337. doTask: doTask,
  7338. ...tasks.instagram
  7339. }));
  7340. }
  7341. if (this.socialInitialized.reddit === true && this.social.reddit) {
  7342. pro.push(this.social.reddit.toggle({
  7343. doTask: doTask,
  7344. ...tasks.reddit
  7345. }));
  7346. }
  7347. if (this.socialInitialized.twitch === true && this.social.twitch) {
  7348. pro.push(this.social.twitch.toggle({
  7349. doTask: doTask,
  7350. ...tasks.twitch
  7351. }));
  7352. }
  7353. if (this.socialInitialized.twitter === true && this.social.twitter) {
  7354. pro.push(this.social.twitter.toggle({
  7355. doTask: doTask,
  7356. ...tasks.twitter
  7357. }));
  7358. }
  7359. if (this.socialInitialized.vk === true && this.social.vk) {
  7360. pro.push(this.social.vk.toggle({
  7361. doTask: doTask,
  7362. ...tasks.vk
  7363. }));
  7364. }
  7365. if (this.socialInitialized.youtube === true && this.social.youtube) {
  7366. pro.push(this.social.youtube.toggle({
  7367. doTask: doTask,
  7368. ...tasks.youtube
  7369. }));
  7370. }
  7371. if ((this.steamTaskType.steamCommunity ? this.socialInitialized.steamCommunity === true : true) && (this.steamTaskType.steamStore ? this.socialInitialized.steamStore === true : true) && this.social.steam) {
  7372. pro.push(this.social.steam.toggle({
  7373. doTask: doTask,
  7374. ...tasks.steam
  7375. }));
  7376. }
  7377. if (this.social.visitLink && tasks.links && doTask) {
  7378. for (const link of tasks.links) {
  7379. pro.push(this.social.visitLink(link));
  7380. }
  7381. }
  7382. if (doTask && tasks.extra && this.extraDoTask) {
  7383. const hasExtra = Object.values(tasks.extra).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7384. if (hasExtra) {
  7385. pro.push(this.extraDoTask(tasks.extra));
  7386. }
  7387. }
  7388. await Promise.all(pro);
  7389. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7390. return true;
  7391. } catch (error) {
  7392. throwError(error, 'Website.toggleTask');
  7393. return false;
  7394. }
  7395. }
  7396. async doTask() {
  7397. try {
  7398. return await this.toggleTask('do');
  7399. } catch (error) {
  7400. throwError(error, 'Website.doTask');
  7401. return false;
  7402. }
  7403. }
  7404. async undoTask() {
  7405. try {
  7406. return await this.toggleTask('undo');
  7407. } catch (error) {
  7408. throwError(error, 'Website.undoTask');
  7409. return false;
  7410. }
  7411. }
  7412. }
  7413. const website_Website = Website;
  7414. const defaultTasksTemplate = {
  7415. steam: {
  7416. groupLinks: [],
  7417. wishlistLinks: [],
  7418. curatorLinks: [],
  7419. followLinks: []
  7420. },
  7421. discord: {
  7422. serverLinks: []
  7423. },
  7424. vk: {
  7425. nameLinks: []
  7426. },
  7427. extra: {
  7428. website: []
  7429. }
  7430. };
  7431. const defaultTasks = JSON.stringify(defaultTasksTemplate);
  7432. class FreeAnyWhere extends website_Website {
  7433. name = 'FreeAnyWhere';
  7434. tasks = [];
  7435. socialTasks = JSON.parse(defaultTasks);
  7436. undoneTasks = JSON.parse(defaultTasks);
  7437. buttons = [ 'doTask', 'undoTask', 'verifyTask', 'getKey' ];
  7438. static test() {
  7439. return window.location.host === 'freeanywhere.net';
  7440. }
  7441. async init() {
  7442. try {
  7443. const logStatus = scripts_echoLog({
  7444. text: i18n('initing')
  7445. });
  7446. debug('检测登录按钮');
  7447. if ($('div.header__login a[href*=logout]').length === 0) {
  7448. window.open('https://freeanywhere.net/game.php?steam_login', '_self');
  7449. logStatus.warning(i18n('needLogin'));
  7450. return false;
  7451. }
  7452. debug('检测是否为登录页面');
  7453. if (window.location.href.includes('/login')) {
  7454. logStatus.warning(i18n('needLogin'));
  7455. return false;
  7456. }
  7457. this.initialized = true;
  7458. logStatus.success();
  7459. return true;
  7460. } catch (error) {
  7461. throwError(error, 'Freeanywhere.init');
  7462. return false;
  7463. }
  7464. }
  7465. async classifyTask(action) {
  7466. try {
  7467. const logStatus = scripts_echoLog({
  7468. text: i18n('getTasksInfo')
  7469. });
  7470. if (action === 'undo') {
  7471. this.socialTasks = GM_getValue(`fawTasks-${this.giveawayId}`)?.tasks || JSON.parse(defaultTasks);
  7472. }
  7473. const tasks = $('div.game__content-tasks__task').map((index, element) => ({
  7474. id: $(element).attr('data-id'),
  7475. social: $(element).find('div.task-img img').attr('alt'),
  7476. link: $(element).find('div.task-link a').attr('href'),
  7477. title: $(element).find('div.task-link').text().trim(),
  7478. type: $(element).attr('data-type'),
  7479. isSuccess: $(element).hasClass('done')
  7480. })).toArray();
  7481. if (tasks.length === 0) {
  7482. logStatus.success();
  7483. return false;
  7484. }
  7485. if (action === 'verify') {
  7486. this.tasks = [];
  7487. }
  7488. for (const task of tasks) {
  7489. debug('任务分类', task);
  7490. const {
  7491. id,
  7492. social,
  7493. title,
  7494. type,
  7495. link,
  7496. isSuccess
  7497. } = task;
  7498. const taskInfo = {
  7499. id: id,
  7500. title: title,
  7501. social: social,
  7502. type: type
  7503. };
  7504. if (action === 'verify' && !isSuccess) {
  7505. this.tasks.push(taskInfo);
  7506. continue;
  7507. }
  7508. switch (type) {
  7509. case 'steam_account_verify':
  7510. break;
  7511.  
  7512. case 'steam_game_wishlist':
  7513. if (action === 'undo' && link) {
  7514. this.socialTasks.steam.wishlistLinks.push(link);
  7515. }
  7516. if (action === 'do' && !isSuccess && link) {
  7517. this.undoneTasks.steam.wishlistLinks.push(link);
  7518. }
  7519. break;
  7520.  
  7521. case 'steam_group_sub':
  7522. if (action === 'undo' && link) {
  7523. this.socialTasks.steam.groupLinks.push(link);
  7524. }
  7525. if (action === 'do' && !isSuccess && link) {
  7526. this.undoneTasks.steam.groupLinks.push(link);
  7527. }
  7528. break;
  7529.  
  7530. case 'site_visit':
  7531. if (action === 'do' && !isSuccess) {
  7532. this.undoneTasks.extra.website.push(`id=${id}&type=${type}&task=true`);
  7533. }
  7534. break;
  7535.  
  7536. case 'vk_community_sub':
  7537. if (action === 'undo' && link) {
  7538. this.socialTasks.vk.nameLinks.push(link);
  7539. }
  7540. if (action === 'do' && !isSuccess && link) {
  7541. this.undoneTasks.vk.nameLinks.push(link);
  7542. }
  7543. break;
  7544.  
  7545. case 'vk_post_like':
  7546. if (action === 'undo' && link) {
  7547. this.socialTasks.vk.nameLinks.push(`${link}&action=like`);
  7548. }
  7549. if (action === 'do' && !isSuccess && link) {
  7550. this.undoneTasks.vk.nameLinks.push(`${link}&action=like`);
  7551. }
  7552. break;
  7553.  
  7554. case 'discord_server_sub':
  7555. if (action === 'undo' && link) {
  7556. this.socialTasks.discord.serverLinks.push(link);
  7557. }
  7558. if (action === 'do' && !isSuccess && link) {
  7559. this.undoneTasks.discord.serverLinks.push(link);
  7560. }
  7561. break;
  7562.  
  7563. case 'telegram_channel_sub':
  7564. scripts_echoLog({}).warning(`${i18n('tgTaskNotice')}`);
  7565. break;
  7566.  
  7567. case 'none':
  7568. scripts_echoLog({}).warning(`${i18n('notConnect')}`);
  7569. break;
  7570.  
  7571. default:
  7572. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${type}`);
  7573. break;
  7574. }
  7575. }
  7576. logStatus.success();
  7577. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7578. this.socialTasks = this.uniqueTasks(this.socialTasks);
  7579. if (window.DEBUG) {
  7580. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7581. }
  7582. GM_setValue(`fawTasks-${this.giveawayId}`, {
  7583. tasks: this.socialTasks,
  7584. time: new Date().getTime()
  7585. });
  7586. return true;
  7587. } catch (error) {
  7588. throwError(error, 'Freeanywhere.classifyTask');
  7589. return false;
  7590. }
  7591. }
  7592. async verifyTask() {
  7593. try {
  7594. if (!this.initialized && !this.init()) {
  7595. debug('未初始化');
  7596. return false;
  7597. }
  7598. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  7599. debug('任务列表为空', this.tasks);
  7600. return false;
  7601. }
  7602. const pro = [];
  7603. for (const task of this.tasks) {
  7604. pro.push(this.#verify(task));
  7605. await delay(1e3);
  7606. }
  7607. await Promise.all(pro);
  7608. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7609. return !!await this.getKey(true);
  7610. } catch (error) {
  7611. throwError(error, 'Freeanywhere.verifyTask');
  7612. return false;
  7613. }
  7614. }
  7615. async extraDoTask({
  7616. website
  7617. }) {
  7618. try {
  7619. const pro = [];
  7620. for (const link of website) {
  7621. pro.push(this.#doVisitWebsite(link));
  7622. }
  7623. return Promise.all(pro).then(() => true);
  7624. } catch (error) {
  7625. throwError(error, 'FreeAnyWhere.extraDoTask');
  7626. return false;
  7627. }
  7628. }
  7629. async #doVisitWebsite(link) {
  7630. try {
  7631. const logStatus = scripts_echoLog({
  7632. text: i18n('visitingLink')
  7633. });
  7634. const {
  7635. result,
  7636. statusText,
  7637. status
  7638. } = await tools_httpRequest({
  7639. url: 'https://freeanywhere.net/php/task_site_visit_done.php',
  7640. method: 'POST',
  7641. headers: {
  7642. 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  7643. },
  7644. data: link
  7645. });
  7646. if (result === 'Success') {
  7647. logStatus.success();
  7648. return true;
  7649. }
  7650. logStatus.error(`${result}:${statusText}(${status})`);
  7651. return false;
  7652. } catch (error) {
  7653. throwError(error, 'FreeAnyWhere.doVisitWebsite');
  7654. return false;
  7655. }
  7656. }
  7657. async getKey(initialized) {
  7658. try {
  7659. if (!initialized && !this.initialized && !this.init()) {
  7660. debug('未初始化');
  7661. return false;
  7662. }
  7663. const logStatus = scripts_echoLog({
  7664. text: i18n('gettingKey')
  7665. });
  7666. const {
  7667. result,
  7668. statusText,
  7669. status,
  7670. data
  7671. } = await tools_httpRequest({
  7672. url: 'https://freeanywhere.net/php/user_get_key.php',
  7673. method: 'POST'
  7674. });
  7675. if (result === 'Success') {
  7676. if (data?.responseText.indexOf('bad') !== -1 || data?.responseText.length > 50) {
  7677. logStatus.error(data?.responseText);
  7678. return false;
  7679. }
  7680. logStatus.success();
  7681. scripts_echoLog({}).success(data.responseText);
  7682. return data.responseText;
  7683. }
  7684. logStatus.error(`${result}:${statusText}(${status})`);
  7685. return false;
  7686. } catch (error) {
  7687. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7688. return false;
  7689. }
  7690. }
  7691. async #verify(task) {
  7692. try {
  7693. const logStatus = scripts_echoLog({
  7694. html: `<li>${i18n('verifyingTask')}${task.title.trim()}...<font></font></li>`
  7695. });
  7696. const {
  7697. result,
  7698. statusText,
  7699. status,
  7700. data
  7701. } = await tools_httpRequest({
  7702. url: 'https://freeanywhere.net/php/user_task_update.php',
  7703. method: 'POST',
  7704. headers: {
  7705. 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  7706. },
  7707. data: `id=${task.id}&type=${task.type}`
  7708. });
  7709. if (result === 'Success') {
  7710. if (data?.responseText.trim() === 'good') {
  7711. logStatus.success();
  7712. return true;
  7713. }
  7714. debug('任务验证结果', data?.response);
  7715. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7716. return false;
  7717. }
  7718. logStatus.error(`${result}:${statusText}(${status})`);
  7719. return false;
  7720. } catch (error) {
  7721. throwError(error, 'Freeanywhere.verify');
  7722. return false;
  7723. }
  7724. }
  7725. }
  7726. const Freeanywhere = FreeAnyWhere;
  7727. const Giveawaysu_defaultTasks = {
  7728. steam: {
  7729. groupLinks: [],
  7730. wishlistLinks: [],
  7731. curatorLinks: [],
  7732. curatorLikeLinks: [],
  7733. followLinks: [],
  7734. forumLinks: [],
  7735. announcementLinks: [],
  7736. workshopVoteLinks: [],
  7737. playtestLinks: []
  7738. },
  7739. discord: {
  7740. serverLinks: []
  7741. },
  7742. instagram: {
  7743. userLinks: []
  7744. },
  7745. vk: {
  7746. nameLinks: []
  7747. },
  7748. twitch: {
  7749. channelLinks: []
  7750. },
  7751. reddit: {
  7752. redditLinks: []
  7753. },
  7754. youtube: {
  7755. channelLinks: [],
  7756. likeLinks: []
  7757. },
  7758. twitter: {
  7759. userLinks: [],
  7760. retweetLinks: []
  7761. }
  7762. };
  7763. class GiveawaySu extends website_Website {
  7764. name = 'GiveawaySu';
  7765. socialTasks = Giveawaysu_defaultTasks;
  7766. undoneTasks = Giveawaysu_defaultTasks;
  7767. buttons = [ 'doTask', 'undoTask' ];
  7768. static test() {
  7769. return /^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(window.location.href);
  7770. }
  7771. async after() {
  7772. try {
  7773. if (!this.#checkLogin()) {
  7774. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7775. }
  7776. if (!await this.#checkLeftKey()) {
  7777. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7778. }
  7779. scripts_echoLog({}).warning(i18n('gsNotice'));
  7780. } catch (error) {
  7781. throwError(error, 'Giveawaysu.after');
  7782. }
  7783. }
  7784. init() {
  7785. try {
  7786. const logStatus = scripts_echoLog({
  7787. text: i18n('initing')
  7788. });
  7789. if ($('a.steam-login').length > 0) {
  7790. window.open('/steam/redirect', '_self');
  7791. logStatus.warning(i18n('needLogin'));
  7792. return false;
  7793. }
  7794. if (!this.#getGiveawayId()) {
  7795. return false;
  7796. }
  7797. this.initialized = true;
  7798. logStatus.success();
  7799. return true;
  7800. } catch (error) {
  7801. throwError(error, 'Giveawaysu.init');
  7802. return false;
  7803. }
  7804. }
  7805. async classifyTask(action) {
  7806. try {
  7807. const logStatus = scripts_echoLog({
  7808. text: i18n('getTasksInfo')
  7809. });
  7810. if (action === 'undo') {
  7811. this.socialTasks = GM_getValue(`gasTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  7812. return true;
  7813. }
  7814. const pro = [];
  7815. const tasks = $('#actions tr');
  7816. if ($('div.bind-discord').is(':visible')) {
  7817. $('div.bind-discord a')[0].click();
  7818. }
  7819. if ($('div.bind-twitch').is(':visible')) {
  7820. $('div.bind-twitch a')[0].click();
  7821. }
  7822. for (const task of tasks) {
  7823. pro.push(new Promise(resolve => {
  7824. const td = $(task).find('td:not(".hidden")');
  7825. const colorfulTask = td.eq(1).find('a:not([data-trigger="link"])');
  7826. const colorlessTask = td.eq(2).find('a:not([data-trigger="link"])');
  7827. const taskDes = colorfulTask.length > 0 ? colorfulTask : colorlessTask;
  7828. const taskIcon = td.eq(0).find('i').attr('class') || '';
  7829. const taskName = taskDes.text().trim();
  7830. if (taskIcon.includes('ban') || /disable adblock/gi.test(taskName)) {
  7831. return resolve(true);
  7832. }
  7833. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  7834. if (!taskLink) {
  7835. return resolve(false);
  7836. }
  7837. if (taskIcon.includes('steam') && /join/gi.test(taskName)) {
  7838. this.undoneTasks.steam.groupLinks.push(taskLink);
  7839. } else if (/like.*announcement/gi.test(taskName)) {
  7840. this.undoneTasks.steam.announcementLinks.push(taskLink);
  7841. } else if (/(follow|subscribe).*curator/gim.test(taskName) && /^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  7842. this.undoneTasks.steam.curatorLinks.push(taskLink);
  7843. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  7844. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  7845. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  7846. this.undoneTasks.steam.forumLinks.push(taskLink);
  7847. } else if (taskIcon.includes('thumbs-up') && /^https?:\/\/steamcommunity\.com\/sharedfiles\/filedetails\/\?id=[\d]+/.test(taskLink)) {
  7848. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7849. } else if (taskIcon.includes('plus') && /request.*playtest/gim.test(taskName)) {
  7850. this.undoneTasks.steam.playtestLinks.push(taskLink);
  7851. } else if (taskIcon.includes('discord') || /join.*discord/gim.test(taskName)) {
  7852. this.undoneTasks.discord.serverLinks.push(taskLink);
  7853. } else if (taskIcon.includes('instagram') || /follow.*instagram/gim.test(taskName)) {
  7854. this.undoneTasks.instagram.userLinks.push(taskLink);
  7855. } else if (taskIcon.includes('twitch') || /follow.*twitch.*channel/gim.test(taskName)) {
  7856. this.undoneTasks.twitch.channelLinks.push(taskLink);
  7857. } else if (taskIcon.includes('reddit') || /subscribe.*subreddit/gim.test(taskName) || /follow.*reddit/gim.test(taskName)) {
  7858. this.undoneTasks.reddit.redditLinks.push(taskLink);
  7859. } else if (/watch.*art/gim.test(taskName)) {
  7860. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  7861. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  7862. this.undoneTasks.youtube.channelLinks.push(taskLink);
  7863. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  7864. this.undoneTasks.youtube.likeLinks.push(taskLink);
  7865. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  7866. this.undoneTasks.vk.nameLinks.push(taskLink);
  7867. } else {
  7868. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  7869. if (/wishlist.*game|add.*wishlist/gim.test(taskName)) {
  7870. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  7871. }
  7872. if (/follow.*button/gim.test(taskName)) {
  7873. this.undoneTasks.steam.followLinks.push(taskLink);
  7874. }
  7875. }
  7876. }
  7877. resolve(true);
  7878. }).catch(error => {
  7879. throwError(error, 'Giveawaysu.classifyTask->getRedirectLink');
  7880. return false;
  7881. });
  7882. }));
  7883. }
  7884. await Promise.all(pro);
  7885. logStatus.success();
  7886. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7887. this.socialTasks = this.undoneTasks;
  7888. if (window.DEBUG) {
  7889. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7890. }
  7891. GM_setValue(`gasTasks-${this.giveawayId}`, {
  7892. tasks: this.socialTasks,
  7893. time: new Date().getTime()
  7894. });
  7895. return true;
  7896. } catch (error) {
  7897. throwError(error, 'Giveawaysu.classifyTask');
  7898. return false;
  7899. }
  7900. }
  7901. #checkLogin() {
  7902. try {
  7903. if (!globalOptions.other.checkLogin) {
  7904. return true;
  7905. }
  7906. if ($('a.steam-login').length > 0) {
  7907. window.open('/steam/redirect', '_self');
  7908. }
  7909. return true;
  7910. } catch (error) {
  7911. throwError(error, 'Giveawaysu.checkLogin');
  7912. return false;
  7913. }
  7914. }
  7915. async #checkLeftKey() {
  7916. try {
  7917. if (!globalOptions.other.checkLeftKey) {
  7918. return true;
  7919. }
  7920. if ($('.giveaway-ended').length > 0 && $('.giveaway-key').length === 0) {
  7921. await external_Swal_default().fire({
  7922. icon: 'warning',
  7923. title: i18n('notice'),
  7924. text: i18n('noKeysLeft'),
  7925. confirmButtonText: i18n('confirm'),
  7926. cancelButtonText: i18n('cancel'),
  7927. showCancelButton: true
  7928. }).then(({
  7929. value
  7930. }) => {
  7931. if (value) {
  7932. window.close();
  7933. }
  7934. });
  7935. }
  7936. return true;
  7937. } catch (error) {
  7938. throwError(error, 'Giveawaysu.checkLeftKey');
  7939. return false;
  7940. }
  7941. }
  7942. #getGiveawayId() {
  7943. try {
  7944. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  7945. if (giveawayId) {
  7946. this.giveawayId = giveawayId;
  7947. return true;
  7948. }
  7949. scripts_echoLog({
  7950. text: i18n('getFailed', 'GiveawayId')
  7951. });
  7952. return false;
  7953. } catch (error) {
  7954. throwError(error, 'Giveawaysu.getGiveawayId');
  7955. return false;
  7956. }
  7957. }
  7958. }
  7959. class Indiedb {
  7960. name = 'Indiedb';
  7961. buttons = [ 'doTask' ];
  7962. static test() {
  7963. return window.location.host === 'www.indiedb.com';
  7964. }
  7965. async after() {
  7966. try {
  7967. if (!this.#checkLogin()) {
  7968. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7969. }
  7970. if (!await this.#checkLeftKey()) {
  7971. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7972. }
  7973. } catch (error) {
  7974. throwError(error, 'Indiedb.after');
  7975. }
  7976. }
  7977. async doTask() {
  7978. try {
  7979. if (!await this.#join()) {
  7980. return false;
  7981. }
  7982. return await this.#do();
  7983. } catch (error) {
  7984. throwError(error, 'Indiedb.doTask');
  7985. return false;
  7986. }
  7987. }
  7988. async #join() {
  7989. try {
  7990. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  7991. scripts_echoLog({}).error(i18n('needLogin'));
  7992. return false;
  7993. }
  7994. const currentoption = $('a.buttonenter.buttongiveaway');
  7995. if (/join giveaway/gim.test(currentoption.text())) {
  7996. const logStatus = scripts_echoLog({
  7997. text: `${i18n('joiningGiveaway')}...`
  7998. });
  7999. const {
  8000. result,
  8001. statusText,
  8002. status,
  8003. data
  8004. } = await tools_httpRequest({
  8005. url: currentoption.attr('href'),
  8006. method: 'POST',
  8007. data: 'ajax=t',
  8008. dataType: 'json',
  8009. headers: {
  8010. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  8011. Accept: 'application/json, text/javascript, */*; q=0.01',
  8012. Origin: window.location.origin,
  8013. referer: window.location.href
  8014. }
  8015. });
  8016. if (result === 'Success') {
  8017. if (data?.status === 200) {
  8018. if (data.response?.success) {
  8019. currentoption.addClass('buttonentered').text('Success - Giveaway joined');
  8020. $('#giveawaysjoined').slideDown();
  8021. $('#giveawaysrecommend').slideDown();
  8022. logStatus.success(`Success${data.response?.text ? `:${data.response?.text}` : ''}`);
  8023. return true;
  8024. }
  8025. logStatus.error(`Error${data.response?.text ? `:${data.response?.text}` : ''}`);
  8026. return false;
  8027. }
  8028. if (await this.#join2()) {
  8029. logStatus.success('Success');
  8030. return true;
  8031. }
  8032. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  8033. return false;
  8034. }
  8035. logStatus.error(`${result}:${statusText}(${status})`);
  8036. return false;
  8037. } else if (/success/gim.test($('a.buttonenter.buttongiveaway').text())) {
  8038. return true;
  8039. }
  8040. scripts_echoLog({}).warning(i18n('needJoinGiveaway'));
  8041. return false;
  8042. } catch (error) {
  8043. throwError(error, 'Indiedb.join');
  8044. return false;
  8045. }
  8046. }
  8047. async #join2() {
  8048. try {
  8049. return await new Promise(resolve => {
  8050. const targetNode = document.getElementById('giveawaysjoined');
  8051. const config = {
  8052. attributes: true
  8053. };
  8054. const observer = new MutationObserver(() => {
  8055. if ($('#giveawaysjoined').is(':visible')) {
  8056. resolve(true);
  8057. observer.disconnect();
  8058. }
  8059. });
  8060. observer.observe(targetNode, config);
  8061. $('a.buttonenter.buttongiveaway')[0]?.click();
  8062. setTimeout(() => {
  8063. resolve(false);
  8064. observer.disconnect();
  8065. }, 3e4);
  8066. });
  8067. } catch (error) {
  8068. throwError(error, 'Indiedb.join2');
  8069. return false;
  8070. }
  8071. }
  8072. async #do() {
  8073. try {
  8074. const id = $('script').map((index, script) => {
  8075. if (/\$\(document\)/gim.test(script.innerHTML)) {
  8076. return [ script.innerHTML.match(/"\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0], script.innerHTML.match(/"\/newsletter\/ajax\/subscribeprofile\/optin\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0] ];
  8077. }
  8078. return null;
  8079. });
  8080. if (id.length === 2) {
  8081. const pro = [];
  8082. const tasks = $('#giveawaysjoined a[class*=promo]');
  8083. for (const task of tasks) {
  8084. const promo = $(task);
  8085. if (!promo.hasClass('buttonentered')) {
  8086. const status = scripts_echoLog({
  8087. text: `${i18n('doing')}:${promo.parents('p').text()}...`
  8088. });
  8089. if (/facebookpromo|twitterpromo|visitpromo/gim.test(task.className)) {
  8090. let text = '';
  8091. if (promo.hasClass('facebookpromo')) {
  8092. text = 'facebookpromo';
  8093. } else if (promo.hasClass('twitterpromo')) {
  8094. text = 'twitterpromo';
  8095. } else {
  8096. text = 'visitpromo';
  8097. }
  8098. pro.push(new Promise(resolve => {
  8099. $.ajax({
  8100. type: 'POST',
  8101. url: urlPath(`/giveaways/ajax/${text}/${id[0]}`),
  8102. timeout: 6e4,
  8103. dataType: 'json',
  8104. data: {
  8105. ajax: 't'
  8106. },
  8107. error(response, error, exception) {
  8108. if (window.DEBUG) {
  8109. console.log('%cAuto-Task[Debug]:', 'color:red', {
  8110. response: response,
  8111. error: error,
  8112. exception: exception
  8113. });
  8114. }
  8115. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  8116. resolve(true);
  8117. },
  8118. success(response) {
  8119. if (response.success) {
  8120. status.success(`Success:${response.text}`);
  8121. promo.addClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  8122. resolve(true);
  8123. } else {
  8124. status.error(`Error:${response.text}`);
  8125. resolve(true);
  8126. }
  8127. }
  8128. });
  8129. }));
  8130. } else if (promo.hasClass('emailoptinpromo')) {
  8131. pro.push(new Promise(resolve => {
  8132. $.ajax({
  8133. type: 'POST',
  8134. url: urlPath(`/newsletter/ajax/subscribeprofile/optin/${id[1]}`),
  8135. timeout: 6e4,
  8136. dataType: 'json',
  8137. data: {
  8138. ajax: 't',
  8139. emailsystoggle: 4
  8140. },
  8141. error(response, error, exception) {
  8142. if (window.DEBUG) {
  8143. console.log('%cAuto-Task[Debug]:', 'color:red', {
  8144. response: response,
  8145. error: error,
  8146. exception: exception
  8147. });
  8148. }
  8149. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  8150. resolve(true);
  8151. },
  8152. success(response) {
  8153. if (response.success) {
  8154. status.success(`Success:${response.text}`);
  8155. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  8156. resolve(true);
  8157. } else {
  8158. status.error(`Error:${response.text}`);
  8159. resolve(true);
  8160. }
  8161. }
  8162. });
  8163. }));
  8164. } else if (promo.hasClass('watchingpromo')) {
  8165. pro.push(new Promise(resolve => {
  8166. const data = getUrlQuery(promo.attr('href'));
  8167. data.ajax = 't';
  8168. $.ajax({
  8169. type: 'POST',
  8170. url: urlPath(promo.attr('href')?.split(/[?#]/)[0]),
  8171. timeout: 6e4,
  8172. dataType: 'json',
  8173. data: data,
  8174. error(response, error, exception) {
  8175. if (window.DEBUG) {
  8176. console.log('%cAuto-Task[Debug]:', 'color:red', {
  8177. response: response,
  8178. error: error,
  8179. exception: exception
  8180. });
  8181. }
  8182. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  8183. resolve(true);
  8184. },
  8185. success(response) {
  8186. if (response.success) {
  8187. status.success(`Success:${response.text}`);
  8188. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  8189. resolve(true);
  8190. } else {
  8191. status.error(`Error:${response.text}`);
  8192. resolve(true);
  8193. }
  8194. }
  8195. });
  8196. }));
  8197. } else if (!/the-challenge-of-adblock/gim.test(promo.attr('href'))) {
  8198. pro.push(new Promise(resolve => {
  8199. $.ajax({
  8200. type: 'POST',
  8201. url: urlPath(promo.attr('href')),
  8202. timeout: 6e4,
  8203. dataType: 'json',
  8204. data: {
  8205. ajax: 't'
  8206. },
  8207. error(response, error, exception) {
  8208. if (window.DEBUG) {
  8209. console.log('%cAuto-Task[Debug]:', 'color:red', {
  8210. response: response,
  8211. error: error,
  8212. exception: exception
  8213. });
  8214. }
  8215. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  8216. resolve(true);
  8217. },
  8218. success(response) {
  8219. if (response.success) {
  8220. status.success(`Success:${response.text}`);
  8221. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  8222. resolve(true);
  8223. } else {
  8224. status.error(`Error:${response.text}`);
  8225. resolve(true);
  8226. }
  8227. }
  8228. });
  8229. }));
  8230. } else {
  8231. status.error(`Error:${i18n('unKnownTaskType')}`);
  8232. }
  8233. }
  8234. }
  8235. await Promise.all(pro);
  8236. scripts_echoLog({}).success(i18n('allTasksComplete'));
  8237. return true;
  8238. }
  8239. scripts_echoLog({}).error(i18n('getFailed', 'TaskId'));
  8240. return false;
  8241. } catch (error) {
  8242. throwError(error, 'Indiedb.classifyTask');
  8243. return false;
  8244. }
  8245. }
  8246. #checkLogin() {
  8247. try {
  8248. if (!globalOptions.other.checkLogin) {
  8249. return true;
  8250. }
  8251. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  8252. window.open('/members/login', '_self');
  8253. }
  8254. return true;
  8255. } catch (error) {
  8256. throwError(error, 'Indiedb.checkLogin');
  8257. return false;
  8258. }
  8259. }
  8260. async #checkLeftKey() {
  8261. try {
  8262. if (!globalOptions.other.checkLeftKey) {
  8263. return true;
  8264. }
  8265. if ($('a.buttonenter:contains("next time"), a.buttonenter:contains("Giveaway is closed")').length > 0) {
  8266. await external_Swal_default().fire({
  8267. icon: 'warning',
  8268. title: i18n('notice'),
  8269. text: i18n('giveawayEnded'),
  8270. confirmButtonText: i18n('confirm'),
  8271. cancelButtonText: i18n('cancel'),
  8272. showCancelButton: true
  8273. }).then(({
  8274. value
  8275. }) => {
  8276. if (value) {
  8277. window.close();
  8278. }
  8279. });
  8280. }
  8281. return true;
  8282. } catch (error) {
  8283. throwError(error, 'Indiedb.checkLeftKey');
  8284. return false;
  8285. }
  8286. }
  8287. }
  8288. const website_Indiedb = Indiedb;
  8289. const Keyhub_defaultTasksTemplate = {
  8290. steam: {
  8291. groupLinks: [],
  8292. officialGroupLinks: [],
  8293. wishlistLinks: [],
  8294. curatorLinks: []
  8295. },
  8296. discord: {
  8297. serverLinks: []
  8298. },
  8299. extra: {
  8300. videoTasks: []
  8301. },
  8302. links: []
  8303. };
  8304. const Keyhub_defaultTasks = JSON.stringify(Keyhub_defaultTasksTemplate);
  8305. class Keyhub extends website_Website {
  8306. name = 'Keyhub';
  8307. socialTasks = JSON.parse(Keyhub_defaultTasks);
  8308. undoneTasks = JSON.parse(Keyhub_defaultTasks);
  8309. buttons = [ 'doTask', 'undoTask' ];
  8310. static test() {
  8311. return window.location.host === 'key-hub.eu';
  8312. }
  8313. async after() {
  8314. try {
  8315. if (!this.#checkLogin()) {
  8316. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8317. }
  8318. if (!await this.#checkLeftKey()) {
  8319. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8320. }
  8321. $('.NSFW').hide();
  8322. } catch (error) {
  8323. throwError(error, 'Keyhub.after');
  8324. }
  8325. }
  8326. init() {
  8327. try {
  8328. const logStatus = scripts_echoLog({
  8329. text: i18n('initing')
  8330. });
  8331. if ($('a[href*="/connect/steam"]').length > 0) {
  8332. window.open('/connect/steam', '_self');
  8333. logStatus.warning(i18n('needLogin'));
  8334. return false;
  8335. }
  8336. if (!this.#getGiveawayId()) {
  8337. return false;
  8338. }
  8339. $('#VPNoverlay').hide();
  8340. $('#mainArticleSection').show();
  8341. this.initialized = true;
  8342. logStatus.success();
  8343. return true;
  8344. } catch (error) {
  8345. throwError(error, 'Keyhub.init');
  8346. return false;
  8347. }
  8348. }
  8349. async classifyTask(action) {
  8350. try {
  8351. const logStatus = scripts_echoLog({
  8352. text: i18n('getTasksInfo')
  8353. });
  8354. if (action === 'undo') {
  8355. this.socialTasks = GM_getValue(`khTasks-${this.giveawayId}`)?.tasks || JSON.parse(Keyhub_defaultTasks);
  8356. }
  8357. const tasks = $('.task:not(".googleads")').filter((index, element) => action === 'do' ? $(element).find('i.fa-check-circle:visible').length === 0 : true).find('a');
  8358. for (const task of tasks) {
  8359. let link = $(task).attr('href');
  8360. const taskDes = $(task).text().trim();
  8361. if (!link) {
  8362. continue;
  8363. }
  8364. if (/\/away\?data=/.test(link) || /steamcommunity\.com\/gid\//.test(link)) {
  8365. link = await getRedirectLink(link) || link;
  8366. }
  8367. if (/https?:\/\/key-hub\.eu\/connect\/discord/.test(link)) {
  8368. GM_openInTab(link, {
  8369. active: true
  8370. });
  8371. } else if (/steamcommunity\.com\/groups\//.test(link)) {
  8372. if (action === 'undo') {
  8373. this.socialTasks.steam.groupLinks.push(link);
  8374. }
  8375. if (action === 'do') {
  8376. this.undoneTasks.steam.groupLinks.push(link);
  8377. }
  8378. } else if (/steamcommunity\.com\/games\/[\d]+/.test(link)) {
  8379. if (action === 'undo') {
  8380. this.socialTasks.steam.officialGroupLinks.push(link);
  8381. }
  8382. if (action === 'do') {
  8383. this.undoneTasks.steam.officialGroupLinks.push(link);
  8384. }
  8385. } else if (/store\.steampowered\.com\/app\//.test(link) && /wishlist/gim.test(taskDes)) {
  8386. if (action === 'undo') {
  8387. this.socialTasks.steam.wishlistLinks.push(link);
  8388. }
  8389. if (action === 'do') {
  8390. this.undoneTasks.steam.wishlistLinks.push(link);
  8391. }
  8392. } else if (/store\.steampowered\.com\/curator\//.test(link)) {
  8393. if (action === 'undo') {
  8394. this.socialTasks.steam.curatorLinks.push(link);
  8395. }
  8396. if (action === 'do') {
  8397. this.undoneTasks.steam.curatorLinks.push(link);
  8398. }
  8399. } else if (/^https?:\/\/discord\.com\/invite\//.test(link)) {
  8400. if (action === 'undo') {
  8401. this.socialTasks.discord.serverLinks.push(link);
  8402. }
  8403. if (action === 'do') {
  8404. this.undoneTasks.discord.serverLinks.push(link);
  8405. }
  8406. } else if (/^javascript:videoTask.+/.test(link)) {
  8407. if (action === 'do') {
  8408. const taskData = link.match(/javascript:videoTask\('.+?','(.+?)'/)?.[1];
  8409. if (taskData) {
  8410. this.undoneTasks.extra.videoTasks.push(taskData);
  8411. }
  8412. }
  8413. } 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 {
  8414. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  8415. }
  8416. }
  8417. logStatus.success();
  8418. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8419. this.socialTasks = this.uniqueTasks(this.socialTasks);
  8420. if (window.DEBUG) {
  8421. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8422. }
  8423. GM_setValue(`khTasks-${this.giveawayId}`, {
  8424. tasks: this.socialTasks,
  8425. time: new Date().getTime()
  8426. });
  8427. return true;
  8428. } catch (error) {
  8429. throwError(error, 'Keyhub.classifyTask');
  8430. return false;
  8431. }
  8432. }
  8433. async #doScriptTask(data) {
  8434. try {
  8435. const logStatus = scripts_echoLog({
  8436. text: i18n('doingKeyhubTask')
  8437. });
  8438. const {
  8439. result,
  8440. statusText,
  8441. status,
  8442. data: response
  8443. } = await tools_httpRequest({
  8444. url: `/away?data=${data}`,
  8445. method: 'GET',
  8446. headers: {
  8447. origin: 'https://key-hub.eu',
  8448. referer: 'https://key-hub.eu/'
  8449. }
  8450. });
  8451. if (result === 'Success') {
  8452. if (response?.status === 200) {
  8453. logStatus.success();
  8454. return true;
  8455. }
  8456. logStatus.error(`Error:${response?.statusText}(${response?.status})`);
  8457. return false;
  8458. }
  8459. logStatus.error(`${result}:${statusText}(${status})`);
  8460. return false;
  8461. } catch (error) {
  8462. throwError(error, 'Keyhub.doScriptTask');
  8463. return false;
  8464. }
  8465. }
  8466. async extraDoTask({
  8467. videoTasks
  8468. }) {
  8469. try {
  8470. const pro = [];
  8471. for (const data of videoTasks) {
  8472. pro.push(this.#doScriptTask(data));
  8473. }
  8474. return Promise.all(pro).then(() => true);
  8475. } catch (error) {
  8476. throwError(error, 'Keyhub.extraDoTask');
  8477. return false;
  8478. }
  8479. }
  8480. #getGiveawayId() {
  8481. try {
  8482. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  8483. if (giveawayId) {
  8484. this.giveawayId = giveawayId;
  8485. return true;
  8486. }
  8487. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  8488. return false;
  8489. } catch (error) {
  8490. throwError(error, 'Keyhub.getGiveawayId');
  8491. return false;
  8492. }
  8493. }
  8494. async #checkLeftKey() {
  8495. try {
  8496. if (!globalOptions.other.checkLeftKey) {
  8497. return true;
  8498. }
  8499. const leftKey = $('#keysleft').text().trim();
  8500. if (leftKey === '0') {
  8501. await external_Swal_default().fire({
  8502. icon: 'warning',
  8503. title: i18n('notice'),
  8504. text: i18n('noKeysLeft'),
  8505. confirmButtonText: i18n('confirm'),
  8506. cancelButtonText: i18n('cancel'),
  8507. showCancelButton: true
  8508. }).then(({
  8509. value
  8510. }) => {
  8511. if (value) {
  8512. window.close();
  8513. }
  8514. });
  8515. }
  8516. return true;
  8517. } catch (error) {
  8518. throwError(error, 'Keyhub.checkLeftKey');
  8519. return false;
  8520. }
  8521. }
  8522. #checkLogin() {
  8523. try {
  8524. if (!globalOptions.other.checkLogin) {
  8525. return true;
  8526. }
  8527. if ($('a[href*="/connect/steam"]').length > 0) {
  8528. window.open('/connect/steam', '_self');
  8529. }
  8530. return true;
  8531. } catch (error) {
  8532. throwError(error, 'Keyhub.checkLogin');
  8533. return false;
  8534. }
  8535. }
  8536. }
  8537. const website_Keyhub = Keyhub;
  8538. const Givekey_defaultTasksTemplate = {
  8539. steam: {
  8540. groupLinks: [],
  8541. wishlistLinks: [],
  8542. curatorLinks: [],
  8543. curatorLikeLinks: []
  8544. },
  8545. twitter: {
  8546. userLinks: []
  8547. },
  8548. vk: {
  8549. nameLinks: []
  8550. },
  8551. discord: {
  8552. serverLinks: []
  8553. }
  8554. };
  8555. const Givekey_defaultTasks = JSON.stringify(Givekey_defaultTasksTemplate);
  8556. class Givekey extends website_Website {
  8557. name = 'Givekey';
  8558. tasks = [];
  8559. socialTasks = JSON.parse(Givekey_defaultTasks);
  8560. undoneTasks = JSON.parse(Givekey_defaultTasks);
  8561. userId;
  8562. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8563. static test() {
  8564. return window.location.host === 'givekey.ru';
  8565. }
  8566. async after() {
  8567. try {
  8568. await new Promise(resolve => {
  8569. const checker = setInterval(() => {
  8570. if ($('#navbarDropdown').length > 0) {
  8571. clearInterval(checker);
  8572. resolve(true);
  8573. }
  8574. }, 500);
  8575. });
  8576. if (!await this.#checkLeftKey()) {
  8577. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8578. }
  8579. } catch (error) {
  8580. throwError(error, 'Givekey.after');
  8581. }
  8582. }
  8583. init() {
  8584. try {
  8585. const logStatus = scripts_echoLog({
  8586. text: i18n('initing')
  8587. });
  8588. if ($('a[href*="/auth/steam"]').length > 0) {
  8589. window.open('/auth/steam', '_self');
  8590. logStatus.warning(i18n('needLogin'));
  8591. return false;
  8592. }
  8593. if (!this.#getGiveawayId()) {
  8594. return false;
  8595. }
  8596. const userId = $('meta[name="user-id"]').attr('content');
  8597. if (!userId) {
  8598. logStatus.error(i18n('getFailed', i18n('userId')));
  8599. return false;
  8600. }
  8601. this.userId = userId;
  8602. this.initialized = true;
  8603. logStatus.success();
  8604. return true;
  8605. } catch (error) {
  8606. throwError(error, 'Givekey.init');
  8607. return false;
  8608. }
  8609. }
  8610. async classifyTask(action) {
  8611. try {
  8612. const logStatus = scripts_echoLog({
  8613. text: i18n('getTasksInfo')
  8614. });
  8615. if (action === 'undo') {
  8616. this.socialTasks = GM_getValue(`gkTasks-${this.giveawayId}`)?.tasks || JSON.parse(Givekey_defaultTasks);
  8617. }
  8618. const tasks = $('.card-body:has("button") .row');
  8619. for (const task of tasks) {
  8620. const taskEle = $(task);
  8621. const isSuccess = /Complete/i.test(taskEle.find('button').text().trim());
  8622. if (isSuccess && action !== 'undo') {
  8623. continue;
  8624. }
  8625. const checkButton = taskEle.find('#task_check');
  8626. const taskId = checkButton.attr('data-id');
  8627. if (taskId) {
  8628. this.tasks.push(taskId);
  8629. }
  8630. if (action === 'verify') {
  8631. continue;
  8632. }
  8633. let href = taskEle.find('a').attr('href') || null;
  8634. const text = taskEle.find('a').text().trim();
  8635. const icon = taskEle.find('i');
  8636. if (!href || !text) {
  8637. continue;
  8638. }
  8639. if (/^https?:\/\/givekey\.ru\/giveaway\/[\d]+\/execution_task/.test(href)) {
  8640. href = await getRedirectLink(href);
  8641. }
  8642. if (!href) {
  8643. continue;
  8644. }
  8645. if (/^https?:\/\/vk\.com\//.test(href)) {
  8646. this.socialTasks.vk.nameLinks.push(href);
  8647. if (action === 'do' && !isSuccess) {
  8648. this.undoneTasks.vk.nameLinks.push(href);
  8649. }
  8650. } else if (/^https?:\/\/steamcommunity\.com\/groups/.test(href)) {
  8651. this.socialTasks.steam.groupLinks.push(href);
  8652. if (action === 'do' && !isSuccess) {
  8653. this.undoneTasks.steam.groupLinks.push(href);
  8654. }
  8655. } else if (/^https?:\/\/store\.steampowered\.com\/app\//.test(href)) {
  8656. this.socialTasks.steam.wishlistLinks.push(href);
  8657. if (action === 'do' && !isSuccess) {
  8658. this.undoneTasks.steam.wishlistLinks.push(href);
  8659. }
  8660. } else if (/Subscribe/gi.test(text) && icon.hasClass('fa-steam-square')) {
  8661. if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(href)) {
  8662. this.socialTasks.steam.curatorLinks.push(href);
  8663. if (action === 'do' && !isSuccess) {
  8664. this.undoneTasks.steam.curatorLinks.push(href);
  8665. }
  8666. } else {
  8667. this.socialTasks.steam.curatorLikeLinks.push(href);
  8668. if (action === 'do' && !isSuccess) {
  8669. this.undoneTasks.steam.curatorLikeLinks.push(href);
  8670. }
  8671. }
  8672. } else if (/^https?:\/\/twitter\.com\//.test(href) && /Subscribe/gi.test(text)) {
  8673. this.socialTasks.twitter.userLinks.push(href);
  8674. if (action === 'do' && !isSuccess) {
  8675. this.undoneTasks.twitter.userLinks.push(href);
  8676. }
  8677. } else if (icon.hasClass('fa-discord') || /^https?:\/\/discord\.com\/invite\//.test(href)) {
  8678. this.socialTasks.discord.serverLinks.push(href);
  8679. if (action === 'do' && !isSuccess) {
  8680. this.undoneTasks.discord.serverLinks.push(href);
  8681. }
  8682. } else {
  8683. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${text}(${href})`);
  8684. }
  8685. }
  8686. logStatus.success();
  8687. this.tasks = unique(this.tasks);
  8688. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8689. this.socialTasks = this.uniqueTasks(this.socialTasks);
  8690. if (window.DEBUG) {
  8691. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8692. }
  8693. GM_setValue(`gkTasks-${this.giveawayId}`, {
  8694. tasks: this.socialTasks,
  8695. time: new Date().getTime()
  8696. });
  8697. return true;
  8698. } catch (error) {
  8699. throwError(error, 'Givekey.classifyTask');
  8700. return false;
  8701. }
  8702. }
  8703. async verifyTask() {
  8704. try {
  8705. if (!this.initialized && !this.init()) {
  8706. return false;
  8707. }
  8708. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  8709. return false;
  8710. }
  8711. scripts_echoLog({}).warning(i18n('giveKeyNoticeBefore'));
  8712. const taskLength = this.tasks.length;
  8713. for (let i = 0; i < taskLength; i++) {
  8714. await this.#verify(this.tasks[i]);
  8715. if (i < taskLength - 1) {
  8716. await delay(15e3);
  8717. }
  8718. }
  8719. scripts_echoLog({}).success(i18n('allTasksComplete'));
  8720. scripts_echoLog({
  8721. html: `<li><font class="warning">${i18n('giveKeyNoticeAfter')}</font></li>`
  8722. });
  8723. return true;
  8724. } catch (error) {
  8725. throwError(error, 'Givekey.verifyTask');
  8726. return false;
  8727. }
  8728. }
  8729. async #verify(task) {
  8730. try {
  8731. const logStatus = scripts_echoLog({
  8732. html: `<li>${i18n('verifyingTask')}${task}...<font></font></li>`
  8733. });
  8734. return await new Promise(resolve => {
  8735. $.ajax({
  8736. url: 'https://givekey.ru/giveaway/task',
  8737. method: 'POST',
  8738. data: `id=${task}&user_id=${this.userId}`,
  8739. dataType: 'json',
  8740. headers: {
  8741. 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  8742. },
  8743. success: data => {
  8744. if (data.btn) {
  8745. $(`button[data-id=${this.userId}]`).html(data.btn);
  8746. }
  8747. if (data.status === 'ok') {
  8748. $(`.task_check_${data.id}`).html(`<button class="btn btn-success mb-2 btn-block" disabled>${data.btn}</button>`);
  8749. logStatus.success();
  8750. resolve(true);
  8751. } else if (data.status === 'end') {
  8752. logStatus.success();
  8753. scripts_echoLog({}).success(data.key);
  8754. resolve(true);
  8755. } else {
  8756. logStatus.error(`Error:${data.msg}`);
  8757. resolve(false);
  8758. }
  8759. },
  8760. error: xhr => {
  8761. logStatus.error(`Error:${xhr.statusText}(${xhr.status})`);
  8762. resolve(false);
  8763. }
  8764. });
  8765. });
  8766. } catch (error) {
  8767. throwError(error, 'Givekey.verify');
  8768. return false;
  8769. }
  8770. }
  8771. #getGiveawayId() {
  8772. try {
  8773. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  8774. if (giveawayId) {
  8775. this.giveawayId = giveawayId;
  8776. return true;
  8777. }
  8778. scripts_echoLog({
  8779. text: i18n('getFailed', 'GiveawayId')
  8780. });
  8781. return false;
  8782. } catch (error) {
  8783. throwError(error, 'Givekey.getGiveawayId');
  8784. return false;
  8785. }
  8786. }
  8787. async #checkLeftKey() {
  8788. try {
  8789. if (!globalOptions.other.checkLeftKey) {
  8790. return true;
  8791. }
  8792. if (!$('#keys_count').text()) {
  8793. await external_Swal_default().fire({
  8794. icon: 'warning',
  8795. title: i18n('notice'),
  8796. text: i18n('noKeysLeft'),
  8797. confirmButtonText: i18n('confirm'),
  8798. cancelButtonText: i18n('cancel'),
  8799. showCancelButton: true
  8800. }).then(({
  8801. value
  8802. }) => {
  8803. if (value) {
  8804. window.close();
  8805. }
  8806. });
  8807. }
  8808. return true;
  8809. } catch (error) {
  8810. throwError(error, 'Givekey.checkLeftKey');
  8811. return false;
  8812. }
  8813. }
  8814. }
  8815. const website_Givekey = Givekey;
  8816. class GiveeClub extends GiveawaySu {
  8817. name = 'GiveeClub';
  8818. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8819. static test() {
  8820. return /^https?:\/\/givee\.club\/.*?\/event\/[\d]+/.test(window.location.href);
  8821. }
  8822. async after() {
  8823. try {
  8824. if (!this.#checkLogin()) {
  8825. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8826. }
  8827. if (!await this.#checkLeftKey()) {
  8828. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8829. }
  8830. } catch (error) {
  8831. throwError(error, 'GiveeClub.after');
  8832. }
  8833. }
  8834. init() {
  8835. try {
  8836. const logStatus = scripts_echoLog({
  8837. text: i18n('initing')
  8838. });
  8839. if (!this.#checkLogin()) {
  8840. logStatus.warning(i18n('needLogin'));
  8841. return false;
  8842. }
  8843. if (!this.#getGiveawayId()) {
  8844. return false;
  8845. }
  8846. this.initialized = true;
  8847. logStatus.success();
  8848. return true;
  8849. } catch (error) {
  8850. throwError(error, 'GiveeClub.init');
  8851. return false;
  8852. }
  8853. }
  8854. async classifyTask(action) {
  8855. try {
  8856. const logStatus = scripts_echoLog({
  8857. text: i18n('getTasksInfo')
  8858. });
  8859. if (action === 'undo') {
  8860. this.socialTasks = GM_getValue(`gcTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  8861. return true;
  8862. }
  8863. this.undoneTasks = Giveawaysu_defaultTasks;
  8864. const pro = [];
  8865. const tasks = $('.event-actions tr');
  8866. for (const task of tasks) {
  8867. pro.push(new Promise(resolve => {
  8868. const taskDes = $(task).find('.event-action-label a');
  8869. const taskIcon = $(task).find('.event-action-icon i').attr('class') || '';
  8870. const taskName = taskDes.text().trim();
  8871. const taskType = $(task).find('button[data-type]')?.attr('data-type');
  8872. const taskFinished = $(task).find('.event-action-buttons .btn-success')?.length;
  8873. if (taskIcon.includes('ban') || /AdBlock/i.test(taskName) || taskIcon.includes('envelope') || taskFinished) {
  8874. return resolve(true);
  8875. }
  8876. getRedirectLink(taskDes.attr('href'), true).then(taskLink => {
  8877. if (!taskLink) {
  8878. return resolve(false);
  8879. }
  8880. if (taskType === 'steam.group.join' && /^https?:\/\/steamcommunity\.com\/groups/.test(taskLink)) {
  8881. this.undoneTasks.steam.groupLinks.push(taskLink);
  8882. } else if (/like.*announcement/gi.test(taskName)) {
  8883. this.undoneTasks.steam.announcementLinks.push(taskLink);
  8884. } else if (taskType === 'steam.game.wishlist' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8885. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  8886. } else if (taskType === 'steam.game.wishlist' && taskDes.attr('data-steam-wishlist-appid')) {
  8887. this.undoneTasks.steam.wishlistLinks.push(`https://store.steampowered.com/app/${taskDes.attr('data-steam-wishlist-appid')}`);
  8888. } else if (taskType === 'steam.game.follow' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  8889. this.undoneTasks.steam.followLinks.push(taskLink);
  8890. } else if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  8891. this.undoneTasks.steam.curatorLinks.push(taskLink);
  8892. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  8893. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  8894. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  8895. this.undoneTasks.steam.forumLinks.push(taskLink);
  8896. } else if (taskIcon.includes('discord')) {
  8897. this.undoneTasks.discord.serverLinks.push(taskLink);
  8898. } else if (taskIcon.includes('instagram')) {
  8899. this.undoneTasks.instagram.userLinks.push(taskLink);
  8900. } else if (taskIcon.includes('twitch')) {
  8901. this.undoneTasks.twitch.channelLinks.push(taskLink);
  8902. } else if (taskIcon.includes('reddit')) {
  8903. this.undoneTasks.reddit.redditLinks.push(taskLink);
  8904. } else if (/watch.*art/gim.test(taskName)) {
  8905. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  8906. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  8907. this.undoneTasks.youtube.channelLinks.push(taskLink);
  8908. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  8909. this.undoneTasks.youtube.likeLinks.push(taskLink);
  8910. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  8911. this.undoneTasks.vk.nameLinks.push(taskLink);
  8912. } else if (taskIcon.includes('twitter')) {
  8913. if (/https?:\/\/(twitter|x)\.com\/[^/]+\/?$/gim.test(taskLink)) {
  8914. this.undoneTasks.twitter.userLinks.push(taskLink);
  8915. } else if (/https?:\/\/(twitter|x)\.com\/[^/]+?\/status\/[\d]+/gim.test(taskLink)) {
  8916. this.undoneTasks.twitter.retweetLinks.push(taskLink);
  8917. }
  8918. } else {
  8919. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  8920. if (/follow.*button/gim.test(taskName)) {
  8921. this.undoneTasks.steam.followLinks.push(taskLink);
  8922. }
  8923. }
  8924. }
  8925. resolve(true);
  8926. }).catch(error => {
  8927. throwError(error, 'GiveeClub.classifyTask->getRedirectLink');
  8928. return false;
  8929. });
  8930. }));
  8931. }
  8932. await Promise.all(pro);
  8933. logStatus.success();
  8934. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8935. this.socialTasks = this.undoneTasks;
  8936. if (window.DEBUG) {
  8937. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8938. }
  8939. GM_setValue(`gcTasks-${this.giveawayId}`, {
  8940. tasks: this.socialTasks,
  8941. time: new Date().getTime()
  8942. });
  8943. return true;
  8944. } catch (error) {
  8945. throwError(error, 'GiveeClub.classifyTask');
  8946. return false;
  8947. }
  8948. }
  8949. async verifyTask() {
  8950. try {
  8951. const logStatus = scripts_echoLog({
  8952. text: i18n('giveeClubVerifyNotice')
  8953. });
  8954. const taskButtons = $('.event-actions tr button').has('i.glyphicon-refresh').not('[data-type="user.adblock"]');
  8955. for (const button of taskButtons) {
  8956. button.click();
  8957. if ($(button).attr('data-type') !== 'steam.game.wishlist') {
  8958. await delay(1e3);
  8959. }
  8960. }
  8961. logStatus.warning(i18n('giveeClubVerifyFinished'));
  8962. return true;
  8963. } catch (error) {
  8964. throwError(error, 'Givekey.verifyTask');
  8965. return false;
  8966. }
  8967. }
  8968. #checkLogin() {
  8969. try {
  8970. if (!globalOptions.other.checkLogin) {
  8971. return true;
  8972. }
  8973. if ($('a[href*="/account/auth"]').length > 0) {
  8974. window.open($('a[href*="/account/auth"]').attr('href'), '_self');
  8975. }
  8976. return true;
  8977. } catch (error) {
  8978. throwError(error, 'GiveeClub.checkLogin');
  8979. return false;
  8980. }
  8981. }
  8982. #getGiveawayId() {
  8983. const giveawayId = window.location.href.match(/\/event\/([\d]+)/)?.[1];
  8984. if (giveawayId) {
  8985. this.giveawayId = giveawayId;
  8986. return true;
  8987. }
  8988. scripts_echoLog({
  8989. text: i18n('getFailed', 'GiveawayId')
  8990. });
  8991. return false;
  8992. }
  8993. async #checkLeftKey() {
  8994. try {
  8995. if (!globalOptions.other.checkLeftKey) {
  8996. return true;
  8997. }
  8998. if ($('.event-ended').length > 0 && $('.event-winner').length === 0) {
  8999. await external_Swal_default().fire({
  9000. icon: 'warning',
  9001. title: i18n('notice'),
  9002. text: i18n('giveawayEnded'),
  9003. confirmButtonText: i18n('confirm'),
  9004. cancelButtonText: i18n('cancel'),
  9005. showCancelButton: true
  9006. }).then(({
  9007. value
  9008. }) => {
  9009. if (value) {
  9010. window.close();
  9011. }
  9012. });
  9013. }
  9014. return true;
  9015. } catch (error) {
  9016. throwError(error, 'Giveawaysu.checkLeftKey');
  9017. return false;
  9018. }
  9019. }
  9020. }
  9021. const website_GiveeClub = GiveeClub;
  9022. const defaultOptions = {
  9023. maxPoint: '99999999'
  9024. };
  9025. class OpiumPulses {
  9026. name = 'OpiumPulses';
  9027. options = {
  9028. ...defaultOptions,
  9029. ...GM_getValue('OpiumPulsesOptions')
  9030. };
  9031. maxPoints = 99999999;
  9032. myPoints = 0;
  9033. buttons = [ 'doFreeTask', 'doPointTask' ];
  9034. static test() {
  9035. return window.location.host === 'www.opiumpulses.com';
  9036. }
  9037. async after() {
  9038. try {
  9039. if (!this.#checkLogin()) {
  9040. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9041. }
  9042. this.maxPoints = parseInt(this.options.maxPoint, 10);
  9043. } catch (error) {
  9044. throwError(error, 'OpiumPulses.after');
  9045. }
  9046. }
  9047. async doFreeTask() {
  9048. try {
  9049. this.#toggleTask('FREE');
  9050. } catch (error) {
  9051. throwError(error, 'OpiumPulses.doFreeTask');
  9052. }
  9053. }
  9054. async doPointTask() {
  9055. try {
  9056. this.myPoints = parseInt($('.page-header__nav-func-user-nav-items.points-items').text().match(/[\d]+/gim)?.[0] || '0', 10);
  9057. this.#toggleTask('points');
  9058. } catch (error) {
  9059. throwError(error, 'OpiumPulses.doPointTask');
  9060. }
  9061. }
  9062. async #toggleTask(type) {
  9063. try {
  9064. const items = $(`.giveaways-page-item:contains('${type}'):not(:contains('ENTERED'))`);
  9065. for (const item of items) {
  9066. const needPoints = parseInt($(item).find('.giveaways-page-item-header-points').text().match(/[\d]+/gim)?.[0] || '999999', 10);
  9067. const name = $(item).find('.giveaways-page-item-footer-name').text().trim();
  9068. if (type === 'points' && needPoints > this.myPoints) {
  9069. scripts_echoLog({}).warning(`${i18n('noPoints')}: ${name}`);
  9070. } else if (type === 'points' && !needPoints) {
  9071. scripts_echoLog({}).warning(`${i18n('getNeedPointsFailed')}: ${name}`);
  9072. } else if (!(type === 'points' && needPoints > this.maxPoints)) {
  9073. const logStatus = scripts_echoLog({
  9074. text: `${i18n('joiningLottery')}<a href="${$(item).find('a.giveaways-page-item-img-btn-more').attr('href')}" target="_blank">${name}</a>...`
  9075. });
  9076. const aElement = $(item).find('a.giveaways-page-item-img-btn-enter:contains(\'enter\')');
  9077. if (aElement?.attr('onclick')?.includes('checkUser')) {
  9078. const giveawayId = aElement.attr('onclick')?.match(/[\d]+/)?.[0];
  9079. if (giveawayId) {
  9080. checkUser(giveawayId);
  9081. }
  9082. }
  9083. if (!aElement.attr('href')) {
  9084. logStatus.error('Error: No "href".');
  9085. continue;
  9086. }
  9087. const {
  9088. result,
  9089. statusText,
  9090. status,
  9091. data
  9092. } = await tools_httpRequest({
  9093. url: aElement.attr('href'),
  9094. method: 'GET'
  9095. });
  9096. if (result === 'Success') {
  9097. const {
  9098. result: result0,
  9099. statusText: statusText0,
  9100. status: status0,
  9101. data: data0
  9102. } = await tools_httpRequest({
  9103. url: data?.finalUrl,
  9104. method: 'GET'
  9105. });
  9106. if (data0?.responseText && /You've entered this giveaway/gim.test(data0.responseText)) {
  9107. logStatus.success();
  9108. const points = data0.responseText.match(/Points:[\s]*?([\d]+)/)?.[1];
  9109. if (type === 'points' && points) {
  9110. this.myPoints = parseInt(points, 10);
  9111. }
  9112. } else if (data0?.responseText && /You're not eligible to enter/gim.test(data0.responseText)) {
  9113. logStatus.error('You\'re not eligible to enter');
  9114. } else {
  9115. logStatus.error(`${result0}:${statusText0}(${status0})`);
  9116. }
  9117. } else {
  9118. logStatus.error(`${result}:${statusText}(${status})`);
  9119. }
  9120. }
  9121. }
  9122. scripts_echoLog({
  9123. text: '-----END-----'
  9124. });
  9125. } catch (error) {
  9126. throwError(error, 'OpiumPulses.toggleTask');
  9127. }
  9128. }
  9129. init() {
  9130. return true;
  9131. }
  9132. classifyTask() {
  9133. return true;
  9134. }
  9135. #checkLogin() {
  9136. try {
  9137. if (!globalOptions.other.checkLogin) {
  9138. return true;
  9139. }
  9140. if ($('a[href*="/site/login"]').length > 1) {
  9141. window.open('/site/login', '_self');
  9142. }
  9143. return true;
  9144. } catch (error) {
  9145. throwError(error, 'OpiumPulses.checkLogin');
  9146. return false;
  9147. }
  9148. }
  9149. }
  9150. const website_OpiumPulses = OpiumPulses;
  9151. const external_dayjs_namespaceObject = dayjs;
  9152. var external_dayjs_default = __webpack_require__.n(external_dayjs_namespaceObject);
  9153. const leftKeyChecker = {
  9154. async classify(link) {
  9155. try {
  9156. if (/^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(link)) {
  9157. return await this.giveawaySu(link);
  9158. }
  9159. if (/^https?:\/\/givee\.club\/[\w]+?\/event\/[\d]+/.test(link)) {
  9160. return await this.giveeClub(link);
  9161. }
  9162. if (/^https?:\/\/gleam\.io\/.+?\/.+/.test(link)) {
  9163. return await this.gleam(link);
  9164. }
  9165. if (/^https?:\/\/www\.indiedb\.com\/giveaways\/.+/.test(link)) {
  9166. return await this.indieDb(link);
  9167. }
  9168. if (/^https?:\/\/key-hub\.eu\/giveaway\/[\d]+/.test(link)) {
  9169. return await this.keyhub(link);
  9170. }
  9171. if (/^https?:\/\/opquests\.com\/quests\/[\d]+/.test(link)) {
  9172. return await this.opquests(link);
  9173. }
  9174. if (/^https?:\/\/itch\.io\/s\/[\d]+?\/.*/.test(link)) {
  9175. return await this.itch(link);
  9176. }
  9177. return false;
  9178. } catch (error) {
  9179. throwError(error, 'leftKeyChecker.classify');
  9180. return false;
  9181. }
  9182. },
  9183. async giveawaySu(link) {
  9184. try {
  9185. const {
  9186. result,
  9187. data
  9188. } = await tools_httpRequest({
  9189. url: link,
  9190. method: 'GET'
  9191. });
  9192. if (result === 'Success' && data?.status === 200) {
  9193. if (data.responseText.includes('class="steam-login"')) {
  9194. return false;
  9195. }
  9196. if (data.responseText.includes('class="giveaway-ended"')) {
  9197. return 'Ended';
  9198. }
  9199. return 'Active';
  9200. }
  9201. return false;
  9202. } catch (error) {
  9203. throwError(error, 'leftKeyChecker.giveawaySu');
  9204. return false;
  9205. }
  9206. },
  9207. async giveeClub(link) {
  9208. try {
  9209. const {
  9210. result,
  9211. data
  9212. } = await tools_httpRequest({
  9213. url: link,
  9214. method: 'GET'
  9215. });
  9216. if (result === 'Success' && data?.status === 200) {
  9217. if (data.responseText.includes('class="event-winner"')) {
  9218. return 'Won';
  9219. }
  9220. if (data.responseText.includes('class="event-ended"')) {
  9221. return 'Ended';
  9222. }
  9223. return 'Active';
  9224. }
  9225. return false;
  9226. } catch (error) {
  9227. throwError(error, 'leftKeyChecker.giveeClub');
  9228. return false;
  9229. }
  9230. },
  9231. async gleam(link) {
  9232. try {
  9233. const {
  9234. result,
  9235. data
  9236. } = await tools_httpRequest({
  9237. url: link,
  9238. method: 'GET'
  9239. });
  9240. if (result === 'Success' && data?.status === 200) {
  9241. if (/incentives&quot;:{&quot;[\d]+?&quot;:\[&quot;.+?&quot;\]/.test(data.responseText)) {
  9242. return 'Won';
  9243. }
  9244. const campaignDiv = data.responseText.match(/<div class='popup-blocks-container'[\w\W]+?'>/)?.[0];
  9245. if (!campaignDiv) {
  9246. return false;
  9247. }
  9248. const campaignString = $(campaignDiv).attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  9249. if (!campaignString) {
  9250. return false;
  9251. }
  9252. const {
  9253. campaign
  9254. } = JSON.parse(campaignString);
  9255. if (campaign.banned) {
  9256. return 'Banned';
  9257. }
  9258. if (campaign.finished) {
  9259. return 'Ended';
  9260. }
  9261. if (campaign.paused) {
  9262. return 'Paused';
  9263. }
  9264. if (new Date().getTime() < campaign.starts_at * 1e3) {
  9265. return 'NotStart';
  9266. }
  9267. return 'Active';
  9268. }
  9269. return false;
  9270. } catch (error) {
  9271. throwError(error, 'leftKeyChecker.gleam');
  9272. return false;
  9273. }
  9274. },
  9275. async indieDb(link) {
  9276. try {
  9277. const {
  9278. result,
  9279. data
  9280. } = await tools_httpRequest({
  9281. url: link,
  9282. method: 'GET'
  9283. });
  9284. if (result === 'Success' && data?.status === 200) {
  9285. if (data.responseText.includes('Congrats you WON')) {
  9286. return 'Won';
  9287. }
  9288. if (data.responseText.includes('Giveaway is closed') || data.responseText.includes('next time')) {
  9289. return 'Ended';
  9290. }
  9291. return 'Active';
  9292. }
  9293. return false;
  9294. } catch (error) {
  9295. throwError(error, 'leftKeyChecker.indieDb');
  9296. return false;
  9297. }
  9298. },
  9299. async keyhub(link) {
  9300. try {
  9301. const {
  9302. result,
  9303. data
  9304. } = await tools_httpRequest({
  9305. url: link,
  9306. method: 'GET'
  9307. });
  9308. if (result === 'Success' && data?.status === 200) {
  9309. const keysleft = data.responseText.match(/<span id="keysleft">([\d]+?)<\/span>/)?.[1];
  9310. if (!keysleft) {
  9311. return false;
  9312. }
  9313. if (keysleft === '0') {
  9314. return 'Ended';
  9315. }
  9316. return `Active(${keysleft})`;
  9317. }
  9318. return false;
  9319. } catch (error) {
  9320. throwError(error, 'leftKeyChecker.keyhub');
  9321. return false;
  9322. }
  9323. },
  9324. async opquests(link) {
  9325. try {
  9326. const {
  9327. result,
  9328. data
  9329. } = await tools_httpRequest({
  9330. url: link,
  9331. method: 'GET'
  9332. });
  9333. if (result === 'Success' && data?.status === 200) {
  9334. const keysleft = data.responseText.match(/<div class="">[\s]*?([\d]+?)[\s]*?of/)?.[1];
  9335. if (!keysleft) {
  9336. return false;
  9337. }
  9338. if (keysleft === '0') {
  9339. return 'Ended';
  9340. }
  9341. return `Active(${keysleft})`;
  9342. } else if (data?.status === 404) {
  9343. return 'Ended';
  9344. }
  9345. return false;
  9346. } catch (error) {
  9347. throwError(error, 'leftKeyChecker.opquests');
  9348. return false;
  9349. }
  9350. },
  9351. async itch(link) {
  9352. try {
  9353. const {
  9354. result,
  9355. data
  9356. } = await tools_httpRequest({
  9357. url: link,
  9358. method: 'GET'
  9359. });
  9360. if (result === 'Success' && data?.status === 200) {
  9361. const endDate = data.responseText.match(/{"start_date":"[0-9A-Z-:]+?".*?"end_date":"([0-9A-Z-:]+?)".*?}/)?.[1];
  9362. if (!endDate) {
  9363. return false;
  9364. }
  9365. if (new Date().getTime() > new Date(endDate).getTime()) {
  9366. return 'Ended';
  9367. }
  9368. return `Active(${external_dayjs_default()(endDate).format('YYYY-MM-DD HH:mm:ss')})`;
  9369. }
  9370. return false;
  9371. } catch (error) {
  9372. throwError(error, 'leftKeyChecker.itch');
  9373. return false;
  9374. }
  9375. }
  9376. };
  9377. const website_leftKeyChecker = leftKeyChecker;
  9378. const Keylol_defaultTasksTemplate = {
  9379. steam: {
  9380. groupLinks: [],
  9381. wishlistLinks: [],
  9382. curatorLinks: [],
  9383. curatorLikeLinks: [],
  9384. followLinks: [],
  9385. forumLinks: [],
  9386. announcementLinks: [],
  9387. workshopVoteLinks: [],
  9388. licenseLinks: []
  9389. },
  9390. discord: {
  9391. serverLinks: []
  9392. },
  9393. instagram: {
  9394. userLinks: []
  9395. },
  9396. vk: {
  9397. nameLinks: []
  9398. },
  9399. twitch: {
  9400. channelLinks: []
  9401. },
  9402. reddit: {
  9403. redditLinks: []
  9404. },
  9405. twitter: {
  9406. userLinks: [],
  9407. retweetLinks: []
  9408. },
  9409. youtube: {
  9410. channelLinks: [],
  9411. likeLinks: []
  9412. }
  9413. };
  9414. const Keylol_defaultTasks = JSON.stringify(Keylol_defaultTasksTemplate);
  9415. class Keylol extends website_Website {
  9416. name = 'Keylol';
  9417. socialTasks = JSON.parse(Keylol_defaultTasks);
  9418. undoneTasks = JSON.parse(Keylol_defaultTasks);
  9419. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect' ];
  9420. static test() {
  9421. 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'));
  9422. }
  9423. init() {
  9424. return true;
  9425. }
  9426. after() {
  9427. try {
  9428. const selector = this.name === 'Keylol' ? '#postlist>div[id^="post_"]:first' : 'div.container';
  9429. const mainPost = $(selector);
  9430. const discordLinks = mainPost.find('a[href*="discord.com"]:visible');
  9431. const redditLinks = mainPost.find('a[href*="reddit.com"]:visible');
  9432. const insLinks = mainPost.find('a[href*="instagram.com"]:visible');
  9433. const twitterLinks = mainPost.find('a[href*="twitter.com"]:visible,a[href*="x.com"]:visible');
  9434. const twitchLinks = mainPost.find('a[href*="twitch.tv"]:visible');
  9435. const vkLinks = mainPost.find('a[href*="vk.com"]:visible');
  9436. const steamStoreLinks = mainPost.find('a[href*="store.steampowered.com"]:visible');
  9437. const steamCommunityLinks = mainPost.find('a[href*="steamcommunity.com"]:visible');
  9438. const ytbLinks = mainPost.find('a[href*="youtube.com"]:visible');
  9439. if (discordLinks.length > 0) {
  9440. for (const discordLink of discordLinks) {
  9441. const link = $(discordLink).attr('href');
  9442. if (!(link && /^https?:\/\/discord\.com\/invite\/.+/.test(link))) {
  9443. continue;
  9444. }
  9445. this.#addBtn(discordLink, 'discord', 'serverLinks', link);
  9446. }
  9447. }
  9448. if (redditLinks.length > 0) {
  9449. for (const redditLink of redditLinks) {
  9450. const link = $(redditLink).attr('href');
  9451. if (!(link && /^https?:\/\/www\.reddit\.com\/(r|user)\/.+/.test(link))) {
  9452. continue;
  9453. }
  9454. this.#addBtn(redditLink, 'reddit', 'redditLinks', link);
  9455. }
  9456. }
  9457. if (insLinks.length > 0) {
  9458. for (const insLink of insLinks) {
  9459. const link = $(insLink).attr('href');
  9460. if (!(link && /^https:\/\/www\.instagram\.com\/.+/.test(link))) {
  9461. continue;
  9462. }
  9463. this.#addBtn(insLink, 'instagram', 'userLinks', link);
  9464. }
  9465. }
  9466. if (twitterLinks.length > 0) {
  9467. for (const twitterLink of twitterLinks) {
  9468. const link = $(twitterLink).attr('href');
  9469. if (!(link && /^https:\/\/twitter\.com\/.+/.test(link))) {
  9470. continue;
  9471. }
  9472. if (/https:\/\/twitter\.com\/.*?\/status\/[\d]+/.test(link)) {
  9473. this.#addBtn(twitterLink, 'twitter', 'retweetLinks', link);
  9474. } else {
  9475. this.#addBtn(twitterLink, 'twitter', 'userLinks', link);
  9476. }
  9477. }
  9478. }
  9479. if (twitchLinks.length > 0) {
  9480. for (const twitchLink of twitchLinks) {
  9481. const link = $(twitchLink).attr('href');
  9482. if (!(link && /^https:\/\/(www\.)?twitch\.tv\/.+/.test(link))) {
  9483. continue;
  9484. }
  9485. this.#addBtn(twitchLink, 'twitch', 'channelLinks', link);
  9486. }
  9487. }
  9488. if (vkLinks.length > 0) {
  9489. for (const vkLink of vkLinks) {
  9490. const link = $(vkLink).attr('href');
  9491. if (!(link && /^https:\/\/vk\.com\/.+/.test(link))) {
  9492. continue;
  9493. }
  9494. this.#addBtn(vkLink, 'vk', 'nameLinks', link);
  9495. }
  9496. }
  9497. if (steamStoreLinks.length > 0) {
  9498. for (const steamStoreLink of steamStoreLinks) {
  9499. const link = $(steamStoreLink).attr('href');
  9500. if (!link) {
  9501. continue;
  9502. }
  9503. if (/curator\/[\d]+/.test(link)) {
  9504. this.#addBtn(steamStoreLink, 'steam', 'curatorLinks', link);
  9505. } else if (/(publisher|developer|franchise)\/.+/.test(link)) {
  9506. this.#addBtn(steamStoreLink, 'steam', 'curatorLikeLinks', link);
  9507. } else if (/news(hub)?\/app\/[\d]+\/view\/[\d]+/.test(link)) {
  9508. this.#addBtn(steamStoreLink, 'steam', 'announcementLinks', link);
  9509. } else if (/app\/[\d]+/.test(link)) {
  9510. this.#addBtn(steamStoreLink, 'steam', 'followLinks', link);
  9511. this.#addBtn(steamStoreLink, 'steam', 'wishlistLinks', link);
  9512. }
  9513. }
  9514. }
  9515. if (steamCommunityLinks.length > 0) {
  9516. for (const steamCommunityLink of steamCommunityLinks) {
  9517. const link = $(steamCommunityLink).attr('href');
  9518. if (!link) {
  9519. continue;
  9520. }
  9521. if (/groups\/.+/.test(link)) {
  9522. this.#addBtn(steamCommunityLink, 'steam', 'groupLinks', link);
  9523. } else if (/announcements\/detail\/[\d]+/.test(link)) {
  9524. this.#addBtn(steamCommunityLink, 'steam', 'announcementLinks', link);
  9525. }
  9526. }
  9527. }
  9528. if (ytbLinks.length > 0) {
  9529. for (const ytbLink of ytbLinks) {
  9530. const link = $(ytbLink).attr('href');
  9531. if (!link) {
  9532. continue;
  9533. }
  9534. this.#addBtn(ytbLink, 'youtube', 'channelLinks', link);
  9535. this.#addBtn(ytbLink, 'youtube', 'likeLinks', link);
  9536. }
  9537. }
  9538. 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');
  9539. if (giveawayLinks.length > 0) {
  9540. for (const giveawayLink of giveawayLinks) {
  9541. const link = $(giveawayLink).attr('href');
  9542. if (!link) {
  9543. continue;
  9544. }
  9545. website_leftKeyChecker.classify(link).then(status => {
  9546. if (!status) {
  9547. return;
  9548. }
  9549. if (/^Active/.test(status)) {
  9550. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status active" title="${i18n('Active')}">${status}</font>`);
  9551. return;
  9552. }
  9553. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status not-active" title="${i18n(status)}">${status}</font>`);
  9554. }).catch(error => {
  9555. throwError(error, 'keylol.after -> leftKeyChecker');
  9556. });
  9557. }
  9558. }
  9559. if (this.name === 'Keylol') {
  9560. const asfLinks = mainPost.find('a[href^="#asf"]:visible');
  9561. if (asfLinks.length > 0) {
  9562. for (const asfLink of asfLinks) {
  9563. const link = $(asfLink).attr('href');
  9564. if (!link) {
  9565. continue;
  9566. }
  9567. this.#addBtn($(`a[href="${link}"]`).after('<span style="color: #ccc; margin: 0 -5px 0 5px"> | </span>').next()[0], 'steam', 'licenseLinks', `appid-${link.replace('#asf', '')}`);
  9568. }
  9569. }
  9570. const subLinks = mainPost.find('a[href*="steamdb.info/sub/"]:visible');
  9571. if (subLinks.length > 0) {
  9572. for (const subLink of subLinks) {
  9573. const link = $(subLink).attr('href');
  9574. if (!link) {
  9575. continue;
  9576. }
  9577. const subid = link.match(/^https:\/\/steamdb\.info\/sub\/([\d]+)/)?.[1];
  9578. if (!subid) {
  9579. continue;
  9580. }
  9581. this.#addBtn(subLink, 'steam', 'licenseLinks', `subid-${subid}`);
  9582. }
  9583. }
  9584. const asfLinks2 = mainPost.find('.blockcode:contains("addlicense"):visible');
  9585. if (asfLinks2.length > 0) {
  9586. for (const asfLink of asfLinks2) {
  9587. const appid = [ ...asfLink.innerText.matchAll(/a(pp)?\/([\d]+)/g) ].map(matched => matched?.[2]).filter(id => id) || [];
  9588. if (appid.length > 0) {
  9589. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `appid-${appid.join(',')}`);
  9590. }
  9591. const subid = asfLink.innerText.match(/[\d]+/g)?.filter(matched => !appid.includes(matched));
  9592. if (!subid || subid.length === 0) {
  9593. continue;
  9594. }
  9595. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `subid-${subid.join(',')}`);
  9596. }
  9597. }
  9598. }
  9599. if ($('#threadindex').length > 0) {
  9600. const [ targetNode ] = $('#postlist').children('div[id^="post_"]');
  9601. const config = {
  9602. childList: true
  9603. };
  9604. const observer = new MutationObserver(() => {
  9605. observer.disconnect();
  9606. this.after();
  9607. });
  9608. observer.observe(targetNode, config);
  9609. }
  9610. } catch (error) {
  9611. throwError(error, 'keylol.after');
  9612. }
  9613. }
  9614. classifyTask(action) {
  9615. try {
  9616. this.socialTasks = JSON.parse(Keylol_defaultTasks);
  9617. this.undoneTasks = JSON.parse(Keylol_defaultTasks);
  9618. const selectedBtns = $('.auto-task-keylol[selected="selected"]:visible');
  9619. for (const btn of selectedBtns) {
  9620. const button = $(btn);
  9621. const social = button.attr('data-social');
  9622. const type = button.attr('data-type');
  9623. const link = button.attr('data-link');
  9624. if (!(social && type && link)) {
  9625. continue;
  9626. }
  9627. if (action === 'do') {
  9628. this.undoneTasks[social][type].push(link);
  9629. }
  9630. if (action === 'undo') {
  9631. this.socialTasks[social][type].push(link);
  9632. }
  9633. }
  9634. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9635. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9636. if (window.DEBUG) {
  9637. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9638. }
  9639. return true;
  9640. } catch (error) {
  9641. throwError(error, 'Keylol.classifyTask');
  9642. return false;
  9643. }
  9644. }
  9645. selectAll() {
  9646. try {
  9647. $('.auto-task-keylol:visible').attr('selected', 'selected');
  9648. } catch (error) {
  9649. throwError(error, 'Keylol.selectAll');
  9650. }
  9651. }
  9652. selectNone() {
  9653. try {
  9654. $('.auto-task-keylol:visible').removeAttr('selected');
  9655. } catch (error) {
  9656. throwError(error, 'Keylol.selectNone');
  9657. }
  9658. }
  9659. invertSelect() {
  9660. try {
  9661. $('.auto-task-keylol:visible').each((index, element) => {
  9662. element.getAttribute('selected') ? element.removeAttribute('selected') : element.setAttribute('selected', 'selected');
  9663. });
  9664. } catch (error) {
  9665. throwError(error, 'Keylol.invertSelect');
  9666. }
  9667. }
  9668. #addBtn(before, social, linkType, link) {
  9669. try {
  9670. $(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>`);
  9671. } catch (error) {
  9672. throwError(error, 'keylol.addBtn');
  9673. }
  9674. }
  9675. }
  9676. const website_Keylol = Keylol;
  9677. const Opquests_defaultTasks = {
  9678. steam: {
  9679. groupLinks: [],
  9680. wishlistLinks: [],
  9681. followLinks: [],
  9682. curatorLikeLinks: []
  9683. },
  9684. twitter: {
  9685. userLinks: [],
  9686. retweetLinks: []
  9687. }
  9688. };
  9689. class Opquests extends website_Website {
  9690. name = 'Opquests';
  9691. undoneTasks = {
  9692. ...Opquests_defaultTasks
  9693. };
  9694. buttons = [ 'doTask', 'verifyTask', 'getKey' ];
  9695. static test() {
  9696. return window.location.host === 'opquests.com';
  9697. }
  9698. async after() {
  9699. try {
  9700. if (!this.#checkLogin()) {
  9701. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9702. }
  9703. const opquestsVerifyTasks = GM_getValue('opquestsVerifyTasks') || [];
  9704. if (opquestsVerifyTasks.length > 0) {
  9705. const taskId = opquestsVerifyTasks.pop();
  9706. GM_setValue('opquestsVerifyTasks', opquestsVerifyTasks);
  9707. const [ verifyBtn ] = $(`#task_id[value="${taskId}"]`).parent().find('button[type="button"]').has('i.fa-check');
  9708. if (verifyBtn) {
  9709. verifyBtn.click();
  9710. return;
  9711. }
  9712. this.after();
  9713. return;
  9714. }
  9715. if (GM_getValue('opquestsVerifyTasks')) {
  9716. GM_deleteValue('opquestsVerifyTasks');
  9717. }
  9718. } catch (error) {
  9719. throwError(error, 'Opquests.after');
  9720. }
  9721. }
  9722. init() {
  9723. try {
  9724. const logStatus = scripts_echoLog({
  9725. text: i18n('initing')
  9726. });
  9727. if ($('a[href*="/auth/redirect"]').length > 0) {
  9728. window.open('/auth/redirect', '_self');
  9729. logStatus.warning(i18n('needLogin'));
  9730. return false;
  9731. }
  9732. if (!this.#getGiveawayId()) {
  9733. return false;
  9734. }
  9735. this.initialized = true;
  9736. logStatus.success();
  9737. return true;
  9738. } catch (error) {
  9739. throwError(error, 'Opquests.init');
  9740. return false;
  9741. }
  9742. }
  9743. async classifyTask(action) {
  9744. try {
  9745. if (action === 'undo') {
  9746. scripts_echoLog({
  9747. text: i18n('cannotUndo')
  9748. });
  9749. return false;
  9750. }
  9751. const logStatus = scripts_echoLog({
  9752. text: i18n('getTasksInfo')
  9753. });
  9754. const tasks = $('.w-full:contains("Validate") .items-center');
  9755. for (const task of tasks) {
  9756. const link = $(task).find('a:contains("Open")').attr('href');
  9757. const taskDes = $(task).find('div').eq(1).text().trim();
  9758. if (!link) {
  9759. continue;
  9760. }
  9761. if (/steamcommunity\.com\/groups\//.test(link)) {
  9762. this.undoneTasks.steam.groupLinks.push(link);
  9763. } else if (/store\.steampowered\.com\/app\//.test(link)) {
  9764. if (/wishlist/gim.test(taskDes)) {
  9765. this.undoneTasks.steam.wishlistLinks.push(link);
  9766. } else if (/follow/gim.test(taskDes)) {
  9767. this.undoneTasks.steam.followLinks.push(link);
  9768. }
  9769. } else if (/store\.steampowered\.com\/(publisher|developer|curator)\//.test(link) && /follow/gim.test(taskDes)) {
  9770. this.undoneTasks.steam.curatorLikeLinks.push(link);
  9771. } else if (link.includes('//x.com/') && /follow/gim.test(taskDes)) {
  9772. this.undoneTasks.twitter.userLinks.push(link);
  9773. } else if (link.includes('//x.com/') && link.includes('status') && /Repost/gim.test(taskDes)) {
  9774. this.undoneTasks.twitter.retweetLinks.push(link);
  9775. } else if (/clash.gg/.test(link)) {
  9776. scripts_echoLog({}).warning(`${i18n('unSupporttedTaskType')}: ${taskDes}(${link})`);
  9777. } else {
  9778. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  9779. }
  9780. }
  9781. logStatus.success();
  9782. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9783. if (window.DEBUG) {
  9784. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9785. }
  9786. return true;
  9787. } catch (error) {
  9788. throwError(error, 'Opquests.classifyTask');
  9789. return false;
  9790. }
  9791. }
  9792. async verifyTask() {
  9793. try {
  9794. if (!this.initialized) {
  9795. this.init();
  9796. }
  9797. const tasks = $.makeArray($('.items-center').has('input[name="task_id"]')).map(ele => $(ele).find('input[name="task_id"]').val());
  9798. GM_setValue('opquestsVerifyTasks', tasks);
  9799. await this.#confirm();
  9800. this.after();
  9801. return true;
  9802. } catch (error) {
  9803. throwError(error, 'Opquests.verifyTask');
  9804. return false;
  9805. }
  9806. }
  9807. async #confirm() {
  9808. try {
  9809. const logStatus = scripts_echoLog({
  9810. html: `<li>${i18n('confirmingTask')}...<font></font></li>`
  9811. });
  9812. const {
  9813. result,
  9814. statusText,
  9815. status,
  9816. data
  9817. } = await tools_httpRequest({
  9818. url: `https://opquests.com/quests/${this.giveawayId}?confirm=1`,
  9819. method: 'GET',
  9820. nochche: true,
  9821. headers: {
  9822. origin: 'https://opquests.com',
  9823. referer: `https://opquests.com/warning?id=${this.giveawayId}`
  9824. }
  9825. });
  9826. if (result === 'Success') {
  9827. if (data?.status === 200) {
  9828. logStatus.success();
  9829. return true;
  9830. }
  9831. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9832. return false;
  9833. }
  9834. logStatus.error(`${result}:${statusText}(${status})`);
  9835. return false;
  9836. } catch (error) {
  9837. throwError(error, 'Opquests.confirm');
  9838. return false;
  9839. }
  9840. }
  9841. async getKey(isButton) {
  9842. try {
  9843. const logStatus = scripts_echoLog({
  9844. text: i18n('gettingKey')
  9845. });
  9846. const {
  9847. result,
  9848. statusText,
  9849. status,
  9850. data
  9851. } = await tools_httpRequest({
  9852. url: 'https://opquests.com/keys',
  9853. method: 'GET'
  9854. });
  9855. if (result === 'Success') {
  9856. if (data?.responseText) {
  9857. const key = $(data?.responseText).find(`div.items-center:contains("${$('h1.font-bold').text().trim().replace(' Quest', '')}")`).find('div.font-bold').next().text();
  9858. if (!key) {
  9859. logStatus.error('Error: Key was not found');
  9860. if (isButton) {
  9861. window.open('https://opquests.com/keys', '_self');
  9862. }
  9863. return false;
  9864. }
  9865. logStatus.success();
  9866. scripts_echoLog({}).success(key);
  9867. return true;
  9868. }
  9869. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9870. return false;
  9871. }
  9872. logStatus.error(`${result}:${statusText}(${status})`);
  9873. return false;
  9874. } catch (error) {
  9875. throwError(error, 'Opquests.getGiveawayId');
  9876. return false;
  9877. }
  9878. }
  9879. #getGiveawayId() {
  9880. try {
  9881. const giveawayId = window.location.href.match(/quests\/([\d]+)/)?.[1];
  9882. if (giveawayId) {
  9883. this.giveawayId = giveawayId;
  9884. return true;
  9885. }
  9886. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  9887. return false;
  9888. } catch (error) {
  9889. throwError(error, 'Opquests.getGiveawayId');
  9890. return false;
  9891. }
  9892. }
  9893. #checkLogin() {
  9894. try {
  9895. if (!globalOptions.other.checkLogin) {
  9896. return true;
  9897. }
  9898. if ($('a[href*="/auth/redirect"]').length > 0) {
  9899. window.open('/auth/redirect', '_self');
  9900. }
  9901. return true;
  9902. } catch (error) {
  9903. throwError(error, 'Opquests.checkLogin');
  9904. return false;
  9905. }
  9906. }
  9907. }
  9908. const website_Opquests = Opquests;
  9909. const Gleam_defaultTasksTemplate = {
  9910. steam: {
  9911. groupLinks: [],
  9912. wishlistLinks: [],
  9913. followLinks: [],
  9914. curatorLinks: [],
  9915. curatorLikeLinks: []
  9916. },
  9917. twitter: {
  9918. userLinks: [],
  9919. retweetLinks: []
  9920. },
  9921. twitch: {
  9922. channelLinks: []
  9923. },
  9924. discord: {
  9925. serverLinks: []
  9926. },
  9927. youtube: {
  9928. channelLinks: []
  9929. },
  9930. extra: {
  9931. gleam: []
  9932. }
  9933. };
  9934. const Gleam_defaultTasks = JSON.stringify(Gleam_defaultTasksTemplate);
  9935. class Gleam extends website_Website {
  9936. name = 'Gleam';
  9937. undoneTasks = JSON.parse(Gleam_defaultTasks);
  9938. socialTasks = JSON.parse(Gleam_defaultTasks);
  9939. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  9940. static test() {
  9941. return window.location.host === 'gleam.io';
  9942. }
  9943. before() {
  9944. try {
  9945. unsafeWindow.confirm = () => {};
  9946. unsafeWindow.alert = () => {};
  9947. unsafeWindow.prompt = () => {};
  9948. } catch (error) {
  9949. throwError(error, 'Gleam.before');
  9950. }
  9951. }
  9952. async after() {
  9953. try {
  9954. if (window.location.search.includes('8b07d23f4bfa65f9')) {
  9955. const checkComplete = setInterval(() => {
  9956. if ($('.entry-content .entry-method i.fa-check').length > 0) {
  9957. clearInterval(checkComplete);
  9958. window.close();
  9959. }
  9960. });
  9961. for (const task of $('.entry-content .entry-method')) {
  9962. const taskInfo = $(task).find('.user-links');
  9963. const expandInfo = $(task).find('.expandable');
  9964. const aElements = expandInfo.find('a.btn,a:contains(Continue),button:contains(Continue)');
  9965. if (aElements.length > 0) {
  9966. for (const element of aElements) {
  9967. const $element = $(element);
  9968. const href = $element.attr('href');
  9969. $element.removeAttr('href')[0].click();
  9970. $element.attr('href', href);
  9971. await delay(1e3);
  9972. }
  9973. }
  9974. taskInfo[0].click();
  9975. await delay(1e3);
  9976. }
  9977. scripts_echoLog({}).warning(i18n('gleamTaskNotice'));
  9978. } else if (!await this.#checkLeftKey()) {
  9979. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  9980. }
  9981. } catch (error) {
  9982. throwError(error, 'Gleam.after');
  9983. }
  9984. }
  9985. init() {
  9986. try {
  9987. const logStatus = scripts_echoLog({
  9988. text: i18n('initing')
  9989. });
  9990. if (!this.#getGiveawayId()) {
  9991. return false;
  9992. }
  9993. this.initialized = true;
  9994. logStatus.success();
  9995. return true;
  9996. } catch (error) {
  9997. throwError(error, 'Gleam.init');
  9998. return false;
  9999. }
  10000. }
  10001. async classifyTask(action) {
  10002. try {
  10003. const logStatus = scripts_echoLog({
  10004. text: i18n('getTasksInfo')
  10005. });
  10006. if (action === 'undo') {
  10007. this.socialTasks = GM_getValue(`gleamTasks-${this.giveawayId}`)?.tasks || JSON.parse(Gleam_defaultTasks);
  10008. }
  10009. const tasks = $('.entry-content .entry-method');
  10010. for (const task of tasks) {
  10011. const $task = $(task);
  10012. if (action === 'do' && $task.find('i.fa-question').length === 0) {
  10013. continue;
  10014. }
  10015. const socialIcon = $task.find('.icon-wrapper i');
  10016. const taskInfo = $task.find('.user-links');
  10017. const taskText = taskInfo.text().trim();
  10018. const expandInfo = $task.find('.expandable');
  10019. const aElements = expandInfo.find('a.btn');
  10020. if (aElements.length > 0) {
  10021. for (const element of aElements) {
  10022. const $element = $(element);
  10023. const href = $element.attr('href');
  10024. $element.removeAttr('href')[0].click();
  10025. $element.attr('href', href);
  10026. }
  10027. }
  10028. if (socialIcon.hasClass('fa-twitter') || socialIcon.hasClass('fa-x-twitter')) {
  10029. const link = $task.find('a[href^="https://twitter.com/"],a[href^="https://x.com/"]').attr('href');
  10030. if (!link) {
  10031. continue;
  10032. }
  10033. if (/follow/gi.test(taskText)) {
  10034. if (action === 'undo') {
  10035. this.socialTasks.twitter.userLinks.push(link);
  10036. }
  10037. if (action === 'do') {
  10038. this.undoneTasks.twitter.userLinks.push(link);
  10039. }
  10040. } else if (/retweet/gim.test(taskText)) {
  10041. if (action === 'undo') {
  10042. this.socialTasks.twitter.retweetLinks.push(link);
  10043. }
  10044. if (action === 'do') {
  10045. this.undoneTasks.twitter.retweetLinks.push(link);
  10046. }
  10047. }
  10048. } else if (socialIcon.hasClass('fa-twitch')) {
  10049. if (/follow/gim.test(taskText)) {
  10050. const link = $task.find('a[href^="https://twitch.tv/"]').attr('href');
  10051. if (!link) {
  10052. continue;
  10053. }
  10054. if (action === 'undo') {
  10055. this.socialTasks.twitch.channelLinks.push(link);
  10056. }
  10057. if (action === 'do') {
  10058. this.undoneTasks.twitch.channelLinks.push(link);
  10059. }
  10060. }
  10061. } else if (socialIcon.hasClass('fa-discord')) {
  10062. if (/join/gim.test(taskText)) {
  10063. let link = $task.find('a[href^="https://discord.com/invite/"]').attr('href');
  10064. if (!link) {
  10065. const ggLink = $task.find('a[href^="https://discord.gg/"]').attr('href')?.match(/discord\.gg\/([^/]+)/)?.[1];
  10066. if (!ggLink) {
  10067. continue;
  10068. }
  10069. link = `https://discord.com/invite/${ggLink}`;
  10070. }
  10071. if (action === 'undo') {
  10072. this.socialTasks.discord.serverLinks.push(link);
  10073. }
  10074. if (action === 'do') {
  10075. this.undoneTasks.discord.serverLinks.push(link);
  10076. }
  10077. }
  10078. } else if (socialIcon.hasClass('fa-external-link-square-alt')) {
  10079. continue;
  10080. } else if (socialIcon.hasClass('fa-youtube')) {
  10081. if (/subscribe/gim.test(taskText)) {
  10082. const link = $task.find('a[href^="https://www.youtube.com/channel/"]').attr('href');
  10083. if (!link) {
  10084. continue;
  10085. }
  10086. if (action === 'undo') {
  10087. this.socialTasks.youtube.channelLinks.push(link);
  10088. }
  10089. if (action === 'do') {
  10090. this.undoneTasks.youtube.channelLinks.push(link);
  10091. }
  10092. }
  10093. } else if (socialIcon.attr('class')?.includes('steam')) {
  10094. if (/join.*group/gi.test(taskText)) {
  10095. const link = $task.find('a[href^="https://steamcommunity.com/groups/"]').attr('href');
  10096. if (!link) {
  10097. continue;
  10098. }
  10099. if (action === 'undo') {
  10100. this.socialTasks.steam.groupLinks.push(link);
  10101. }
  10102. if (action === 'do') {
  10103. this.undoneTasks.steam.groupLinks.push(link);
  10104. }
  10105. } else if (/follow.*curator/gi.test(taskText)) {
  10106. const link = $task.find('a[href^="https://store.steampowered.com/curator/"]').attr('href');
  10107. if (!link) {
  10108. continue;
  10109. }
  10110. if (action === 'undo') {
  10111. this.socialTasks.steam.curatorLinks.push(link);
  10112. }
  10113. if (action === 'do') {
  10114. this.undoneTasks.steam.curatorLinks.push(link);
  10115. }
  10116. }
  10117. } else if (socialIcon.hasClass('fa-bullhorn') && /Complete|Increase/gi.test(taskText)) {
  10118. if (action !== 'do') {
  10119. continue;
  10120. }
  10121. const gleamLink = await this.#getGleamLink(taskText);
  10122. if (!gleamLink) {
  10123. continue;
  10124. }
  10125. this.undoneTasks.extra.gleam.push(gleamLink);
  10126. } 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 {
  10127. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskText}`);
  10128. }
  10129. }
  10130. logStatus.success();
  10131. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  10132. this.socialTasks = this.uniqueTasks(this.socialTasks);
  10133. if (window.DEBUG) {
  10134. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  10135. }
  10136. GM_setValue(`gleamTasks-${this.giveawayId}`, {
  10137. tasks: this.socialTasks,
  10138. time: new Date().getTime()
  10139. });
  10140. return true;
  10141. } catch (error) {
  10142. throwError(error, 'Gleam.classifyTask');
  10143. return false;
  10144. }
  10145. }
  10146. async extraDoTask({
  10147. gleam
  10148. }) {
  10149. try {
  10150. const pro = [];
  10151. for (const link of gleam) {
  10152. pro.push(this.#doGleamTask(link));
  10153. }
  10154. return Promise.all(pro).then(() => true);
  10155. } catch (error) {
  10156. throwError(error, 'Gleam.extraDoTask');
  10157. return false;
  10158. }
  10159. }
  10160. async verifyTask() {
  10161. try {
  10162. scripts_echoLog({
  10163. text: `${i18n('verifyingTask')}...`
  10164. });
  10165. const tasks = $('.entry-content .entry-method');
  10166. unsafeWindow._OxA = '_OxA';
  10167. for (const task of tasks) {
  10168. if ($('[campaign-key="campaign.key"]').length > 0) {
  10169. return scripts_echoLog({
  10170. text: i18n('campaign')
  10171. });
  10172. }
  10173. const $task = $(task);
  10174. if ($task.find('i.fa-question').length === 0) {
  10175. continue;
  10176. }
  10177. const taskInfo = $task.find('.user-links');
  10178. taskInfo[0].click();
  10179. const aElements = $task.find('.expandable').find('a.btn');
  10180. if (aElements.length > 0) {
  10181. for (const element of aElements) {
  10182. const $element = $(element);
  10183. const href = $element.attr('href');
  10184. $element.removeAttr('href')[0].click();
  10185. $element.attr('href', href);
  10186. }
  10187. }
  10188. unsafeWindow.$hookTimer?.setSpeed(1e3);
  10189. const visitBtn = $task.find('.expandable').find('span:contains(more seconds),button:contains(more seconds)').filter(':visible');
  10190. if (visitBtn.length > 0 && unsafeWindow.$hookTimer) {
  10191. const newTab = GM_openInTab('', {
  10192. active: true
  10193. });
  10194. await delay(1e3);
  10195. newTab?.close();
  10196. window.focus();
  10197. }
  10198. await delay(3e3);
  10199. unsafeWindow.$hookTimer?.setSpeed(1);
  10200. const expandInfo = $task.find('.expandable');
  10201. const [ input ] = expandInfo.find('input');
  10202. if (input) {
  10203. const evt = new Event('input', {
  10204. bubbles: true,
  10205. cancelable: true,
  10206. composed: true
  10207. });
  10208. const valuelimit = [ ...expandInfo.text().matchAll(/"(.+?)"/g) ].at(-1)?.[1];
  10209. input.value = valuelimit || 'vloot';
  10210. input.dispatchEvent(evt);
  10211. await delay(1e3);
  10212. }
  10213. await this.#checkSync();
  10214. const continueBtn = $task.find('.expandable').find('span:contains(Continue),button:contains(Continue)');
  10215. for (const button of continueBtn) {
  10216. button.click();
  10217. await delay(500);
  10218. await this.#checkSync();
  10219. }
  10220. }
  10221. scripts_echoLog({
  10222. text: i18n('verifiedGleamTasks')
  10223. });
  10224. } catch (error) {
  10225. throwError(error, 'Gleam.verifyTask');
  10226. return false;
  10227. }
  10228. }
  10229. async #checkSync() {
  10230. try {
  10231. return await new Promise(resolve => {
  10232. const checker = setInterval(() => {
  10233. if ($('.entry-content .entry-method i.fa-sync').length === 0) {
  10234. clearInterval(checker);
  10235. resolve(true);
  10236. }
  10237. }, 500);
  10238. });
  10239. } catch (error) {
  10240. throwError(error, 'Gleam.checkSync');
  10241. return false;
  10242. }
  10243. }
  10244. async #doGleamTask(link) {
  10245. try {
  10246. const logStatus = scripts_echoLog({
  10247. text: i18n('doingGleamTask')
  10248. });
  10249. return await new Promise(resolve => {
  10250. GM_openInTab(`${link}?8b07d23f4bfa65f9`, {
  10251. active: true,
  10252. insert: true,
  10253. setParent: true
  10254. }).onclose = () => {
  10255. logStatus.success();
  10256. resolve(true);
  10257. };
  10258. });
  10259. } catch (error) {
  10260. throwError(error, 'Gleam.doGleamTask');
  10261. return false;
  10262. }
  10263. }
  10264. #getGiveawayId() {
  10265. try {
  10266. const giveawayId = window.location.pathname;
  10267. if (giveawayId) {
  10268. this.giveawayId = giveawayId;
  10269. return true;
  10270. }
  10271. scripts_echoLog({
  10272. text: i18n('getFailed', 'GiveawayId')
  10273. });
  10274. return false;
  10275. } catch (error) {
  10276. throwError(error, 'Gleam.getGiveawayId');
  10277. return false;
  10278. }
  10279. }
  10280. async #getGleamLink(title) {
  10281. try {
  10282. const logStatus = scripts_echoLog({
  10283. text: i18n('gettingGleamLink')
  10284. });
  10285. const {
  10286. result,
  10287. statusText,
  10288. status,
  10289. data
  10290. } = await tools_httpRequest({
  10291. url: 'https://www.vloot.io/api/v1/giveaways',
  10292. method: 'GET',
  10293. responseType: 'json'
  10294. });
  10295. if (result === 'Success') {
  10296. if (data?.status === 200 && data?.response?.Success === true && data?.response?.Data) {
  10297. const {
  10298. link
  10299. } = data.response.Data.find(giveaway => title.replace(/[\s]/g, '').toLowerCase().includes(giveaway.title.replace(/[\s]/g, '').toLowerCase())) || {};
  10300. if (link) {
  10301. logStatus.success();
  10302. return link;
  10303. }
  10304. logStatus.error(`Error:${i18n('getLinkFailed')}`);
  10305. return false;
  10306. }
  10307. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10308. return false;
  10309. }
  10310. logStatus.error(`${result}:${statusText}(${status})`);
  10311. return false;
  10312. } catch (error) {
  10313. throwError(error, 'Gleam.getGleamLink');
  10314. return false;
  10315. }
  10316. }
  10317. async #checkLeftKey() {
  10318. try {
  10319. if (!globalOptions.other.checkLeftKey) {
  10320. return true;
  10321. }
  10322. const campaignString = $('div.popup-blocks-container').attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  10323. if (!campaignString) {
  10324. return false;
  10325. }
  10326. const {
  10327. campaign,
  10328. incentive
  10329. } = JSON.parse(campaignString);
  10330. const controllerString = $('div.campaign.reward').attr('ng-init')?.match(/initContestant\(([\w\W]+?)\);/)?.[1];
  10331. let ownedKey = false;
  10332. if (controllerString) {
  10333. if (JSON.parse(controllerString).contestant?.claims?.incentives?.[incentive.id]?.length) {
  10334. ownedKey = true;
  10335. }
  10336. }
  10337. if (campaign.banned || campaign.finished && !ownedKey || campaign.paused || new Date().getTime() < campaign.starts_at * 1e3) {
  10338. await external_Swal_default().fire({
  10339. icon: 'warning',
  10340. title: i18n('notice'),
  10341. text: i18n('giveawayNotWork'),
  10342. confirmButtonText: i18n('confirm'),
  10343. cancelButtonText: i18n('cancel'),
  10344. showCancelButton: true
  10345. }).then(({
  10346. value
  10347. }) => {
  10348. if (value) {
  10349. window.close();
  10350. }
  10351. });
  10352. }
  10353. return true;
  10354. } catch (error) {
  10355. throwError(error, 'Gleam.checkLeftKey');
  10356. return false;
  10357. }
  10358. }
  10359. }
  10360. const website_Gleam = Gleam;
  10361. const SweepWidget_defaultOptions = {
  10362. username: '',
  10363. email: ''
  10364. };
  10365. class SweepWidget extends website_Website {
  10366. name = 'SweepWidget';
  10367. options = {
  10368. ...SweepWidget_defaultOptions,
  10369. ...GM_getValue('SweepWidgetOptions')
  10370. };
  10371. buttons = [ 'doTask' ];
  10372. static test() {
  10373. return /^https?:\/\/sweepwidget\.com\/view\/[\d]+/.test(window.location.href);
  10374. }
  10375. async after() {
  10376. try {
  10377. if (!this.#checkLogin()) {
  10378. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  10379. }
  10380. } catch (error) {
  10381. throwError(error, 'SweepWidget.after');
  10382. }
  10383. }
  10384. init() {
  10385. try {
  10386. const logStatus = scripts_echoLog({
  10387. text: i18n('initing')
  10388. });
  10389. if (!this.#checkLogin()) {
  10390. logStatus.warning(i18n('needLogin'));
  10391. return false;
  10392. }
  10393. if (!this.#getGiveawayId()) {
  10394. return false;
  10395. }
  10396. this.initialized = true;
  10397. logStatus.success();
  10398. return true;
  10399. } catch (error) {
  10400. throwError(error, 'SweepWidget.init');
  10401. return false;
  10402. }
  10403. }
  10404. classifyTask() {
  10405. return true;
  10406. }
  10407. async doTask() {
  10408. try {
  10409. if ($('#unlock_rewards_main_wrapper').length === 0) {
  10410. if ($('input[name="sw__login_name"]:visible').length > 0) {
  10411. $('input[name="sw__login_name"]').val(this.options.username);
  10412. }
  10413. if ($('input[name="sw__login_email"]:visible').length > 0) {
  10414. $('input[name="sw__login_email"]').val(this.options.email);
  10415. }
  10416. if ($('#sw_login_button:visible').length > 0) {
  10417. $('#sw_login_button')[0].click();
  10418. }
  10419. if (!await this.#checkEnter()) {
  10420. return false;
  10421. }
  10422. }
  10423. const logStatus = scripts_echoLog({
  10424. text: i18n('SweepWidgetNotice')
  10425. });
  10426. const tasks = $('#sw_inner_entry_methods_l2_wrapper>div.sw_entry');
  10427. for (const task of tasks) {
  10428. const $task = $(task);
  10429. if ($task.find('i.fa-check:visible').length > 0) {
  10430. continue;
  10431. }
  10432. const title = $task.find('.sw_text_inner');
  10433. title[0].click();
  10434. const aElement = $task.find('a.sw_link');
  10435. const link = aElement.attr('href');
  10436. aElement.attr('href', '#a').attr('target', '_self');
  10437. aElement[0]?.click();
  10438. await delay(300);
  10439. aElement.attr('href', link).attr('target', '_blank');
  10440. $task.find('input[type="text"]').val('test');
  10441. const verifyBtn = $task.find('input.sw_verify');
  10442. if (verifyBtn.prop('disabled') === true) {
  10443. title[0].click();
  10444. await delay(300);
  10445. title[0].click();
  10446. await delay(300);
  10447. }
  10448. $task.find('input.sw_verify').removeAttr('disabled')[0]?.click();
  10449. await this.#checkFinish($task);
  10450. await delay(parseInt(`${Math.random() * (3e3 - 1e3 + 1) + 1e3}`, 10));
  10451. }
  10452. logStatus.success();
  10453. return true;
  10454. } catch (error) {
  10455. throwError(error, 'SweepWidget.doTask');
  10456. return false;
  10457. }
  10458. }
  10459. #checkLogin() {
  10460. try {
  10461. if ($('#twitter_login_button').length > 0) {
  10462. $('#twitter_login_button')[0].click();
  10463. }
  10464. return true;
  10465. } catch (error) {
  10466. throwError(error, 'SweepWidget.checkLogin');
  10467. return false;
  10468. }
  10469. }
  10470. #getGiveawayId() {
  10471. try {
  10472. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  10473. if (giveawayId) {
  10474. this.giveawayId = giveawayId;
  10475. return true;
  10476. }
  10477. scripts_echoLog({
  10478. text: i18n('getFailed', 'GiveawayId')
  10479. });
  10480. return false;
  10481. } catch (error) {
  10482. throwError(error, 'SweepWidget.getGiveawayId');
  10483. return false;
  10484. }
  10485. }
  10486. async #checkEnter() {
  10487. try {
  10488. return new Promise(resolve => {
  10489. const checker = setInterval(() => {
  10490. if ($('#unlock_rewards_main_wrapper').length > 0) {
  10491. clearInterval(checker);
  10492. resolve(true);
  10493. }
  10494. }, 500);
  10495. });
  10496. } catch (error) {
  10497. throwError(error, 'SweepWidget.checkEnter');
  10498. return false;
  10499. }
  10500. }
  10501. async #checkFinish($task) {
  10502. try {
  10503. return new Promise(resolve => {
  10504. const checker = setInterval(() => {
  10505. if ($task.find('i.fa-check:visible').length > 0 || $task.find('.sw_entry_input:visible').length === 0) {
  10506. clearInterval(checker);
  10507. resolve(true);
  10508. }
  10509. }, 500);
  10510. });
  10511. } catch (error) {
  10512. throwError(error, 'SweepWidget.checkFinish');
  10513. return false;
  10514. }
  10515. }
  10516. }
  10517. const website_SweepWidget = SweepWidget;
  10518. const defaultWhiteList = {
  10519. discord: {
  10520. servers: []
  10521. },
  10522. instagram: {
  10523. users: []
  10524. },
  10525. twitch: {
  10526. channels: []
  10527. },
  10528. twitter: {
  10529. users: [],
  10530. retweets: [],
  10531. likes: []
  10532. },
  10533. vk: {
  10534. names: []
  10535. },
  10536. youtube: {
  10537. channels: [],
  10538. likes: []
  10539. },
  10540. reddit: {
  10541. reddits: []
  10542. },
  10543. steam: {
  10544. groups: [],
  10545. officialGroups: [],
  10546. wishlists: [],
  10547. follows: [],
  10548. forums: [],
  10549. workshops: [],
  10550. curators: [],
  10551. workshopVotes: [],
  10552. curatorLikes: [],
  10553. announcements: [],
  10554. licenses: [],
  10555. playtests: []
  10556. }
  10557. };
  10558. const link2id = async function(type) {
  10559. try {
  10560. const link = $('#socialLink').val();
  10561. let id = '';
  10562. switch (type) {
  10563. case 'discord.servers':
  10564. id = link.match(/invite\/(.+)/)?.[1] || '';
  10565. break;
  10566.  
  10567. case 'instagram.users':
  10568. id = link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1] || '';
  10569. break;
  10570.  
  10571. case 'twitch.channels':
  10572. id = link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2] || '';
  10573. break;
  10574.  
  10575. case 'twitter.users':
  10576. id = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || '';
  10577. break;
  10578.  
  10579. case 'twitter.retweets':
  10580. id = link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1] || '';
  10581. break;
  10582.  
  10583. case 'vk.names':
  10584. id = link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1] || '';
  10585. break;
  10586.  
  10587. case 'youtube.channels':
  10588. id = (await getInfo(link, 'channel'))?.params?.channelId || '';
  10589. break;
  10590.  
  10591. case 'youtube.likes':
  10592. id = (await getInfo(link, 'likeVideo'))?.params?.videoId || '';
  10593. break;
  10594.  
  10595. case 'reddit.reddits':
  10596. id = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1] || link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1] || '';
  10597. break;
  10598.  
  10599. case 'steam.groups':
  10600. id = link.match(/groups\/(.+)\/?/)?.[1] || '';
  10601. break;
  10602.  
  10603. case 'steam.wishlists':
  10604. case 'steam.follows':
  10605. case 'steam.forums':
  10606. id = link.match(/app\/([\d]+)/)?.[1] || '';
  10607. break;
  10608.  
  10609. case 'steam.workshops':
  10610. id = link.match(/\?id=([\d]+)/)?.[1] || '';
  10611. break;
  10612.  
  10613. case 'steam.curators':
  10614. {
  10615. if (link.includes('curator')) {
  10616. id = link.match(/curator\/([\d]+)/)?.[1] || '';
  10617. } else {
  10618. const param = link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3);
  10619. if (!param || param.length !== 2) {
  10620. break;
  10621. }
  10622. const steam = new social_Steam();
  10623. if (await steam.init()) {
  10624. id = await steam.getCuratorId(param[0], param[1]) || '';
  10625. }
  10626. }
  10627. }
  10628. break;
  10629. }
  10630. return id;
  10631. } catch (error) {
  10632. throwError(error, 'link2id');
  10633. return i18n('getFailed', 'id');
  10634. }
  10635. };
  10636. const disabledType = {
  10637. steam: [ 'workshopVotes', 'curatorLikes', 'announcements' ],
  10638. twitter: [ 'likes' ]
  10639. };
  10640. const assignWhiteList = whiteList => {
  10641. try {
  10642. const newWhiteList = {};
  10643. for (const [ key, value ] of Object.entries(defaultWhiteList)) {
  10644. newWhiteList[key] = {
  10645. ...value,
  10646. ...whiteList[key]
  10647. };
  10648. }
  10649. return newWhiteList;
  10650. } catch (error) {
  10651. throwError(error, 'assignWhiteList');
  10652. return defaultWhiteList;
  10653. }
  10654. };
  10655. const whiteListOptions = function(showType) {
  10656. try {
  10657. const whiteList = assignWhiteList(GM_getValue('whiteList') || {});
  10658. let whiteListOptionsForm = `<form id="whiteListForm" class="auto-task-form">
  10659. <table class="auto-task-table"><thead><tr><td>${i18n('website')}</td><td>${i18n('type')}</td><td>${i18n('edit')}</td></tr></thead><tbody>`;
  10660. for (const [ social, types ] of Object.entries(whiteList)) {
  10661. 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('');
  10662. }
  10663. whiteListOptionsForm += '</tbody></table></form>';
  10664. if (showType === 'swal') {
  10665. external_Swal_default().fire({
  10666. title: i18n('whiteListOptions'),
  10667. html: whiteListOptionsForm,
  10668. showConfirmButton: false,
  10669. showCloseButton: true
  10670. });
  10671. } else {
  10672. $('body').append(`<h2>${i18n('whiteList')}</h2>${whiteListOptionsForm}`);
  10673. }
  10674. $('.editWhiteList').on('click', function() {
  10675. const value = $(this).attr('data-value');
  10676. if (!value) {
  10677. return;
  10678. }
  10679. const [ social, type ] = value.split('.');
  10680. if (!whiteList?.[social]?.[type]) {
  10681. scripts_echoLog({}).warning(i18n('whiteListNotFound', value));
  10682. return;
  10683. }
  10684. external_Swal_default().fire({
  10685. title: i18n('changeWhiteListOption', value),
  10686. input: 'textarea',
  10687. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10688. <button id="link2id" data-type="${value}" class="swal2-confirm swal2-styled">获取id</button>
  10689. <p style="margin-bottom:0 !important;">在下方填写白名单,每行一个</p>`,
  10690. inputValue: whiteList[social][type].join('\n'),
  10691. showConfirmButton: true,
  10692. confirmButtonText: i18n('save'),
  10693. showCancelButton: true,
  10694. cancelButtonText: i18n('close'),
  10695. showDenyButton: true,
  10696. denyButtonText: i18n('return')
  10697. }).then(({
  10698. isDenied,
  10699. isConfirmed,
  10700. value
  10701. }) => {
  10702. if (isDenied) {
  10703. if (showType === 'swal') {
  10704. whiteListOptions(showType);
  10705. }
  10706. return;
  10707. } else if (isConfirmed) {
  10708. whiteList[social][type] = value.split('\n');
  10709. GM_setValue('whiteList', whiteList);
  10710. external_Swal_default().fire({
  10711. title: i18n('changeWhiteListSuccess'),
  10712. icon: 'success'
  10713. });
  10714. }
  10715. });
  10716. $('#link2id').on('click', async function() {
  10717. const type = $(this).attr('data-type');
  10718. $('#socialLink').val(await link2id(type));
  10719. });
  10720. });
  10721. } catch (error) {
  10722. throwError(error, 'whiteListOptions');
  10723. }
  10724. };
  10725. const whiteList = whiteListOptions;
  10726. const setGistData = async (token, gistId, fileName, content) => {
  10727. try {
  10728. const logStatus = scripts_echoLog({
  10729. text: i18n('settingData')
  10730. });
  10731. const contentData = JSON.stringify({
  10732. files: {
  10733. [fileName]: {
  10734. content: JSON.stringify(content)
  10735. }
  10736. }
  10737. });
  10738. const {
  10739. result,
  10740. statusText,
  10741. status,
  10742. data
  10743. } = await tools_httpRequest({
  10744. url: `https://api.github.com/gists/${gistId}`,
  10745. headers: {
  10746. Accept: 'application/vnd.github.v3+json',
  10747. Authorization: `token ${token}`
  10748. },
  10749. data: contentData,
  10750. responseType: 'json',
  10751. method: 'POST',
  10752. timeout: 3e4
  10753. });
  10754. if (result === 'Success') {
  10755. if (data?.status === 200 && data.response.files?.[fileName]?.content === JSON.stringify(content)) {
  10756. logStatus.success();
  10757. return true;
  10758. }
  10759. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10760. return false;
  10761. }
  10762. logStatus.error(`${result}:${statusText}(${status})`);
  10763. return false;
  10764. } catch (error) {
  10765. throwError(error, 'setGistData');
  10766. return false;
  10767. }
  10768. };
  10769. const getGistData = async (token, gistId, fileName, test = false) => {
  10770. try {
  10771. const logStatus = scripts_echoLog({
  10772. text: i18n('gettingData')
  10773. });
  10774. const {
  10775. result,
  10776. statusText,
  10777. status,
  10778. data
  10779. } = await tools_httpRequest({
  10780. url: `https://api.github.com/gists/${gistId}`,
  10781. headers: {
  10782. Accept: 'application/vnd.github.v3+json',
  10783. Authorization: `token ${token}`
  10784. },
  10785. responseType: 'json',
  10786. method: 'GET',
  10787. timeout: 3e4
  10788. });
  10789. if (result === 'Success') {
  10790. if (data?.status === 200) {
  10791. const content = data.response?.files?.[fileName]?.content;
  10792. let formatedContent;
  10793. if (!content) {
  10794. logStatus.error(`Error:${i18n('noRemoteData')}`);
  10795. return false;
  10796. }
  10797. if (test) {
  10798. logStatus.success();
  10799. return true;
  10800. }
  10801. try {
  10802. formatedContent = JSON.parse(content);
  10803. } catch (error) {
  10804. logStatus.error(`Error:${i18n('errorRemoteDataFormat')}`);
  10805. return false;
  10806. }
  10807. logStatus.success();
  10808. return formatedContent;
  10809. }
  10810. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10811. return false;
  10812. }
  10813. logStatus.error(`${result}:${statusText}(${status})`);
  10814. return false;
  10815. } catch (error) {
  10816. throwError(error, 'getGistData');
  10817. return false;
  10818. }
  10819. };
  10820. const syncOptions = () => {
  10821. try {
  10822. const {
  10823. TOKEN,
  10824. GIST_ID,
  10825. FILE_NAME,
  10826. SYNC_HISTORY
  10827. } = GM_getValue('gistOptions') || {
  10828. TOKEN: '',
  10829. GIST_ID: '',
  10830. FILE_NAME: '',
  10831. SYNC_HISTORY: true
  10832. };
  10833. external_Swal_default().fire({
  10834. title: i18n('gistOptions'),
  10835. 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;">
  10836. ${i18n('upload2gist')}</button>` + `<button id="download-data" type="button" class="swal2-confirm swal2-styled" style="display: inline-block;">
  10837. ${i18n('downloadFromGist')}</button></p>`,
  10838. focusConfirm: false,
  10839. showLoaderOnConfirm: true,
  10840. 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>`,
  10841. preConfirm: async () => {
  10842. const token = $('#github-token').val();
  10843. const gistId = $('#gist-id').val();
  10844. const fileName = $('#file-name').val();
  10845. const syncHistory = $('#sync-history').prop('checked');
  10846. GM_setValue('gistOptions', {
  10847. TOKEN: token,
  10848. GIST_ID: gistId,
  10849. FILE_NAME: fileName,
  10850. SYNC_HISTORY: syncHistory
  10851. });
  10852. return await getGistData(token, gistId, fileName, true);
  10853. },
  10854. allowOutsideClick: () => !external_Swal_default().isLoading(),
  10855. confirmButtonText: i18n('saveAndTest'),
  10856. showCancelButton: true,
  10857. cancelButtonText: i18n('close')
  10858. }).then(({
  10859. value
  10860. }) => {
  10861. if (value) {
  10862. external_Swal_default().fire({
  10863. icon: 'success',
  10864. title: i18n('testSuccess')
  10865. }).then(syncOptions);
  10866. } else if (value !== undefined) {
  10867. external_Swal_default().fire({
  10868. icon: 'error',
  10869. title: i18n('testFailed')
  10870. }).then(syncOptions);
  10871. }
  10872. });
  10873. $('#upload-data').on('click', async () => {
  10874. const {
  10875. TOKEN,
  10876. GIST_ID,
  10877. FILE_NAME
  10878. } = GM_getValue('gistOptions') || {};
  10879. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10880. return external_Swal_default().fire({
  10881. icon: 'error',
  10882. title: i18n('saveAndTestNotice')
  10883. }).then(syncOptions);
  10884. }
  10885. external_Swal_default().fire({
  10886. icon: 'info',
  10887. title: i18n('processingData')
  10888. });
  10889. const data = {};
  10890. const names = GM_listValues();
  10891. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10892. for (const name of names) {
  10893. if (name === 'gistOptions' || /^[\w]+?Auth$/.test(name)) {
  10894. continue;
  10895. }
  10896. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10897. continue;
  10898. }
  10899. data[name] = GM_getValue(name);
  10900. }
  10901. external_Swal_default().update({
  10902. icon: 'info',
  10903. title: i18n('updatingData')
  10904. });
  10905. if (await setGistData(TOKEN, GIST_ID, FILE_NAME, data)) {
  10906. external_Swal_default().fire({
  10907. icon: 'success',
  10908. title: i18n('syncDataSuccess')
  10909. });
  10910. } else {
  10911. external_Swal_default().fire({
  10912. icon: 'error',
  10913. title: i18n('syncDataFailed')
  10914. });
  10915. }
  10916. });
  10917. $('#download-data').on('click', async () => {
  10918. const {
  10919. TOKEN,
  10920. GIST_ID,
  10921. FILE_NAME
  10922. } = GM_getValue('gistOptions') || {};
  10923. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  10924. return external_Swal_default().fire({
  10925. icon: 'error',
  10926. title: i18n('saveAndTestNotice')
  10927. }).then(syncOptions);
  10928. }
  10929. external_Swal_default().fire({
  10930. icon: 'info',
  10931. title: i18n('downloadingData')
  10932. });
  10933. const data = await getGistData(TOKEN, GIST_ID, FILE_NAME);
  10934. if (!data) {
  10935. return external_Swal_default().fire({
  10936. icon: 'error',
  10937. title: i18n('checkedNoData')
  10938. }).then(syncOptions);
  10939. }
  10940. external_Swal_default().update({
  10941. icon: 'info',
  10942. title: i18n('savingData')
  10943. });
  10944. const SYNC_HISTORY = $('#sync-history').prop('checked');
  10945. for (const [ name, value ] of Object.entries(data)) {
  10946. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  10947. continue;
  10948. }
  10949. GM_setValue(name, value);
  10950. }
  10951. external_Swal_default().fire({
  10952. icon: 'success',
  10953. title: i18n('syncDataSuccess')
  10954. });
  10955. });
  10956. } catch (error) {
  10957. throwError(error, 'syncOptions');
  10958. }
  10959. };
  10960. const dataSync = syncOptions;
  10961. class Setting {
  10962. name = 'Setting';
  10963. buttons = [ 'saveGlobalOptions', 'syncData', 'tasksHistory' ];
  10964. syncData = dataSync;
  10965. tasksHistory() {
  10966. GM_openInTab('https://auto-task-v4.hclonely.com/history.html', {
  10967. active: true
  10968. });
  10969. }
  10970. static test() {
  10971. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/setting.html';
  10972. }
  10973. before() {
  10974. try {
  10975. $('body').html('').addClass('auto-task-options');
  10976. } catch (error) {
  10977. throwError(error, 'Setting.before');
  10978. }
  10979. }
  10980. after() {
  10981. try {
  10982. this.#environment();
  10983. changeGlobalOptions('page');
  10984. whiteList('page');
  10985. $('input[name="other.twitterVerifyId"]').after(`<button id="getTwitterUserId" type="button">${i18n('getTwitterUserId')}</button>`);
  10986. $('#getTwitterUserId').on('click', () => {
  10987. this.#getId('twitterUser');
  10988. });
  10989. $('input[name="other.youtubeVerifyChannel"]').after(`<button id="getYoutubeChannelId" type="button">${i18n('getYoutubeChannelId')}</button>`);
  10990. $('#getYoutubeChannelId').on('click', () => {
  10991. this.#getId('youtubeChannel');
  10992. });
  10993. $('input[name^="position"]').on('input', function() {
  10994. const type = $(this).attr('name').replace('position.', '');
  10995. const xLabel = 'rightleft';
  10996. const yLabel = 'topbottpm';
  10997. switch (type) {
  10998. case 'buttonSideX':
  10999. case 'buttonSideY':
  11000. case 'buttonDistance':
  11001. {
  11002. const distance = $('input[name="position.buttonDistance"]').val();
  11003. const sideX = $('input[name="position.buttonSideX"]').val();
  11004. const sideY = $('input[name="position.buttonSideY"]').val();
  11005. if (![ 'right', 'left' ].includes(sideX)) {
  11006. break;
  11007. }
  11008. if (![ 'top', 'bottom' ].includes(sideY)) {
  11009. break;
  11010. }
  11011. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  11012. break;
  11013. }
  11014. const distanceArr = distance.split(',');
  11015. $('#auto-task-buttons').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  11016. break;
  11017. }
  11018.  
  11019. case 'showButtonSideX':
  11020. case 'showButtonSideY':
  11021. case 'showButtonDistance':
  11022. {
  11023. const distance = $('input[name="position.showButtonDistance"]').val();
  11024. const sideX = $('input[name="position.showButtonSideX"]').val();
  11025. const sideY = $('input[name="position.showButtonSideY"]').val();
  11026. if (![ 'right', 'left' ].includes(sideX)) {
  11027. break;
  11028. }
  11029. if (![ 'top', 'bottom' ].includes(sideY)) {
  11030. break;
  11031. }
  11032. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  11033. break;
  11034. }
  11035. const distanceArr = distance.split(',');
  11036. $('div.show-button-div').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  11037. break;
  11038. }
  11039.  
  11040. case 'logSideX':
  11041. case 'logSideY':
  11042. case 'logDistance':
  11043. {
  11044. const distance = $('input[name="position.logDistance"]').val();
  11045. const sideX = $('input[name="position.logSideX"]').val();
  11046. const sideY = $('input[name="position.logSideY"]').val();
  11047. if (![ 'right', 'left' ].includes(sideX)) {
  11048. break;
  11049. }
  11050. if (![ 'top', 'bottom' ].includes(sideY)) {
  11051. break;
  11052. }
  11053. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  11054. break;
  11055. }
  11056. const distanceArr = distance.split(',');
  11057. $('#auto-task-info').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  11058. break;
  11059. }
  11060.  
  11061. default:
  11062. break;
  11063. }
  11064. });
  11065. $('input[name^="hotKey"]').attr('readonly', 'readonly').off('keydown').on('keydown', function(event) {
  11066. let functionKey = '';
  11067. if (event.altKey) {
  11068. functionKey += 'alt + ';
  11069. } else if (event.ctrlKey) {
  11070. functionKey += 'ctrl + ';
  11071. } else if (event.shiftKey) {
  11072. functionKey += 'shift + ';
  11073. }
  11074. $(this).val(functionKey + (event.key.length === 1 ? event.key.toLowerCase() : ''));
  11075. });
  11076. } catch (error) {
  11077. throwError(error, 'Setting.after');
  11078. }
  11079. }
  11080. saveGlobalOptions() {
  11081. try {
  11082. saveData();
  11083. } catch (error) {
  11084. throwError(error, 'Setting.saveGlobalOptions');
  11085. }
  11086. }
  11087. #getId(social) {
  11088. try {
  11089. external_Swal_default().fire({
  11090. title: i18n('getId', i18n(social)),
  11091. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  11092. <button id="link2id" data-type="${social}" class="swal2-confirm swal2-styled">获取id</button>`,
  11093. showCancelButton: true,
  11094. cancelButtonText: i18n('close'),
  11095. showConfirmButton: false
  11096. });
  11097. $('#link2id').on('click', async function() {
  11098. const link = $('#socialLink').val();
  11099. if (!link) {
  11100. return;
  11101. }
  11102. const type = $(this).attr('data-type');
  11103. if (type === 'twitterUser') {
  11104. const name = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || link;
  11105. $('#socialLink').val(await new social_Twitter().userName2id(name) || '');
  11106. } else if (type === 'youtubeChannel') {
  11107. const name = /^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www.youtube.com\/.*/.test(link) ? link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1] : link;
  11108. $('#socialLink').val((await getInfo(name, 'channel'))?.params?.channelId || '');
  11109. }
  11110. });
  11111. } catch (error) {
  11112. throwError(error, 'Setting.getId');
  11113. }
  11114. }
  11115. #environment() {
  11116. try {
  11117. const userAgent = (0, javascript_utils_umd_min.ua)();
  11118. const environmentForm = `<form id="environmentForm" class="auto-task-form">
  11119. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('name')}</td><td>${i18n('version')}</td></tr></thead><tbody>
  11120. <tr><td>${i18n('os')}</td><td>${userAgent.os}</td><td>${userAgent.osVersion}</td></tr>
  11121. <tr><td>${i18n('browser')}</td><td>${userAgent.browserZH}</td><td>${userAgent.browserVersion}</td></tr>
  11122. <tr><td>${i18n('scriptManager')}</td><td>${GM_info.scriptHandler}</td><td>${GM_info.version}</td></tr>
  11123. <tr><td>${i18n('script')}</td><td>${GM_info.script.name}</td><td>${GM_info.script.version}</td></tr>
  11124. </tbody></table></form>`;
  11125. $('body').append(`<h2>${i18n('environment')}</h2>${environmentForm}`);
  11126. } catch (error) {
  11127. throwError(error, 'Setting.environment');
  11128. }
  11129. }
  11130. }
  11131. const website_Setting = Setting;
  11132. class History extends website_Keylol {
  11133. name = 'History';
  11134. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect', 'clearHistory' ];
  11135. static test() {
  11136. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/history.html';
  11137. }
  11138. before() {
  11139. try {
  11140. $('body').html('<div class="container"></div>').addClass('auto-task-history');
  11141. const data = GM_listValues() || [];
  11142. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  11143. for (const item of tasksHistory) {
  11144. this.#addItem(item);
  11145. }
  11146. } catch (error) {
  11147. throwError(error, 'History.before');
  11148. }
  11149. }
  11150. clearHistory() {
  11151. try {
  11152. const data = GM_listValues() || [];
  11153. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  11154. for (const item of tasksHistory) {
  11155. GM_deleteValue(item);
  11156. }
  11157. external_Swal_default().fire({
  11158. title: i18n('clearHistoryFinished'),
  11159. icon: 'success'
  11160. });
  11161. } catch (error) {
  11162. throwError(error, 'History.clearHistory');
  11163. }
  11164. }
  11165. #addItem(item) {
  11166. try {
  11167. const tasksData = GM_getValue(item);
  11168. if (!tasksData?.tasks) {
  11169. return;
  11170. }
  11171. let html = '';
  11172. let title = '';
  11173. let link = '';
  11174. const [ website, id ] = item.split('-');
  11175. switch (website) {
  11176. case 'fawTasks':
  11177. title = `Freeanywhere[${id}]`;
  11178. link = `https://freeanywhere.net/#/giveaway/${id}`;
  11179. break;
  11180.  
  11181. case 'gasTasks':
  11182. title = `Giveawaysu[${id}]`;
  11183. link = `https://giveaway.su/giveaway/view/${id}`;
  11184. break;
  11185.  
  11186. case 'gcTasks':
  11187. title = `GiveeClub[${id}]`;
  11188. link = `https://givee.club/event/${id}`;
  11189. break;
  11190.  
  11191. case 'gkTasks':
  11192. title = `Givekey[${id}]`;
  11193. link = `https://givekey.ru/giveaway/${id}`;
  11194. break;
  11195.  
  11196. case 'gleamTasks':
  11197. title = `Gleam[${id}]`;
  11198. link = `https://gleam.io${id}`;
  11199. break;
  11200.  
  11201. case 'khTasks':
  11202. title = `keyhub[${id}]`;
  11203. link = `https://key-hub.eu/giveaway/${id}`;
  11204. break;
  11205.  
  11206. case 'prysTasks':
  11207. title = `Prys[${id}]`;
  11208. link = `https://prys.revadike.com/giveaway/?id=${id}`;
  11209. break;
  11210.  
  11211. default:
  11212. return;
  11213. }
  11214. for (const [ social, types ] of Object.entries(tasksData.tasks)) {
  11215. for (const [ type, tasks ] of Object.entries(types)) {
  11216. for (const task of tasks) {
  11217. 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>`;
  11218. }
  11219. }
  11220. }
  11221. $('.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>`);
  11222. $('span.delete-task').on('click', function() {
  11223. const itemName = $(this).attr('data-name');
  11224. if (itemName) {
  11225. GM_deleteValue(itemName);
  11226. $(`div.card[data-name="${itemName}"]`).remove();
  11227. external_Swal_default().fire({
  11228. title: i18n('clearTaskFinished'),
  11229. text: itemName,
  11230. icon: 'success'
  11231. });
  11232. } else {
  11233. external_Swal_default().fire({
  11234. title: i18n('clearTaskFailed'),
  11235. icon: 'error'
  11236. });
  11237. }
  11238. });
  11239. } catch (error) {
  11240. throwError(error, 'History.addItem');
  11241. }
  11242. }
  11243. }
  11244. const website_History = History;
  11245. const GiveawayHopper_defaultTasksTemplate = {
  11246. steam: {
  11247. groupLinks: [],
  11248. wishlistLinks: [],
  11249. followLinks: [],
  11250. curatorLinks: [],
  11251. curatorLikeLinks: []
  11252. },
  11253. twitter: {
  11254. userLinks: [],
  11255. retweetLinks: []
  11256. },
  11257. twitch: {
  11258. channelLinks: []
  11259. },
  11260. discord: {
  11261. serverLinks: []
  11262. },
  11263. youtube: {
  11264. channelLinks: []
  11265. },
  11266. extra: {
  11267. giveawayHopper: []
  11268. }
  11269. };
  11270. const GiveawayHopper_defaultTasks = JSON.stringify(GiveawayHopper_defaultTasksTemplate);
  11271. class GiveawayHopper extends website_Website {
  11272. name = 'GiveawayHopper';
  11273. undoneTasks = JSON.parse(GiveawayHopper_defaultTasks);
  11274. socialTasks = JSON.parse(GiveawayHopper_defaultTasks);
  11275. tasks = [];
  11276. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  11277. static test() {
  11278. return window.location.host === 'giveawayhopper.com';
  11279. }
  11280. async after() {
  11281. try {
  11282. if (!this.#checkLogin()) {
  11283. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  11284. }
  11285. this.#getGiveawayId();
  11286. } catch (error) {
  11287. throwError(error, 'GiveawayHopper.after');
  11288. }
  11289. }
  11290. async init() {
  11291. try {
  11292. const logStatus = scripts_echoLog({
  11293. text: i18n('initing')
  11294. });
  11295. if (!await this.#checkLeftKey()) {
  11296. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  11297. }
  11298. this.initialized = true;
  11299. logStatus.success();
  11300. return true;
  11301. } catch (error) {
  11302. throwError(error, 'GiveawayHopper.init');
  11303. return false;
  11304. }
  11305. }
  11306. async classifyTask(action) {
  11307. try {
  11308. if (!this.giveawayId) {
  11309. await this.#getGiveawayId();
  11310. }
  11311. const logStatus = scripts_echoLog({
  11312. text: i18n('getTasksInfo')
  11313. });
  11314. if (action === 'undo') {
  11315. this.socialTasks = GM_getValue(`giveawayHopperTasks-${this.giveawayId}`)?.tasks || JSON.parse(GiveawayHopper_defaultTasks);
  11316. }
  11317. const {
  11318. result,
  11319. statusText,
  11320. status,
  11321. data
  11322. } = await tools_httpRequest({
  11323. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/with-auth`,
  11324. method: 'GET',
  11325. responseType: 'json',
  11326. fetch: true,
  11327. headers: {
  11328. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  11329. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  11330. }
  11331. });
  11332. if (result === 'Success') {
  11333. if (data?.status === 200 && data?.response?.tasks) {
  11334. this.tasks = data.response.tasks;
  11335. for (const task of data.response.tasks) {
  11336. if (task.isDone) {
  11337. continue;
  11338. }
  11339. await tools_httpRequest({
  11340. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/visited`,
  11341. method: 'GET',
  11342. responseType: 'json',
  11343. fetch: true,
  11344. headers: {
  11345. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  11346. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  11347. }
  11348. });
  11349. if (task.category === 'Steam' && task.type === 'JoinGroup') {
  11350. const steamGroupLink = await getRedirectLink(`https://steamcommunity.com/gid/${task.group_id}`);
  11351. if (!steamGroupLink) {
  11352. continue;
  11353. }
  11354. if (action === 'undo') {
  11355. this.socialTasks.steam.groupLinks.push(steamGroupLink);
  11356. }
  11357. if (action === 'do') {
  11358. this.undoneTasks.steam.groupLinks.push(steamGroupLink);
  11359. }
  11360. continue;
  11361. }
  11362. if (task.category === 'Discord' && task.type === 'JoinServer') {
  11363. if (action === 'undo') {
  11364. this.socialTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  11365. }
  11366. if (action === 'do') {
  11367. this.undoneTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  11368. }
  11369. continue;
  11370. }
  11371. if ([ 'TikTok', 'YouTube', 'General' ].includes(task.category)) {
  11372. continue;
  11373. }
  11374. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${task.category}-${task.type}`);
  11375. }
  11376. logStatus.success();
  11377. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  11378. this.socialTasks = this.uniqueTasks(this.socialTasks);
  11379. if (window.DEBUG) {
  11380. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  11381. }
  11382. GM_setValue(`giveawayHopperTasks-${this.giveawayId}`, {
  11383. tasks: this.socialTasks,
  11384. time: new Date().getTime()
  11385. });
  11386. return true;
  11387. }
  11388. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  11389. return false;
  11390. }
  11391. logStatus.error(`${result}:${statusText}(${status})`);
  11392. return false;
  11393. } catch (error) {
  11394. throwError(error, 'GiveawayHopper.classifyTask');
  11395. return false;
  11396. }
  11397. }
  11398. async verifyTask() {
  11399. try {
  11400. for (const task of this.tasks) {
  11401. if (task.isDone) {
  11402. continue;
  11403. }
  11404. const logStatus = scripts_echoLog({
  11405. text: `${i18n('verifyingTask')}[${task.displayName?.replace(':target', task.targetName) || task.name}]...`
  11406. });
  11407. if (!task.link) {
  11408. if (task.category === 'YouTube' && task.type === 'FollowAccount') {
  11409. task.link = `https://www.youtube.com/@${task.targetName}`;
  11410. } else if (task.category === 'TikTok' && task.type === 'FollowAccount') {
  11411. task.link = `https://www.tiktok.com/@${task.targetName}`;
  11412. } else if (task.category === 'Steam' && task.type === 'JoinGroup') {
  11413. task.link = '';
  11414. } else if (task.category === 'Discord' && task.type === 'JoinServer') {
  11415. task.link = '';
  11416. }
  11417. }
  11418. if (task.link) {
  11419. await tools_httpRequest({
  11420. 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}`,
  11421. method: 'GET',
  11422. fetch: true,
  11423. headers: {
  11424. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  11425. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  11426. }
  11427. });
  11428. }
  11429. await delay(1e3);
  11430. const postData = {
  11431. taskcategory: task.category,
  11432. taskname: task.type
  11433. };
  11434. if ([ 'YouTube', 'TikTok' ].includes(task.category)) {
  11435. postData.username = '1';
  11436. }
  11437. const {
  11438. result,
  11439. statusText,
  11440. status,
  11441. data
  11442. } = await tools_httpRequest({
  11443. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/complete`,
  11444. method: 'POST',
  11445. fetch: true,
  11446. headers: {
  11447. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  11448. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1]),
  11449. 'content-type': 'application/json'
  11450. },
  11451. dataType: 'json',
  11452. data: JSON.stringify(postData)
  11453. });
  11454. if (result === 'Success') {
  11455. if (data?.status === 200 && data?.response?.completed) {
  11456. logStatus.success();
  11457. continue;
  11458. }
  11459. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  11460. continue;
  11461. }
  11462. logStatus.error(`${result}:${statusText}(${status})`);
  11463. continue;
  11464. }
  11465. } catch (error) {
  11466. throwError(error, 'GiveawayHopper.verifyTask');
  11467. return false;
  11468. }
  11469. }
  11470. #getGiveawayId() {
  11471. try {
  11472. const giveawayId = window.location.pathname.split('/').at(-1);
  11473. if (giveawayId) {
  11474. this.giveawayId = giveawayId;
  11475. return true;
  11476. }
  11477. scripts_echoLog({
  11478. text: i18n('getFailed', 'GiveawayId')
  11479. });
  11480. return false;
  11481. } catch (error) {
  11482. throwError(error, 'GiveawayHopper.getGiveawayId');
  11483. return false;
  11484. }
  11485. }
  11486. #checkLogin() {
  11487. try {
  11488. if (!globalOptions.other.checkLogin) {
  11489. return true;
  11490. }
  11491. if ($('div.widget-connections-edit:contains("Log in")').length > 0) {
  11492. $('div.widget-connections-edit:contains("Log in") a')[0].click();
  11493. }
  11494. return true;
  11495. } catch (error) {
  11496. throwError(error, 'GiveawayHopper.checkLogin');
  11497. return false;
  11498. }
  11499. }
  11500. async #checkLeftKey() {
  11501. try {
  11502. if (!globalOptions.other.checkLeftKey) {
  11503. return true;
  11504. }
  11505. if ($('p.widget-single-prize span').length > 0 && parseInt($('p.widget-single-prize span').text()?.match(/\d+/)?.[0] || '0', 10) > 0) {
  11506. return true;
  11507. }
  11508. await external_Swal_default().fire({
  11509. icon: 'warning',
  11510. title: i18n('notice'),
  11511. text: i18n('noKeysLeft'),
  11512. confirmButtonText: i18n('confirm'),
  11513. cancelButtonText: i18n('cancel'),
  11514. showCancelButton: true
  11515. }).then(({
  11516. value
  11517. }) => {
  11518. if (value) {
  11519. window.close();
  11520. }
  11521. });
  11522. return true;
  11523. } catch (error) {
  11524. throwError(error, 'GiveawayHopper.checkLeftKey');
  11525. return false;
  11526. }
  11527. }
  11528. }
  11529. const website_GiveawayHopper = GiveawayHopper;
  11530. 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 ];
  11531. const websiteOptions = function(website, options) {
  11532. try {
  11533. let websiteOptionsForm = `<form id="websiteOptionsForm" class="auto-task-form">
  11534. <table class="auto-task-table"><thead><tr><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  11535. for (const [ option, value ] of Object.entries(options)) {
  11536. websiteOptionsForm += `<tr><td>${option}</td><td><input class="editOption" type="text" name="${option}" value="${value}"/></td></tr>`;
  11537. }
  11538. websiteOptionsForm += '</tbody></table></form>';
  11539. external_Swal_default().fire({
  11540. title: i18n('websiteOptions'),
  11541. html: websiteOptionsForm,
  11542. showConfirmButton: true,
  11543. confirmButtonText: i18n('save'),
  11544. showCancelButton: true,
  11545. cancelButtonText: i18n('close')
  11546. }).then(({
  11547. isConfirmed
  11548. }) => {
  11549. if (isConfirmed) {
  11550. $('#websiteOptionsForm').serializeArray().map(value => {
  11551. options[value.name] = value.value;
  11552. return value;
  11553. });
  11554. GM_setValue(`${website}Options`, options);
  11555. external_Swal_default().fire({
  11556. title: i18n('changeWebsiteOptionsSuccess'),
  11557. icon: 'success'
  11558. });
  11559. }
  11560. });
  11561. } catch (error) {
  11562. throwError(error, 'websiteOptions');
  11563. }
  11564. };
  11565. const options = websiteOptions;
  11566. const external_keyboardJS_namespaceObject = keyboardJS;
  11567. var external_keyboardJS_default = __webpack_require__.n(external_keyboardJS_namespaceObject);
  11568. const checkUpdate = async (updateLink, auto) => {
  11569. try {
  11570. const checkUrl = `${updateLink}package.json?time=${new Date().getTime()}`;
  11571. const {
  11572. result,
  11573. statusText,
  11574. status,
  11575. data
  11576. } = await tools_httpRequest({
  11577. url: checkUrl,
  11578. responseType: 'json',
  11579. method: 'GET',
  11580. timeout: 3e4
  11581. });
  11582. if (result === 'Success') {
  11583. if (data?.response?.version) {
  11584. return data.response;
  11585. }
  11586. if (!auto) {
  11587. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${data?.statusText}(${data?.status})]`);
  11588. }
  11589. return false;
  11590. }
  11591. if (!auto) {
  11592. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${result}:${statusText}(${status})]`);
  11593. }
  11594. return false;
  11595. } catch (error) {
  11596. throwError(error, 'checkUpdate');
  11597. return false;
  11598. }
  11599. };
  11600. const hasNewVersion = (currentVersion, remoteVersion) => {
  11601. try {
  11602. const [ currentRealVersion ] = currentVersion.split('-');
  11603. const [ remoteRealVersion, isPreview ] = remoteVersion.split('-');
  11604. if (isPreview && !globalOptions.other.receivePreview) {
  11605. return false;
  11606. }
  11607. const [ currentVersion1, currentVersion2, currentVersion3 ] = currentRealVersion.split('.').map(value => parseInt(value, 10));
  11608. const [ remoteVersion1, remoteVersion2, remoteVersion3 ] = remoteRealVersion.split('.').map(value => parseInt(value, 10));
  11609. if (remoteVersion1 > currentVersion1) {
  11610. return true;
  11611. }
  11612. if (remoteVersion1 < currentVersion1) {
  11613. return false;
  11614. }
  11615. if (remoteVersion2 > currentVersion2) {
  11616. return true;
  11617. }
  11618. if (remoteVersion2 < currentVersion2) {
  11619. return false;
  11620. }
  11621. if (remoteVersion3 > currentVersion3) {
  11622. return true;
  11623. }
  11624. return false;
  11625. } catch (error) {
  11626. throwError(error, 'compareVersion');
  11627. return false;
  11628. }
  11629. };
  11630. const updateChecker = async () => {
  11631. try {
  11632. const currentVersion = GM_info.script.version;
  11633. const updateSource = globalOptions.other.autoUpdateSource.toLowerCase();
  11634. const updateLinks = {
  11635. github: 'https://github.com/HCLonely/auto-task-new/raw/main/',
  11636. jsdelivr: 'https://cdn.jsdelivr.net/gh/HCLonely/auto-task-v4@main/',
  11637. standby: 'https://auto-task-v4.hclonely.com/'
  11638. };
  11639. let version;
  11640. let updateLink = '';
  11641. let packageData;
  11642. if ([ 'github', 'jsdelivr', 'standby' ].includes(updateSource)) {
  11643. updateLink = updateLinks[updateSource];
  11644. packageData = await checkUpdate(updateLink, false);
  11645. } else {
  11646. updateLink = updateLinks.github;
  11647. packageData = await checkUpdate(updateLink, true);
  11648. if (!packageData) {
  11649. updateLink = updateLinks.jsdelivr;
  11650. packageData = await checkUpdate(updateLink, true);
  11651. if (!packageData) {
  11652. updateLink = updateLinks.standby;
  11653. packageData = await checkUpdate(updateLink, true);
  11654. }
  11655. }
  11656. }
  11657. if (packageData) {
  11658. version = packageData.version || currentVersion;
  11659. } else {
  11660. version = currentVersion;
  11661. scripts_echoLog({}).error(i18n('checkUpdateFailed'));
  11662. }
  11663. if (packageData && hasNewVersion(currentVersion, version)) {
  11664. scripts_echoLog({
  11665. html: `<li><font>${i18n('newVersionNotice', version, `${updateLink}dist/${GM_info.script.name}.user.js`)}</font></li>`
  11666. });
  11667. scripts_echoLog({
  11668. html: `<li>${i18n('updateText', version)}</li><ol class="update-text">${packageData.change?.map(change => `<li>${change}</li>`).join('')}<li>${i18n('updateHistory')}</li></ol>`
  11669. });
  11670. }
  11671. } catch (error) {
  11672. throwError(error, 'updateChecker');
  11673. }
  11674. };
  11675. const scripts_updateChecker = updateChecker;
  11676. window.STYLE = GM_addStyle(auto_task.A + GM_getResourceText('style'));
  11677. window.DEBUG = !!globalOptions.other?.debug;
  11678. window.TRACE = !!globalOptions.other?.debug && typeof console.trace === 'function';
  11679. const loadScript = async () => {
  11680. if (window.name === 'ATv4_twitchAuth' && window.location.hostname === 'www.twitch.tv') {
  11681. const authToken = external_Cookies_default().get('auth-token');
  11682. const isLogin = !!external_Cookies_default().get('login');
  11683. if (isLogin) {
  11684. GM_setValue('twitchAuth', {
  11685. authToken: authToken,
  11686. clientVersion: __twilightBuildID,
  11687. clientId: commonOptions?.headers?.['Client-ID'],
  11688. deviceId: commonOptions?.headers?.['Device-ID'],
  11689. clientSessionId: window.localStorage.local_storage_app_session_id.replace(/"/g, '')
  11690. });
  11691. window.close();
  11692. external_Swal_default().fire('', i18n('closePageNotice'));
  11693. } else {
  11694. external_Swal_default().fire('', i18n('needLogin'));
  11695. }
  11696. return;
  11697. }
  11698. if (window.name === 'ATv4_redditAuth' && window.location.hostname === 'www.reddit.com') {
  11699. const betaButton = $('#redesign-beta-optin-btn');
  11700. if (betaButton.length > 0) {
  11701. return betaButton[0].click();
  11702. }
  11703. window.close();
  11704. external_Swal_default().fire('', i18n('closePageNotice'));
  11705. return;
  11706. }
  11707. let website;
  11708. for (const Website of Websites) {
  11709. if (Website.test()) {
  11710. website = new Website();
  11711. break;
  11712. }
  11713. }
  11714. if (!website) {
  11715. console.log('%c%s', 'color:#ff0000', 'Auto-Task[Warning]: 脚本停止加载,当前网站不支持!');
  11716. return;
  11717. }
  11718. if (website?.before) {
  11719. await website?.before();
  11720. }
  11721. $('body').append(`
  11722. <div id="auto-task-info"
  11723. style="display:${globalOptions.other.defaultShowLog ? 'block' : 'none'};
  11724. ${globalOptions.position.logSideX}:${globalOptions.position.logDistance.split(',')[0]}px;
  11725. ${globalOptions.position.logSideY}:${globalOptions.position.logDistance.split(',')[1]}px;">
  11726. </div>
  11727. <div id="auto-task-buttons"
  11728. style="display:${globalOptions.other.defaultShowButton ? 'block' : 'none'};
  11729. ${globalOptions.position.buttonSideX}:${globalOptions.position.buttonDistance.split(',')[0]}px;
  11730. ${globalOptions.position.buttonSideY}:${globalOptions.position.buttonDistance.split(',')[1]}px;">
  11731. </div>
  11732. <div class="show-button-div"
  11733. style="display:${globalOptions.other.defaultShowButton ? 'none' : 'block'};
  11734. ${globalOptions.position.showButtonSideX}:${globalOptions.position.showButtonDistance.split(',')[0]}px;
  11735. ${globalOptions.position.showButtonSideY}:${globalOptions.position.showButtonDistance.split(',')[1]}px;">
  11736. <a class="auto-task-website-btn"
  11737. href="javascript:void(0);"
  11738. target="_self"
  11739. title="${i18n('showButton')}"> </a>
  11740. </div>
  11741. `);
  11742. $('div.show-button-div').on('click', () => {
  11743. $('#auto-task-buttons').show();
  11744. $('div.show-button-div').hide();
  11745. });
  11746. const toggleLog = () => {
  11747. const $this = $('#toggle-log');
  11748. const status = $this.attr('data-status');
  11749. if (status === 'show') {
  11750. $('#auto-task-info').hide();
  11751. $this.attr('data-status', 'hide').text(i18n('showLog'));
  11752. } else {
  11753. $('#auto-task-info').show();
  11754. $this.attr('data-status', 'show').text(i18n('hideLog'));
  11755. }
  11756. };
  11757. external_keyboardJS_default().bind(globalOptions.hotKey.doTaskKey, () => {
  11758. if (website.doTask) {
  11759. website.doTask();
  11760. }
  11761. });
  11762. external_keyboardJS_default().bind(globalOptions.hotKey.undoTaskKey, () => {
  11763. if (website.undoTask) {
  11764. website.undoTask();
  11765. }
  11766. });
  11767. external_keyboardJS_default().bind(globalOptions.hotKey.toggleLogKey, toggleLog);
  11768. if (website?.after) {
  11769. await website?.after();
  11770. }
  11771. if (website?.buttons && $('#auto-task-buttons').children().length === 0) {
  11772. $('#auto-task-buttons').addClass(`${website.name}-buttons`);
  11773. for (const button of website.buttons) {
  11774. if (website[button]) {
  11775. const btnElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">${i18n(button)}</a></p>`);
  11776. btnElement.find('a.auto-task-website-btn').on('click', () => {
  11777. website[button]();
  11778. });
  11779. $('#auto-task-buttons').append(btnElement);
  11780. }
  11781. }
  11782. }
  11783. const hideButtonElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">
  11784. ${i18n('hideButton')}</a></p>`);
  11785. hideButtonElement.find('a.auto-task-website-btn').on('click', () => {
  11786. $('#auto-task-buttons').hide();
  11787. $('div.show-button-div').show();
  11788. });
  11789. 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'}">
  11790. ${globalOptions.other.defaultShowLog ? i18n('hideLog') : i18n('showLog')}</a></p>`);
  11791. toggleLogElement.find('a.auto-task-website-btn').on('click', toggleLog);
  11792. $('#auto-task-buttons').append(hideButtonElement).append(toggleLogElement);
  11793. if (website?.options) {
  11794. GM_registerMenuCommand(i18n('changeWebsiteOptions'), () => {
  11795. options(website.name, website.options);
  11796. });
  11797. }
  11798. if (website.name !== 'Setting') {
  11799. GM_registerMenuCommand(i18n('changeGlobalOptions'), () => {
  11800. changeGlobalOptions('swal');
  11801. });
  11802. GM_registerMenuCommand(i18n('settingPage'), () => {
  11803. GM_openInTab('https://auto-task-v4.hclonely.com/setting.html', {
  11804. active: true
  11805. });
  11806. });
  11807. }
  11808. console.log('%c%s', 'color:#1bbe1a', 'Auto-Task[Load]: 脚本加载完成');
  11809. const [ v1, v2 ] = GM_info.version?.split('.') || [];
  11810. if (!(parseInt(v1, 10) >= 5 && parseInt(v2, 10) >= 2)) {
  11811. scripts_echoLog({}).error(i18n('versionNotMatched'));
  11812. }
  11813. if (!GM_getValue('notice')) {
  11814. external_Swal_default().fire({
  11815. title: i18n('swalNotice'),
  11816. icon: 'warning'
  11817. }).then(() => {
  11818. GM_openInTab(i18n('noticeLink'), {
  11819. active: true
  11820. });
  11821. GM_setValue('notice', new Date().getTime());
  11822. });
  11823. scripts_echoLog({
  11824. html: `<li><font class="warning">${i18n('echoNotice', i18n('noticeLink'))}</font></li>`
  11825. }).font?.find('a').on('click', () => {
  11826. GM_setValue('notice', new Date().getTime());
  11827. });
  11828. }
  11829. scripts_updateChecker();
  11830. };
  11831. if (window.location.hostname === 'discord.com') {
  11832. const LocalStorage = window.localStorage;
  11833. if (window.name === 'ATv4_discordAuth') {
  11834. window.localStorage.removeItem = () => true;
  11835. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11836. if (discordAuth && discordAuth.length > 0) {
  11837. GM_setValue('discordAuth', {
  11838. auth: discordAuth
  11839. });
  11840. window.close();
  11841. external_Swal_default().fire('', i18n('closePageNotice'));
  11842. } else {
  11843. external_Swal_default().fire({
  11844. text: i18n('getDiscordAuthFailed'),
  11845. icon: 'error'
  11846. });
  11847. }
  11848. } else {
  11849. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  11850. if (discordAuth && discordAuth.length > 0) {
  11851. GM_setValue('discordAuth', {
  11852. auth: discordAuth
  11853. });
  11854. }
  11855. }
  11856. } else if (window.location.hostname === 'opquests.com') {
  11857. loadScript();
  11858. } else if ((window.name === 'ATv4_updateStoreAuth' || GM_getValue('ATv4_updateStoreAuth')) && window.location.host === 'store.steampowered.com') {
  11859. $(() => {
  11860. if ($('[data-miniprofile]').length === 0) {
  11861. return;
  11862. }
  11863. const storeSessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11864. if (storeSessionID) {
  11865. GM_deleteValue('ATv4_updateStoreAuth');
  11866. GM_setValue('steamStoreAuth', {
  11867. storeSessionID: storeSessionID
  11868. });
  11869. window.close();
  11870. external_Swal_default().fire('', i18n('closePageNotice'));
  11871. } else {
  11872. external_Swal_default().fire({
  11873. title: 'Error: Get "sessionID" failed',
  11874. icon: 'error'
  11875. });
  11876. }
  11877. });
  11878. } else if ((window.name === 'ATv4_updateCommunityAuth' || GM_getValue('ATv4_updateCommunityAuth')) && window.location.host === 'steamcommunity.com') {
  11879. $(() => {
  11880. const steam64Id = document.body.innerHTML.match(/g_steamID = "(.+?)";/)?.[1];
  11881. const communitySessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  11882. if (steam64Id && communitySessionID) {
  11883. GM_deleteValue('ATv4_updateCommunityAuth');
  11884. GM_setValue('steamCommunityAuth', {
  11885. steam64Id: steam64Id,
  11886. communitySessionID: communitySessionID
  11887. });
  11888. window.close();
  11889. external_Swal_default().fire('', i18n('closePageNotice'));
  11890. } else {
  11891. setTimeout(() => {
  11892. external_Swal_default().fire({
  11893. title: 'Error: Get "sessionID" failed',
  11894. icon: 'error'
  11895. });
  11896. }, 3e3);
  11897. }
  11898. });
  11899. } else {
  11900. if (window.location.hostname === 'key-hub.eu') {
  11901. unsafeWindow.keyhubtracker = 1;
  11902. unsafeWindow.gaData = {};
  11903. }
  11904. $(loadScript);
  11905. }
  11906. }();
  11907. })();