auto-task-v4

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

  1. // ==UserScript==
  2. // @name auto-task-v4
  3. // @namespace auto-task-v4
  4. // @version 4.7.10
  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. getIndices,
  253. getAnimationKey
  254. } = __webpack_require__(702);
  255. const {
  256. generateTransactionId
  257. } = __webpack_require__(243);
  258. const {
  259. decodeBase64
  260. } = __webpack_require__(243);
  261. const {
  262. never
  263. } = __webpack_require__(727);
  264. const {
  265. decodeTransactionId
  266. } = __webpack_require__(791);
  267. const createSession = async () => {
  268. const raw = await axiosGM({
  269. url: 'https://x.com',
  270. method: 'GET',
  271. responseType: 'text'
  272. });
  273. const html = raw.data;
  274. const root = $.parseHTML(`<div>${html}</div>`)[0];
  275. const content = root.querySelector('[name^=tw]')?.getAttribute('content') ?? never('No content');
  276. const verification = decodeBase64(content);
  277. const frames = root.querySelectorAll('[id^=\'loading-x-anim\']');
  278. const svgArray = svgKey(verification, frames);
  279. const indexKey = await getIndices(html);
  280. const animationKey = getAnimationKey(svgArray, verification, indexKey);
  281. return {
  282. get: (method, path) => generateTransactionId(method, path, content, animationKey.join(''))
  283. };
  284. };
  285. const svgKey = (verification, frames) => {
  286. const index = verification[5] % 4;
  287. const path = frames[index].children[0].children[1];
  288. const d = path.getAttribute('d') ?? never('No d');
  289. const sub = d.substring(9).split('C');
  290. const res = sub.map(item => {
  291. return item.replace(/[^\d]+/g, ' ').trim().split(' ').map(Number);
  292. });
  293. return res;
  294. };
  295. module.exports = {
  296. createSession: createSession,
  297. generateTransactionId: generateTransactionId,
  298. decodeTransactionId: decodeTransactionId
  299. };
  300. },
  301. 601: function(module) {
  302. 'use strict';
  303. module.exports = function(i) {
  304. return i[1];
  305. };
  306. },
  307. 675: function(module, __webpack_exports__, __webpack_require__) {
  308. 'use strict';
  309. __webpack_require__.d(__webpack_exports__, {
  310. A: function() {
  311. return __WEBPACK_DEFAULT_EXPORT__;
  312. }
  313. });
  314. var _node_modules_css_loader_dist_runtime_noSourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(601);
  315. 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__);
  316. var _node_modules_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(314);
  317. 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__);
  318. 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());
  319. ___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}.swal2-modal #swal2-title{text-align:center !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}`, '' ]);
  320. const __WEBPACK_DEFAULT_EXPORT__ = ___CSS_LOADER_EXPORT___.toString();
  321. },
  322. 702: function(module, __unused_webpack_exports, __webpack_require__) {
  323. const {
  324. axiosGM
  325. } = __webpack_require__(945);
  326. const totalTime = 4096;
  327. const calculateScaledValue = (scalingFactor, baseValue, targetValue, roundToInteger) => {
  328. const result = scalingFactor * (targetValue - baseValue) / 255 + baseValue;
  329. return roundToInteger ? Math.floor(result) : Number(result.toFixed(2));
  330. };
  331. function interpolate(from, to, value) {
  332. const out = Array.from(from.length);
  333. for (let i = 0; i < from.length; i++) {
  334. out[i] = interpolateNum(from[i], to[i], value);
  335. }
  336. return out;
  337. }
  338. function interpolateNum(from, to, value) {
  339. return from * (1 - value) + to * value;
  340. }
  341. function convertRotationToMatrix(degrees) {
  342. const radians = degrees * Math.PI / 180;
  343. const c = Math.cos(radians).toFixed(6);
  344. const s = Math.sin(radians).toFixed(6);
  345. return [ c, s, -s, c, 0, 0 ];
  346. }
  347. function cubic(a, b, c, d) {
  348. if (a < 0 || a > 1 || c < 0 || c > 1) {
  349. return function(x) {
  350. return x;
  351. };
  352. }
  353. return function(x) {
  354. if (x <= 0) {
  355. var start_gradient = 0;
  356. if (a > 0) {
  357. start_gradient = b / a;
  358. } else if (!b && c > 0) {
  359. start_gradient = d / c;
  360. }
  361. return start_gradient * x;
  362. }
  363. if (x >= 1) {
  364. var end_gradient = 0;
  365. if (c < 1) {
  366. end_gradient = (d - 1) / (c - 1);
  367. } else if (c == 1 && a < 1) {
  368. end_gradient = (b - 1) / (a - 1);
  369. }
  370. return 1 + end_gradient * (x - 1);
  371. }
  372. var start = 0, end = 1;
  373. function f(a, b, m) {
  374. const _1_m = 1 - m;
  375. return 3 * a * _1_m * _1_m * m + 3 * b * _1_m * m * m + m * m * m;
  376. }
  377. while (start < end) {
  378. var mid = start + (end - start) / 2;
  379. var xEst = f(a, c, mid);
  380. if (Math.abs(x - xEst) < 1e-6) {
  381. return f(b, d, mid);
  382. }
  383. if (xEst < x) {
  384. start = mid;
  385. } else {
  386. end = mid;
  387. }
  388. }
  389. return f(b, d, mid);
  390. };
  391. }
  392. function doAnimation(numArr, frameTime) {
  393. const _cubic = cubic(...numArr.slice(7).map((n, W) => calculateScaledValue(n, W % 2 ? -1 : 0, 1, false)));
  394. const currentTime = Math.round(frameTime / 10) * 10;
  395. const cubicValue = _cubic(currentTime / totalTime);
  396. const frameColor = interpolate([ numArr[0], numArr[1], numArr[2] ], [ numArr[3], numArr[4], numArr[5] ], cubicValue);
  397. const frameRotate = interpolate([ 0 ], [ calculateScaledValue(numArr[6], 60, 360, !0) ], cubicValue);
  398. const frameMatrix = convertRotationToMatrix(frameRotate);
  399. return {
  400. color: frameColor.map(c => Math.round(c)),
  401. transform: frameMatrix.slice(0, 4).map(m => Number(Number(m).toFixed(2)))
  402. };
  403. }
  404. const getAnimationKey = (svgArray, verification, indexKey) => {
  405. const index = verification[indexKey[0]] % 16;
  406. const frameTime = verification[indexKey[1]] % 16 * (verification[indexKey[2]] % 16) * (verification[indexKey[3]] % 16);
  407. const style = doAnimation(svgArray[index], frameTime);
  408. const hexIntArray = Array.from([ style.color.length + style.transform.length + 2 ]);
  409. const hexArray = hexIntArray.map(i => i.toString(16));
  410. hexArray[7] = hexArray[8] = '0';
  411. for (let i = 0; i < 3; i++) {
  412. const numColorValue = style.color[i];
  413. if (numColorValue >= 0 && numColorValue <= 255) {
  414. hexArray[i] = numColorValue.toString(16);
  415. }
  416. if (numColorValue < 0) {
  417. hexArray[i] = '0';
  418. } else {
  419. hexArray[i] = 'ff';
  420. }
  421. }
  422. for (let i = 0; i < 4; i++) {
  423. let numMatrixValue = style.transform[i];
  424. if (numMatrixValue < 0) {
  425. numMatrixValue = -numMatrixValue;
  426. }
  427. if (numMatrixValue > 0 && numMatrixValue < 1) {
  428. hexArray[i + 3] = numMatrixValue.toString(16).replace('.', '');
  429. } else if (numMatrixValue <= 0) {
  430. hexArray[i + 3] = '0';
  431. } else {
  432. hexArray[i + 3] = '1';
  433. }
  434. }
  435. return hexArray;
  436. };
  437. const getIndices = async html => {
  438. const ON_DEMAND_FILE_REGEX = /['"](ondemand\.s)['"]:\s*['"]([\w]*)['"]/gim;
  439. const INDICES_REGEX = /\(\w\[(\d{1,2})\],\s*16\)/gim;
  440. const onDemandMatch = ON_DEMAND_FILE_REGEX.exec(html);
  441. const keyByteIndices = [];
  442. if (onDemandMatch) {
  443. const url = `https://abs.twimg.com/responsive-web/client-web/ondemand.s.${onDemandMatch[2]}a.js`;
  444. try {
  445. const {
  446. data
  447. } = await axiosGM.get(url);
  448. const matches = data.matchAll(INDICES_REGEX);
  449. for (const match of matches) {
  450. keyByteIndices.push(parseInt(match[1], 10));
  451. }
  452. } catch (error) {
  453. console.error('Failed to fetch ondemand file:', error);
  454. }
  455. }
  456. if (keyByteIndices.length < 4) {
  457. throw new Error('Couldn\'t get KEY_BYTE indices');
  458. }
  459. return keyByteIndices;
  460. };
  461. module.exports = {
  462. getIndices: getIndices,
  463. getAnimationKey: getAnimationKey
  464. };
  465. },
  466. 727: function(module) {
  467. const never = (...args) => {
  468. throw new Error(...args);
  469. };
  470. module.exports = {
  471. never: never
  472. };
  473. },
  474. 791: function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  475. 'use strict';
  476. __webpack_require__.r(__webpack_exports__);
  477. __webpack_require__.d(__webpack_exports__, {
  478. decodeTransactionId: function() {
  479. return decodeTransactionId;
  480. }
  481. });
  482. const decodeTimeFromBytes = timeBytes => {
  483. const reversed = [ ...timeBytes ].reverse();
  484. const timeValue = reversed.reduce((acc, value) => acc << 8 | value, 0);
  485. const baseTime = 1682924400;
  486. return new Date((timeValue + baseTime) * 1e3);
  487. };
  488. const decodeTransactionId = transactionId => {
  489. const padded = transactionId + '='.repeat((4 - transactionId.length % 4) % 4);
  490. const binaryString = atob(padded);
  491. const decoded = new Uint8Array(binaryString.length);
  492. for (let i = 0; i < binaryString.length; i++) {
  493. decoded[i] = binaryString.charCodeAt(i);
  494. }
  495. const rand = decoded[0];
  496. const dataSection = Array.from(decoded.subarray(1)).reverse().map(byte => byte ^ rand).reverse();
  497. const keyBytes = dataSection.slice(0, 48);
  498. const timeNowBytes = dataSection.slice(48, 52);
  499. const hashBytes = dataSection.slice(52, 68);
  500. const additional = dataSection[68];
  501. return {
  502. keyBytes: keyBytes,
  503. time: decodeTimeFromBytes(timeNowBytes),
  504. hashBytes: hashBytes,
  505. additional: additional
  506. };
  507. };
  508. },
  509. 945: function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
  510. 'use strict';
  511. __webpack_require__.r(__webpack_exports__);
  512. __webpack_require__.d(__webpack_exports__, {
  513. axiosGM: function() {
  514. return axiosGM;
  515. }
  516. });
  517. const parseResponseHeaders = headerStr => {
  518. const headers = {};
  519. if (!headerStr) {
  520. return headers;
  521. }
  522. headerStr.split('\r\n').forEach(line => {
  523. if (line) {
  524. const parts = line.split(':');
  525. const key = parts.shift()?.trim();
  526. const value = parts.join(':').trim();
  527. if (key) {
  528. if (key.toLowerCase() === 'set-cookie') {
  529. if (headers[key]) {
  530. if (Array.isArray(headers[key])) {
  531. headers[key].push(value);
  532. } else {
  533. headers[key] = [ headers[key], value ];
  534. }
  535. } else {
  536. headers[key] = value;
  537. }
  538. } else {
  539. headers[key] = value;
  540. }
  541. }
  542. }
  543. });
  544. return headers;
  545. };
  546. const axiosGM = function(config) {
  547. const finalConfig = {
  548. ...axiosGM.defaults,
  549. ...config
  550. };
  551. const retries = finalConfig.retry ?? 0;
  552. const retryDelay = finalConfig.retryDelay ?? 0;
  553. const requestAttempt = attempt => new Promise((resolve, reject) => {
  554. GM_xmlhttpRequest({
  555. method: finalConfig.method ? finalConfig.method.toUpperCase() : 'GET',
  556. url: finalConfig.url,
  557. headers: finalConfig.headers,
  558. data: finalConfig.data,
  559. responseType: finalConfig.responseType || 'json',
  560. timeout: finalConfig.timeout,
  561. fetch: finalConfig.fetch ?? true,
  562. onload(response) {
  563. const axiosResponse = {
  564. data: response.response || response.responseText,
  565. status: response.status,
  566. statusText: response.statusText,
  567. headers: parseResponseHeaders(response.responseHeaders),
  568. config: finalConfig,
  569. request: response
  570. };
  571. resolve(axiosResponse);
  572. },
  573. onerror(error) {
  574. if (attempt < retries) {
  575. setTimeout(() => {
  576. requestAttempt(attempt + 1).then(resolve).catch(reject);
  577. }, retryDelay);
  578. } else {
  579. reject(error);
  580. }
  581. },
  582. ontimeout() {
  583. if (attempt < retries) {
  584. setTimeout(() => {
  585. requestAttempt(attempt + 1).then(resolve).catch(reject);
  586. }, retryDelay);
  587. } else {
  588. reject('Error: timeout');
  589. }
  590. }
  591. });
  592. });
  593. return requestAttempt(0);
  594. };
  595. axiosGM.defaults = {};
  596. axiosGM.get = function(url, config = {}) {
  597. return axiosGM({
  598. ...config,
  599. url: url,
  600. method: 'GET'
  601. });
  602. };
  603. axiosGM.post = function(url, data, config = {}) {
  604. return axiosGM({
  605. ...config,
  606. url: url,
  607. data: data,
  608. method: 'POST'
  609. });
  610. };
  611. axiosGM.head = function(url, config = {}) {
  612. return axiosGM({
  613. ...config,
  614. url: url,
  615. method: 'HEAD'
  616. });
  617. };
  618. axiosGM.create = function(instanceDefaults = {}) {
  619. const instance = config => {
  620. const mergedConfig = {
  621. ...axiosGM.defaults,
  622. ...instanceDefaults,
  623. ...config
  624. };
  625. return axiosGM(mergedConfig);
  626. };
  627. instance.defaults = {
  628. ...axiosGM.defaults,
  629. ...instanceDefaults
  630. };
  631. instance.get = function(url, config = {}) {
  632. return instance({
  633. ...config,
  634. url: url,
  635. method: 'GET'
  636. });
  637. };
  638. instance.post = function(url, data, config = {}) {
  639. return instance({
  640. ...config,
  641. url: url,
  642. data: data,
  643. method: 'POST'
  644. });
  645. };
  646. instance.head = function(url, config = {}) {
  647. return instance({
  648. ...config,
  649. url: url,
  650. method: 'HEAD'
  651. });
  652. };
  653. instance.create = axiosGM.create;
  654. return instance;
  655. };
  656. },
  657. 991: function(__unused_webpack_module, exports) {
  658. !function(e, n) {
  659. true ? n(exports) : 0;
  660. }(this, function(e) {
  661. 'use strict';
  662. function l(e) {
  663. return '[object Object]' === o(e);
  664. }
  665. function n(e) {
  666. return /^\d+$/.test(e + '');
  667. }
  668. function t(e) {
  669. return /^\d+\.\d+$/.test(e + '');
  670. }
  671. var o = function(e) {
  672. return Object.prototype.toString.call(e);
  673. };
  674. var r = function() {
  675. return (r = Object.assign || function(e) {
  676. for (var n, t = 1, o = arguments.length; t < o; t++) {
  677. for (var r in n = arguments[t]) {
  678. Object.prototype.hasOwnProperty.call(n, r) && (e[r] = n[r]);
  679. }
  680. }
  681. return e;
  682. }).apply(this, arguments);
  683. };
  684. function i(e, n, t) {
  685. if (t || 2 === arguments.length) {
  686. for (var o, r = 0, i = n.length; r < i; r++) {
  687. !o && r in n || ((o = o || Array.prototype.slice.call(n, 0, r))[r] = n[r]);
  688. }
  689. }
  690. return e.concat(o || Array.prototype.slice.call(n));
  691. }
  692. a.prototype.init = function() {
  693. try {
  694. this.getSystemName(), this.getBrowserName();
  695. } catch (e) {
  696. console.warn('[UA formatter error] '.concat(e));
  697. }
  698. }, a.prototype.getEngine = function() {
  699. var e = this.agent;
  700. return -1 !== e.indexOf('Trident') ? 'Trident' : -1 !== e.indexOf('Firefox') ? 'Gecko' : -1 !== e.indexOf('Presto') ? 'Presto' : 'WebKit';
  701. }, a.prototype.getSystemName = function() {
  702. var e, n = (this.agent.match(/^[a-z]+\/\d+\.\d+\s?\(([a-z\d\s:;./_-]+)\)/i) || [])[1];
  703. try {
  704. var t, o = '';
  705. if (/Windows/i.test(n)) {
  706. var r = (n.match(/NT\s(\d+\.\d+)/) || [])[1];
  707. switch (this.info.os = 'Windows', r) {
  708. case '6.3':
  709. o = '8.1';
  710. break;
  711.  
  712. case '6.2':
  713. o = '8';
  714. break;
  715.  
  716. case '6.1':
  717. o = '7';
  718. break;
  719.  
  720. case '5.2':
  721. case '5.1':
  722. o = 'XP';
  723. break;
  724.  
  725. default:
  726. o = r;
  727. }
  728. this.info.device = 'PC', this.info.osVersion = o;
  729. } else {
  730. /^Macintosh/i.test(n) ? (o = (n.match(/X\s((\d+(_|\.))+\d+)/) || [])[1],
  731. 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],
  732. this.info.os = 'iPad', this.info.device = 'Tablet', this.info.osVersion = o.replace(/_/g, '.')) : /^iPhone/i.test(n) ? (o = (n.match(/((\d+_)+\d+)/) || [])[1],
  733. 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],
  734. 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',
  735. this.info.osVersion = 'Unknown');
  736. }
  737. } catch (e) {
  738. this.info.os = 'Unknown', this.info.osVersion = 'Unknown';
  739. }
  740. }, a.prototype.getBrowserName = function() {
  741. var e = Object.keys(this.browserNameMap).map(function(e) {
  742. return new RegExp(''.concat(e, '(\\/|\\s)(\\d+\\.)+\\d+'));
  743. }), n = 1 < (n = (this.agent.match(/[a-z\d]+(\/|\s)(\d+\.)+\d+/gi) || []).filter(function(n) {
  744. return -1 !== e.findIndex(function(e) {
  745. return e.test(n);
  746. });
  747. })).length && !/^Safari/.test(n[n.length - 1]) ? n.reverse() : n;
  748. this.info = r(r({}, this.info), this._formatBrowserVersion(n[0]));
  749. }, a.prototype._formatBrowserVersion = function(e) {
  750. var n, t, o, r;
  751. try {
  752. 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++) {
  753. var l = f[u], d = l[0], h = l[1];
  754. if (new RegExp(d).test(s)) {
  755. c = h;
  756. break;
  757. }
  758. }
  759. var p = {
  760. browserVersion: null != a ? a : 'Unknown',
  761. browser: null != (o = c.en) ? o : 'Unknown',
  762. browserZH: null != (r = (null == c ? void 0 : c.zh) || c.en) ? r : 'Unknown'
  763. };
  764. return 'Trident' === s && (p.browserVersion = {
  765. '4.0': 8,
  766. '5.0': 9,
  767. '6.0': 10,
  768. '7.0': 11
  769. }[a]), p;
  770. } catch (e) {
  771. return console.warn('[UA formatter error] '.concat(e)), {
  772. browser: 'Unknown',
  773. browserVersion: 'Unknown'
  774. };
  775. }
  776. };
  777. var s = a;
  778. function a(e) {
  779. this.agent = '', this.info = {
  780. browser: '',
  781. browserZH: '',
  782. browserVersion: '',
  783. os: '',
  784. osVersion: '',
  785. device: 'Unknown',
  786. engine: 'WebKit'
  787. }, this.browserNameMap = {
  788. MicroMessenger: {
  789. en: 'MicroMessenger',
  790. zh: '微信'
  791. },
  792. MetaSr: {
  793. en: 'MetaSr',
  794. zh: '搜狗浏览器'
  795. },
  796. 'QQ(Browser)?': {
  797. en: 'QQBrowser',
  798. zh: 'QQ浏览器'
  799. },
  800. UCBrowser: {
  801. en: 'UCBrowser',
  802. zh: 'UC浏览器'
  803. },
  804. '2345Explorer': {
  805. en: '2345Explorer',
  806. zh: '2345极速浏览器'
  807. },
  808. Mb2345Browser: {
  809. en: 'Mb2345Browser',
  810. zh: '2345手机浏览器'
  811. },
  812. Trident: {
  813. en: 'Internet Explorer'
  814. },
  815. 'Edge?': {
  816. en: 'Edge'
  817. },
  818. OPR: {
  819. en: 'Opera'
  820. },
  821. Vivaldi: {
  822. en: 'Vivaldi'
  823. },
  824. Firefox: {
  825. en: 'Firefox'
  826. },
  827. Chrome: {
  828. en: 'Chrome'
  829. },
  830. Safari: {
  831. en: 'Safari'
  832. }
  833. }, this.agent = e, this.init();
  834. var e = this.info, n = e.browser, t = e.browserVersion, e = e.osVersion;
  835. this.info = r(r({}, this.info), {
  836. engine: this.getEngine(),
  837. browserVersion: 'Safari' === n ? e : t
  838. });
  839. }
  840. u.prototype.init = function() {
  841. var t;
  842. 'undefined' != typeof window && (t = {}, document.cookie.split(/;\s/).forEach(function(e) {
  843. var e = e.split(/=/), n = e[0], e = e[1];
  844. t[n] = e;
  845. }), this.cookies = t);
  846. }, u.prototype.getItem = function(e) {
  847. return this.cookies[e];
  848. }, u.prototype.getAllItems = function() {
  849. return this.cookies;
  850. }, u.prototype.setItem = function(e, n, t, o, r, i) {
  851. document.cookie = ''.concat(e, '=').concat(n).concat(t ? '; expires='.concat(t) : '').concat(o ? '; path='.concat(o) : '').concat(r ? '; domain='.concat(r) : '').concat(i ? '; secure' : '');
  852. };
  853. var c = u;
  854. function u() {
  855. this.cookies = {}, this.init();
  856. }
  857. function d(e, n) {
  858. var t = i(i([], n || [], !0), [ '_' ], !1).join('|');
  859. return e.replace(new RegExp('(('.concat(t, ')[a-z])+'), 'g'), function(e, n) {
  860. return n.replace(new RegExp(t), '').toLocaleUpperCase();
  861. });
  862. }
  863. function f(e) {
  864. return e.replace(/(-\w)/g, function(e) {
  865. return e.substr(1, 1).toUpperCase();
  866. }).replace(/^(\w)/, function(e) {
  867. return e.toUpperCase();
  868. });
  869. }
  870. e.countDown = function e(n, t, o, r) {
  871. if (!window) {
  872. throw new Error('window is not defined.');
  873. }
  874. if (0 < n) {
  875. return r && r(), n--, window[t] = window.setTimeout(function() {
  876. e(n, t, o, r);
  877. }, 1e3), function() {
  878. return clearTimeout(window[t]);
  879. };
  880. }
  881. clearTimeout(window[t]), o && o();
  882. }, e.createRandomID = function(e) {
  883. void 0 === e && (e = 12);
  884. for (var n = [], t = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''), o = t.length, r = 0; r < e; r++) {
  885. n.push(t[Math.round(Math.random() * o)]);
  886. }
  887. return n.join('');
  888. }, e.dCookie = function() {
  889. return new c();
  890. }, e.debounce = function(o, r, i) {
  891. var s;
  892. return void 0 === r && (r = 0), void 0 === i && (i = !1), function() {
  893. for (var e = this, n = [], t = 0; t < arguments.length; t++) {
  894. n[t] = arguments[t];
  895. }
  896. i ? o.apply(this, n) : (clearTimeout(s), s = setTimeout(function() {
  897. o.apply(e, n);
  898. }, r));
  899. };
  900. }, e.debounceDecorator = function(r, i) {
  901. var s;
  902. return function(e, n, t) {
  903. var o = t.value;
  904. return t.value = function() {
  905. for (var e = this, n = [], t = 0; t < arguments.length; t++) {
  906. n[t] = arguments[t];
  907. }
  908. i ? o.apply(this, n) : (clearTimeout(s), s = setTimeout(function() {
  909. o.apply(e, n);
  910. }, r));
  911. }, t;
  912. };
  913. }, e.debugWarn = function(e, n) {
  914. console.warn('['.concat(e, ']: ').concat(n));
  915. }, e.deepCopy = function e(n) {
  916. if (l(n) || Array.isArray(n)) {
  917. var t, o = Array.isArray(n) ? [] : {};
  918. for (t in n) {
  919. o[t] = e(n[t]);
  920. }
  921. return o;
  922. }
  923. return n;
  924. }, e.deleteArrayItems = function(n, e, t) {
  925. return 'object' == typeof e[0] ? e.filter(function(e) {
  926. return !n.includes(e[t]);
  927. }) : e.filter(function(e) {
  928. return !n.includes(e);
  929. });
  930. }, e.formatQueryParams = function(e) {
  931. e = null == (e = /\?(?<params>(.*)=.+)/.exec(decodeURIComponent(e))) ? void 0 : e.groups;
  932. if (!e) {
  933. return {};
  934. }
  935. for (var n = e.params.split('&'), o = {}, t = 0; t < n.length; t++) {
  936. n[t].replace(/([^?&]*)=([^?&]*)/, function(e, n, t) {
  937. return o[n] = t, e;
  938. });
  939. }
  940. return o;
  941. }, e.formatThousandth = function(e) {
  942. 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, '$&,');
  943. return ''.concat(n).concat(e ? '.'.concat(e) : '');
  944. }, e.generateTree = function e(n, t, o, r) {
  945. for (var i = [], s = 0; s < n.length; s++) {
  946. var a = n[s];
  947. a[o] === t && (i.push(a), a.children = e(n, a[null != r ? r : 'id'], o, r));
  948. }
  949. return i;
  950. }, e.isBoolean = function(e) {
  951. return 'boolean' == typeof e;
  952. }, e.isEmpty = function(e) {
  953. 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);
  954. }, e.isFloatNumber = t, e.isFunction = function(e) {
  955. return '[object Function]' === o(e);
  956. }, e.isImageUrl = function(e) {
  957. return /\.((png)|(jpe?g)|(gif)|(svg)|(webp))$/gi.test(e);
  958. }, e.isInteger = n, e.isNumber = function(e) {
  959. return n(e) || t(e);
  960. }, e.isObject = l, e.isPromise = function(e) {
  961. return '[object Promise]' === o(e);
  962. }, e.isRegexp = function(e) {
  963. return '[object RegExp]' === o(e);
  964. }, e.objectKeyToCamelCase = function e(n, t, o) {
  965. if (Array.isArray(n)) {
  966. for (var r = [], i = 0; i < n.length; i++) {
  967. r[i] = e(t && n[i][t] ? n[i][t] : n[i], t, o);
  968. }
  969. } else if (l(n)) {
  970. r = {};
  971. for (var s = t && n[t] ? n[t] : n, a = 0, c = Object.entries(s); a < c.length; a++) {
  972. var u = (f = c[a])[0], f = f[1];
  973. Array.isArray(f) || l(s) ? r[d(u, o)] = e(f, t, o) : r[d(u, o)] = f;
  974. }
  975. } else {
  976. r = n;
  977. }
  978. return r;
  979. }, e.pickLastItem = function(e) {
  980. return e[e.length - 1];
  981. }, e.realType = o, e.searchParams = function(e, n) {
  982. return void 0 === e && (e = null === location || void 0 === location ? void 0 : location.search),
  983. new URLSearchParams(e).get(n);
  984. }, e.throwError = function(e, n) {
  985. throw '['.concat(f(e), ']: ').concat(n);
  986. }, e.toBoolean = function(e) {
  987. return 'true' === e || 'false' !== e && Boolean(e);
  988. }, e.toLowerCamelCase = d, e.toPascalCase = f, e.toUnderline = function(e) {
  989. return e.replace(/([A-Z])/g, function(e) {
  990. return '_'.concat(e.toLocaleLowerCase());
  991. });
  992. }, e.ua = function(e) {
  993. return void 0 === e && (e = navigator.userAgent), new s(e).info;
  994. };
  995. });
  996. }
  997. };
  998. var __webpack_module_cache__ = {};
  999. function __webpack_require__(moduleId) {
  1000. var cachedModule = __webpack_module_cache__[moduleId];
  1001. if (cachedModule !== undefined) {
  1002. return cachedModule.exports;
  1003. }
  1004. var module = __webpack_module_cache__[moduleId] = {
  1005. id: moduleId,
  1006. exports: {}
  1007. };
  1008. __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  1009. return module.exports;
  1010. }
  1011. !function() {
  1012. __webpack_require__.n = function(module) {
  1013. var getter = module && module.__esModule ? function() {
  1014. return module['default'];
  1015. } : function() {
  1016. return module;
  1017. };
  1018. __webpack_require__.d(getter, {
  1019. a: getter
  1020. });
  1021. return getter;
  1022. };
  1023. }();
  1024. !function() {
  1025. __webpack_require__.d = function(exports, definition) {
  1026. for (var key in definition) {
  1027. if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  1028. Object.defineProperty(exports, key, {
  1029. enumerable: true,
  1030. get: definition[key]
  1031. });
  1032. }
  1033. }
  1034. };
  1035. }();
  1036. !function() {
  1037. __webpack_require__.o = function(obj, prop) {
  1038. return Object.prototype.hasOwnProperty.call(obj, prop);
  1039. };
  1040. }();
  1041. !function() {
  1042. __webpack_require__.r = function(exports) {
  1043. if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  1044. Object.defineProperty(exports, Symbol.toStringTag, {
  1045. value: 'Module'
  1046. });
  1047. }
  1048. Object.defineProperty(exports, '__esModule', {
  1049. value: true
  1050. });
  1051. };
  1052. }();
  1053. var __webpack_exports__ = {};
  1054. !function() {
  1055. 'use strict';
  1056. const external_Swal_namespaceObject = Swal;
  1057. var external_Swal_default = __webpack_require__.n(external_Swal_namespaceObject);
  1058. const external_Cookies_namespaceObject = Cookies;
  1059. var external_Cookies_default = __webpack_require__.n(external_Cookies_namespaceObject);
  1060. var auto_task = __webpack_require__(675);
  1061. var javascript_utils_umd_min = __webpack_require__(991);
  1062. const httpRequest = async (options, times = 0) => {
  1063. if (window.TRACE) {
  1064. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  1065. }
  1066. try {
  1067. const result = await new Promise(resolve => {
  1068. if (options.dataType) {
  1069. options.responseType = options.dataType;
  1070. }
  1071. const requestObj = {
  1072. ...{
  1073. timeout: 3e4,
  1074. ontimeout(data) {
  1075. resolve({
  1076. result: 'Error',
  1077. statusText: 'Timeout',
  1078. status: 601,
  1079. data: data,
  1080. options: options
  1081. });
  1082. },
  1083. onabort() {
  1084. resolve({
  1085. result: 'Error',
  1086. statusText: 'Aborted',
  1087. status: 602,
  1088. data: undefined,
  1089. options: options
  1090. });
  1091. },
  1092. onerror(data) {
  1093. resolve({
  1094. result: 'Error',
  1095. statusText: 'Error',
  1096. status: 603,
  1097. data: data,
  1098. options: options
  1099. });
  1100. },
  1101. onload(data) {
  1102. const headers = {};
  1103. data.responseHeaders?.split('\n').forEach(header => {
  1104. const headerArr = header.trim().split(':');
  1105. const name = headerArr.shift()?.trim() || '';
  1106. const value = headerArr.join(':').trim();
  1107. if (name && value) {
  1108. if (headers[name]) {
  1109. if (Array.isArray(headers[name])) {
  1110. headers[name].push(value);
  1111. } else {
  1112. headers[name] = [ headers[name], value ];
  1113. }
  1114. } else {
  1115. headers[name] = value;
  1116. }
  1117. }
  1118. });
  1119. if (headers['set-cookie'] && !Array.isArray(headers['set-cookie'])) {
  1120. headers['set-cookie'] = [ headers['set-cookie'] ];
  1121. }
  1122. data.responseHeadersText = data.responseHeaders;
  1123. data.responseHeaders = headers;
  1124. data.finalUrl = data.responseHeaders?.location || data.finalUrl;
  1125. if (options.responseType === 'json' && data?.response && typeof data.response !== 'object') {
  1126. try {
  1127. data.response = JSON.parse(data.responseText);
  1128. } catch (error) {}
  1129. }
  1130. resolve({
  1131. result: 'Success',
  1132. statusText: 'Load',
  1133. status: 600,
  1134. data: data,
  1135. options: options
  1136. });
  1137. }
  1138. },
  1139. ...options
  1140. };
  1141. GM_xmlhttpRequest(requestObj);
  1142. });
  1143. if (window.DEBUG) {
  1144. console.log('%cAuto-Task[httpRequest]:', 'color:blue', JSON.stringify(result));
  1145. }
  1146. if (result.status !== 600 && times < 2) {
  1147. return await httpRequest(options, times + 1);
  1148. }
  1149. return result;
  1150. } catch (error) {
  1151. console.log('%cAuto-Task[httpRequest]:', 'color:red', JSON.stringify({
  1152. errorMsg: error,
  1153. options: options
  1154. }));
  1155. throwError(error, 'httpRequest');
  1156. return {
  1157. result: 'JsError',
  1158. statusText: 'Error',
  1159. status: 604,
  1160. error: error,
  1161. options: options
  1162. };
  1163. }
  1164. };
  1165. const tools_httpRequest = httpRequest;
  1166. const echoLog = ({
  1167. type,
  1168. text,
  1169. html,
  1170. id
  1171. }) => {
  1172. const emptyStatus = {
  1173. success: () => emptyStatus,
  1174. error: () => emptyStatus,
  1175. warning: () => emptyStatus,
  1176. info: () => emptyStatus,
  1177. view: () => emptyStatus
  1178. };
  1179. try {
  1180. let ele;
  1181. if (type) {
  1182. switch (type) {
  1183. case 'joiningSteamGroup':
  1184. case 'leavingSteamGroup':
  1185. case 'gettingSteamGroupId':
  1186. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/groups/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1187. break;
  1188.  
  1189. case 'joiningSteamOfficialGroup':
  1190. case 'leavingSteamOfficialGroup':
  1191. case 'gettingSteamOfficialGroupId':
  1192. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/games/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1193. break;
  1194.  
  1195. case 'subscribingForum':
  1196. case 'unsubscribingForum':
  1197. case 'gettingForumId':
  1198. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/app/${text}/discussions/" target="_blank">${text}</a>]...<font></font></li>`);
  1199. break;
  1200.  
  1201. case 'followingCurator':
  1202. case 'unfollowingCurator':
  1203. case 'gettingCuratorId':
  1204. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/${text?.includes('/') ? text : `curator/${text}`}" target="_blank">${text}</a>]...<font></font></li>`);
  1205. break;
  1206.  
  1207. case 'addingToWishlist':
  1208. case 'removingFromWishlist':
  1209. case 'followingGame':
  1210. case 'unfollowingGame':
  1211. case 'gettingSubid':
  1212. case 'addingFreeLicense':
  1213. case 'requestingPlayTestAccess':
  1214. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/app/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1215. break;
  1216.  
  1217. case 'addingFreeLicenseSubid':
  1218. ele = $(`<li>${i18n('addingFreeLicense')}[<a href="https://steamdb.info/sub/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  1219. break;
  1220.  
  1221. case 'favoritingWorkshop':
  1222. case 'unfavoritingWorkshop':
  1223. case 'gettingWorkshopAppId':
  1224. case 'votingUpWorkshop':
  1225. ele = $(`<li>${i18n(type)}[<a href="https://steamcommunity.com/sharedfiles/filedetails/?id=${text}" target="_blank">
  1226. ${text}</a>]...<font></font></li>`);
  1227. break;
  1228.  
  1229. case 'gettingAnnouncementParams':
  1230. case 'likingAnnouncement':
  1231. ele = $(`<li>${i18n(type)}[<a href="https://store.steampowered.com/news/app/${text}/view/${id}" target="_blank">
  1232. ${id}</a>]...<font></font></li>`);
  1233. break;
  1234.  
  1235. case 'joiningDiscordServer':
  1236. case 'gettingDiscordGuild':
  1237. ele = $(`<li>${i18n(type)}[<a href="https://discord.com/invite/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1238. break;
  1239.  
  1240. case 'leavingDiscordServer':
  1241. ele = $(`<li>${i18n(type)}[<a href="https://discord.com/channels/@me/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1242. break;
  1243.  
  1244. case 'updateDiscordAuth':
  1245. ele = $(`<li style="color:red;">${i18n('updateDiscordAuth')}</li>`);
  1246. break;
  1247.  
  1248. case 'followingTwitchChannel':
  1249. case 'unfollowingTwitchChannel':
  1250. case 'gettingTwitchChannelId':
  1251. ele = $(`<li>${i18n(type)}[<a href="https://www.twitch.tv/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1252. break;
  1253.  
  1254. case 'gettingInsUserId':
  1255. case 'followingIns':
  1256. case 'unfollowingIns':
  1257. ele = $(`<li>${i18n(type)}[<a href="https://www.instagram.com/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  1258. break;
  1259.  
  1260. case 'gettingTwitterUserId':
  1261. case 'followingTwitterUser':
  1262. case 'unfollowingTwitterUser':
  1263. ele = $(`<li>${i18n(type)}[<a href="https://x.com/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1264. break;
  1265.  
  1266. case 'retweetting':
  1267. case 'unretweetting':
  1268. ele = $(`<li>${i18n(type)}${text}...<font></font></li>`);
  1269. break;
  1270.  
  1271. case 'joiningReddit':
  1272. case 'leavingReddit':
  1273. ele = $(`<li>${i18n(type)}[<a href="https://www.reddit.com/r/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  1274. break;
  1275.  
  1276. case 'followingRedditUser':
  1277. case 'unfollowingRedditUser':
  1278. ele = $(`<li>${i18n(type)}[<a href="https://www.reddit.com/user/${text?.replace('u_', '')}" target="_blank">
  1279. ${text?.replace('u_', '')}</a>]...<font></font></li>`);
  1280. break;
  1281.  
  1282. case 'followingYtbChannel':
  1283. case 'unfollowingYtbChannel':
  1284. ele = $(`<li>${i18n(type)}[<a href="https://www.youtube.com/channel/${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1285. break;
  1286.  
  1287. case 'likingYtbVideo':
  1288. case 'unlikingYtbVideo':
  1289. ele = $(`<li>${i18n(type)}[<a href="https://www.youtube.com/watch?v=${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1290. break;
  1291.  
  1292. case 'gettingVkId':
  1293. case 'joiningVkGroup':
  1294. case 'leavingVkGroup':
  1295. case 'joiningVkPublic':
  1296. case 'leavingVkPublic':
  1297. case 'sendingVkWall':
  1298. case 'deletingVkWall':
  1299. ele = $(`<li>${i18n(type)}[<a href="https://vk.com/${text}/" target="_blank">${text}</a>]...<font></font></li>`);
  1300. break;
  1301.  
  1302. case 'visitingLink':
  1303. ele = $(`<li>${i18n('visitingLink')}[<a href="${text}" target="_blank">${text}</a>]...<font></font></li>`);
  1304. break;
  1305.  
  1306. case 'verifyingInsAuth':
  1307. case 'text':
  1308. ele = $(`<li>${i18n(text)}<font></font></li>`);
  1309. break;
  1310.  
  1311. case 'html':
  1312. ele = $(text || html);
  1313. break;
  1314.  
  1315. case 'whiteList':
  1316. ele = $(`<li><font class="warning">${i18n('skipTask')}[${text}(${id})](${i18n('whiteList')})</font></li>`);
  1317. break;
  1318.  
  1319. case 'globalOptionsSkip':
  1320. ele = $(`<li>${i18n('skipTaskOption')}<font class="warning">${text}</font></li>`);
  1321. break;
  1322.  
  1323. default:
  1324. ele = $(`<li>${i18n('unKnown')}:${type}(${text})...<font></font></li>`);
  1325. break;
  1326. }
  1327. } else if (text) {
  1328. ele = $(`<li>${i18n(text)}<font></font></li>`);
  1329. } else if (html) {
  1330. ele = $(html);
  1331. } else {
  1332. ele = $('<li><font></font></li>');
  1333. }
  1334. ele.addClass('card-text');
  1335. $('#auto-task-info').append(ele);
  1336. ele[0]?.scrollIntoView();
  1337. const font = ele.find('font');
  1338. const status = {
  1339. font: font,
  1340. success(text = 'Success', html = false) {
  1341. this.font?.attr('class', '').addClass('success');
  1342. html ? this.font?.html(text) : this.font?.text(text);
  1343. return this;
  1344. },
  1345. error(text = 'Error', html = false) {
  1346. this.font?.attr('class', '').addClass('error');
  1347. html ? this.font?.html(text) : this.font?.text(text);
  1348. return this;
  1349. },
  1350. warning(text = 'Warning', html = false) {
  1351. this.font?.attr('class', '').addClass('warning');
  1352. html ? this.font?.html(text) : this.font?.text(text);
  1353. return this;
  1354. },
  1355. info(text = 'Info', html = false) {
  1356. this.font?.attr('class', '').addClass('info');
  1357. html ? this.font?.html(text) : this.font?.text(text);
  1358. return this;
  1359. },
  1360. view() {
  1361. this.font?.[0].scrollIntoView();
  1362. return this;
  1363. }
  1364. };
  1365. return status;
  1366. } catch (error) {
  1367. throwError(error, 'echoLog');
  1368. return emptyStatus;
  1369. }
  1370. };
  1371. const scripts_echoLog = echoLog;
  1372. const unique = array => {
  1373. try {
  1374. return [ ...new Set(array) ];
  1375. } catch (error) {
  1376. throwError(error, 'unique');
  1377. return [];
  1378. }
  1379. };
  1380. const delay = (time = 1e3) => new Promise(resolve => {
  1381. setTimeout(() => {
  1382. resolve(true);
  1383. }, time);
  1384. });
  1385. const getRedirectLink = async (link, redirectOnce = false) => {
  1386. try {
  1387. if (!link) {
  1388. return null;
  1389. }
  1390. const redirectLinksCache = GM_getValue('redirectLinks') || {};
  1391. if (redirectLinksCache[link]) {
  1392. redirectLinksCache[link];
  1393. }
  1394. return await tools_httpRequest({
  1395. url: link,
  1396. method: 'GET',
  1397. redirect: redirectOnce ? 'manual' : 'follow'
  1398. }).then(({
  1399. data
  1400. }) => {
  1401. if (data?.finalUrl) {
  1402. redirectLinksCache[link] = data.finalUrl;
  1403. GM_setValue('redirectLinks', redirectLinksCache);
  1404. return data.finalUrl;
  1405. }
  1406. return null;
  1407. });
  1408. } catch (error) {
  1409. throwError(error, 'getRedirectLink');
  1410. return null;
  1411. }
  1412. };
  1413. const visitLink = async (link, options) => {
  1414. try {
  1415. const logStatus = scripts_echoLog({
  1416. type: 'visitLink',
  1417. text: link
  1418. });
  1419. return await tools_httpRequest({
  1420. url: link,
  1421. method: 'GET',
  1422. ...options
  1423. }).then(({
  1424. result,
  1425. statusText,
  1426. status
  1427. }) => {
  1428. if (result === 'Success') {
  1429. logStatus.success();
  1430. return true;
  1431. }
  1432. logStatus.error(`${result}:${statusText}(${status})`);
  1433. return false;
  1434. });
  1435. } catch (error) {
  1436. throwError(error, 'visitLink');
  1437. return false;
  1438. }
  1439. };
  1440. const getUrlQuery = url => {
  1441. try {
  1442. const query = {};
  1443. if (url) {
  1444. if (url.includes('?')) {
  1445. url.split('?')[1].replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  1446. query[key] = value;
  1447. return str;
  1448. });
  1449. }
  1450. } else {
  1451. window.location.search.replace(/([^?&=]+)=([^&]+)/g, (str, key, value) => {
  1452. query[key] = value;
  1453. return str;
  1454. });
  1455. }
  1456. return query;
  1457. } catch (error) {
  1458. throwError(error, 'getUrlQuery');
  1459. return {};
  1460. }
  1461. };
  1462. const getUuid = () => {
  1463. const uuidUrl = URL.createObjectURL(new Blob()).toString();
  1464. return uuidUrl.slice(uuidUrl.lastIndexOf('/') + 1);
  1465. };
  1466. const stringToColour = str => {
  1467. try {
  1468. let hash = 0;
  1469. for (let i = 0; i < str.length; i++) {
  1470. hash = str.charCodeAt(i) + ((hash << 5) - hash);
  1471. }
  1472. let colour = '#';
  1473. for (let i = 0; i < 3; i++) {
  1474. const value = hash >> i * 8 & 255;
  1475. colour += `00${value.toString(16)}`.slice(-2);
  1476. }
  1477. return colour;
  1478. } catch (error) {
  1479. throwError(error, 'stringToColour');
  1480. return '#fff';
  1481. }
  1482. };
  1483. const debug = (log, data) => {
  1484. if (!window.DEBUG) {
  1485. return;
  1486. }
  1487. console.log('%c%s', 'color:#a7a7a7', `Auto-Task[Debug]: ${log}`);
  1488. if (data) {
  1489. console.log('%c%s', 'color:#a7a7a7', 'Auto-Task[Debug]: ', data);
  1490. }
  1491. };
  1492. const defaultGlobalOptions = {
  1493. doTask: {
  1494. discord: {
  1495. servers: true
  1496. },
  1497. instagram: {
  1498. users: true
  1499. },
  1500. twitch: {
  1501. channels: true
  1502. },
  1503. twitter: {
  1504. users: true,
  1505. retweets: true
  1506. },
  1507. vk: {
  1508. names: true
  1509. },
  1510. youtube: {
  1511. channels: true,
  1512. likes: true
  1513. },
  1514. reddit: {
  1515. reddits: true
  1516. },
  1517. steam: {
  1518. groups: true,
  1519. officialGroups: true,
  1520. wishlists: true,
  1521. follows: true,
  1522. forums: true,
  1523. workshops: true,
  1524. curators: true,
  1525. workshopVotes: true,
  1526. announcements: true,
  1527. licenses: true,
  1528. playtests: true,
  1529. playTime: true
  1530. }
  1531. },
  1532. undoTask: {
  1533. discord: {
  1534. servers: true
  1535. },
  1536. instagram: {
  1537. users: true
  1538. },
  1539. twitch: {
  1540. channels: true
  1541. },
  1542. twitter: {
  1543. users: true,
  1544. retweets: true
  1545. },
  1546. vk: {
  1547. names: true
  1548. },
  1549. youtube: {
  1550. channels: true,
  1551. likes: true
  1552. },
  1553. reddit: {
  1554. reddits: true
  1555. },
  1556. steam: {
  1557. groups: true,
  1558. officialGroups: true,
  1559. wishlists: true,
  1560. follows: true,
  1561. forums: true,
  1562. workshops: true,
  1563. curators: true,
  1564. playTime: true
  1565. }
  1566. },
  1567. ASF: {
  1568. AsfEnabled: false,
  1569. AsfIpcUrl: '',
  1570. AsfIpcPassword: '',
  1571. AsfBotname: 'asf'
  1572. },
  1573. position: {
  1574. buttonSideX: 'right',
  1575. buttonSideY: 'top',
  1576. buttonDistance: '15,30',
  1577. showButtonSideX: 'right',
  1578. showButtonSideY: 'top',
  1579. showButtonDistance: '15,30',
  1580. logSideX: 'right',
  1581. logSideY: 'bottom',
  1582. logDistance: '10,10'
  1583. },
  1584. hotKey: {
  1585. doTaskKey: 'alt + d',
  1586. undoTaskKey: 'alt + u',
  1587. toggleLogKey: 'alt + l'
  1588. },
  1589. other: {
  1590. twitterVerifyId: '783214',
  1591. youtubeVerifyChannel: 'UCrXUsMBcfTVqwAS7DKg9C0Q',
  1592. autoUpdateSource: 'jsdelivr',
  1593. language: 'zh',
  1594. checkLogin: true,
  1595. checkLeftKey: true,
  1596. defaultShowButton: true,
  1597. defaultShowLog: true,
  1598. debug: false,
  1599. receivePreview: true
  1600. }
  1601. };
  1602. const userDefinedGlobalOptions = GM_getValue('globalOptions') || {};
  1603. const assignObject = (obj1, obj2) => {
  1604. try {
  1605. const newObj = {};
  1606. for (const [ key, value ] of Object.entries(obj1)) {
  1607. if (Object.prototype.toString.call(value) === '[object Object]' && Object.prototype.toString.call(obj2[key]) === '[object Object]') {
  1608. newObj[key] = assignObject(value, obj2[key]);
  1609. } else {
  1610. newObj[key] = obj2[key] ?? value;
  1611. }
  1612. }
  1613. return newObj;
  1614. } catch (error) {
  1615. throwError(error, 'assignObject');
  1616. return defaultGlobalOptions;
  1617. }
  1618. };
  1619. const globalOptions = assignObject(defaultGlobalOptions, userDefinedGlobalOptions);
  1620. const saveData = () => {
  1621. try {
  1622. const data = {};
  1623. $('#globalOptionsForm').serializeArray().map(value => {
  1624. data[value.name] = value.value;
  1625. return value;
  1626. });
  1627. $.makeArray($('#globalOptionsForm input')).map(element => {
  1628. const name = $(element).attr('name');
  1629. const keys = name.split('.');
  1630. if (keys.length === 3) {
  1631. globalOptions[keys[0]][keys[1]][keys[2]] = data[name] ? data[name] === 'on' ? true : data[name] : data[name] ?? false;
  1632. } else if (keys.length === 2) {
  1633. globalOptions[keys[0]][keys[1]] = data[name] ? data[name] === 'on' ? true : data[name] : data[name] ?? false;
  1634. }
  1635. return element;
  1636. });
  1637. GM_setValue('globalOptions', globalOptions);
  1638. external_Swal_default().fire({
  1639. title: i18n('changeGlobalOptionsSuccess'),
  1640. icon: 'success'
  1641. });
  1642. } catch (error) {
  1643. throwError(error, 'saveData');
  1644. }
  1645. };
  1646. const changeGlobalOptions = showType => {
  1647. try {
  1648. let globalOptionsForm = `<form id="globalOptionsForm" class="auto-task-form">
  1649. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  1650. for (const [ type, data1 ] of Object.entries(globalOptions)) {
  1651. for (const [ option, data2 ] of Object.entries(data1)) {
  1652. if ([ 'other', 'position', 'hotKey', 'ASF' ].includes(type)) {
  1653. if (typeof data2 === 'boolean') {
  1654. 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>`;
  1655. } else {
  1656. 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>`;
  1657. }
  1658. } else {
  1659. for (const [ socialType, data3 ] of Object.entries(data2)) {
  1660. 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>`;
  1661. }
  1662. }
  1663. }
  1664. }
  1665. globalOptionsForm += '</tbody></table></form>';
  1666. if (showType === 'swal') {
  1667. external_Swal_default().fire({
  1668. title: i18n('globalOptions'),
  1669. html: globalOptionsForm,
  1670. showConfirmButton: true,
  1671. confirmButtonText: i18n('save'),
  1672. showCancelButton: true,
  1673. cancelButtonText: i18n('close')
  1674. }).then(({
  1675. isConfirmed
  1676. }) => {
  1677. if (isConfirmed) {
  1678. saveData();
  1679. }
  1680. });
  1681. } else {
  1682. $('body').append(`<h2>${i18n('globalOptions')}</h2>${globalOptionsForm}`);
  1683. }
  1684. } catch (error) {
  1685. throwError(error, 'changeGlobalOptions');
  1686. }
  1687. };
  1688. const data = {
  1689. website: '网站',
  1690. type: '类型',
  1691. edit: '编辑',
  1692. whiteList: '白名单',
  1693. skipTask: '跳过撤销任务',
  1694. whiteListOptions: '白名单设置',
  1695. changeWhiteListOption: '设置白名单(%0)',
  1696. whiteListNotFound: '找不到此项白名单: %0',
  1697. changeWhiteListSuccess: '白名单修改成功,刷新生效!',
  1698. changeWebsiteOptions: '网站设置',
  1699. changeGlobalOptions: '全局设置',
  1700. ok: '是',
  1701. save: '保存',
  1702. close: '关闭',
  1703. return: '返回',
  1704. option: '选项',
  1705. value: '值',
  1706. websiteOptions: '当前网站设置',
  1707. changeWebsiteOptionsSuccess: '更改当前网站设置成功,刷新生效!',
  1708. changeGlobalOptionsSuccess: '更改全局设置成功,刷新生效!',
  1709. needLogin: '请先登录!',
  1710. getTasksInfo: '正在获取并处理任务信息...',
  1711. gettingKey: '正在获取Key...',
  1712. verifyingTask: '正在验证任务',
  1713. notice: '自动任务脚本提醒',
  1714. noKeysLeft: '此页面已经没有剩余key了,是否关闭?',
  1715. giveawayEnded: '此活动已结束,是否关闭?',
  1716. giveawayNotWork: '此活动因某些原因(已结束/暂停/未开始...)不可用(如果是脚本误判请及时反馈),是否关闭?',
  1717. confirm: '确定',
  1718. cancel: '取消',
  1719. unKnown: '未知',
  1720. unKnownTaskType: '未识别的任务',
  1721. doing: '正在做任务',
  1722. allTasksComplete: '所有任务已完成!',
  1723. getTaskIdFailed: '获取任务Id失败!',
  1724. initSuccess: '%0 初始化成功!',
  1725. initFailed: '%0 初始化失败!',
  1726. errorLink: '链接错误: %0',
  1727. needInit: '请先初始化',
  1728. verifyingAuth: '正在验证%0凭证...',
  1729. updatingAuth: '正在更新%0凭证...',
  1730. refreshingToken: '正在刷新%0凭证...',
  1731. settingToken: '正在设置%0凭证...',
  1732. steamStoreTab: 'Steam商店(弹窗)',
  1733. steamCommunityTab: 'Steam社区(弹窗)',
  1734. initing: '正在初始化...',
  1735. getFailed: '获取%0失败!',
  1736. checkLoginFailed: '检测登录状态失败!',
  1737. checkLeftKeyFailed: '检测剩余Key失败!',
  1738. userId: '用户Id',
  1739. joiningGiveaway: '正在加入赠Key',
  1740. needJoinGiveaway: '需要先加入赠Key',
  1741. cannotUndo: '此网站不支持取消任务',
  1742. verifyAuth: '正在验证 %0 凭证...',
  1743. closePageNotice: '如果此页面没有自动关闭,请自行关闭本页面。',
  1744. errorReport: '检测到脚本报错,是否前往反馈BUG?',
  1745. visitingLink: '正在访问链接...',
  1746. doTask: '做任务',
  1747. undoTask: '撤销任务',
  1748. verifyTask: '验证任务',
  1749. getKey: '获取Key',
  1750. selectAll: '全选',
  1751. selectNone: '全不选',
  1752. invertSelect: '反选',
  1753. doFreeTask: '加入免费赠品',
  1754. doPointTask: '加入点数赠品',
  1755. skipTaskOption: '设置中已配置跳过任务',
  1756. other: '其他',
  1757. globalOptions: '全局设置',
  1758. checkLogin: '登录检测</br>需要登录的网站自动登录,部分网站支持',
  1759. checkLeftKey: '剩余Key检测</br>赠Key活动结束提示是否关闭,部分网站支持',
  1760. twitterVerifyId: '通过尝试关注该账号验证Twitter凭证</br>默认为Twitter官方帐号 783214</br>不想关注官方账号可以改为自己的帐号',
  1761. youtubeVerifyChannel: '通过尝试订阅该频道验证YouTube凭证</br>默认为YouTube官方频道 UCrXUsMBcfTVqwAS7DKg9C0Q</br>不想关注官方频道可以改为自己的频道',
  1762. autoUpdateSource: '更新源</br>github: 需代理,实时更新</br>jsdelivr: 可不用代理,更新有延迟</br>standby: 备用</br>auto: 依次使用github, jsdelivr, standby源进行尝试更新',
  1763. saveGlobalOptions: '保存设置',
  1764. settingPage: '设置页面',
  1765. name: '名称',
  1766. version: '版本',
  1767. scriptManager: '脚本管理器',
  1768. script: '脚本',
  1769. environment: '环境',
  1770. os: '系统',
  1771. browser: '浏览器',
  1772. getId: '获取 %0 id',
  1773. getTwitterUserId: '获取Twitter用户id(获取id功能仅在设置页面可用)',
  1774. getYoutubeChannelId: '获取Youtube频道id(获取id功能仅在设置页面可用)',
  1775. showButton: '显示按钮',
  1776. hideButton: '隐藏按钮',
  1777. showLog: '显示日志',
  1778. hideLog: '隐藏日志',
  1779. defaultShowButton: '默认显示按钮',
  1780. defaultShowLog: '默认显示日志',
  1781. debug: '输出调试日志,不要开启此选项!',
  1782. receivePreview: '接收预览版更新',
  1783. position: '组件位置',
  1784. buttonSideX: '按钮区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1785. buttonSideY: '按钮区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1786. buttonDistance: '按钮区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1787. showButtonSideX: '显示按钮水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1788. showButtonSideY: '显示按钮垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1789. showButtonDistance: '显示按钮距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1790. logSideX: '日志区域水平方向定位(实时预览功能仅在设置页面可用)</br>left: 靠左 | right: 靠右',
  1791. logSideY: '日志区域垂直方向定位(实时预览功能仅在设置页面可用)</br>top: 靠上 | bottom: 靠下',
  1792. logDistance: '日志区域距边缘的距离(实时预览功能仅在设置页面可用)</br>格式: X距离,Y距离',
  1793. hotKey: '快捷键',
  1794. doTaskKey: '做任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1795. undoTaskKey: '撤销任务快捷键</br>(实时预览功能仅在设置页面可用)',
  1796. toggleLogKey: '显示/隐藏日志快捷键</br>(实时预览功能仅在设置页面可用)',
  1797. tasksHistory: '任务历史',
  1798. clearHistory: '清空历史',
  1799. clearHistoryFinished: '已清空任务历史!',
  1800. deleteTask: '删除任务',
  1801. lastChangeTime: '最后一次修改时间',
  1802. clearTaskFinished: '删除以下任务完成!',
  1803. clearTaskFailed: '删除任务失败,没有找到任务名!',
  1804. syncData: '数据同步',
  1805. settingData: '正在上传数据...',
  1806. gettingData: '正在获取数据...',
  1807. help: '帮助',
  1808. fileName: '文件名',
  1809. upload2gist: '同步到Gist',
  1810. downloadFromGist: '从Gist同步',
  1811. saveAndTest: '保存配置并测试',
  1812. testSuccess: '测试成功!',
  1813. testFailed: '测试失败!',
  1814. saveAndTestNotice: '请先保存配置并测试!',
  1815. processingData: '正在处理数据...',
  1816. updatingData: '正在上传数据...',
  1817. syncDataSuccess: '同步数据成功!',
  1818. syncDataFailed: '同步数据失败,请在控制台查看错误信息!',
  1819. downloadingData: '正在下载数据...',
  1820. checkedNoData: '没有检测到远程数据,请确认配置是否正确!',
  1821. savingData: '正在保存数据...',
  1822. syncHistory: '同步任务历史',
  1823. checkUpdateFailed: '检测更新失败',
  1824. newVersionNotice: '检测到新版本V%0, <a class="high-light" href="%1" target="_blank">点此更新</a>',
  1825. language: '语言</br>目前仅支持zh: 中文, en: 英文',
  1826. gistOptions: 'Gist 设置',
  1827. swalNotice: '检测到您第一次安装V4版本脚本,请前往阅读用前必读内容!',
  1828. echoNotice: '检测到您第一次安装V4版本脚本,请<a class="high-light" href="%0" target="_blank">点此前往</a>阅读用前必读内容!',
  1829. noticeLink: 'https://auto-task-doc.js.org/guide/#用前必读',
  1830. toGithub: '前往Github反馈',
  1831. toKeylol: '前往其乐论坛反馈',
  1832. copySuccess: '错误信息已复制到剪切板,是否前往其乐论坛反馈?',
  1833. copyFailed: '请复制下方错误信息后前往Keylol论坛反馈!',
  1834. updateText: '%0 版本更新内容:',
  1835. Active: '进行中',
  1836. Ended: '已结束',
  1837. Banned: '已封禁',
  1838. Paused: '已暂停',
  1839. notStart: '未开始',
  1840. noRemoteData: '检测到远程无数据',
  1841. errorRemoteDataFormat: '远程数据格式错误',
  1842. updateHistory: '历史更新记录<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">点此查看</a>',
  1843. AsfEnabled: '使用ASF做Steam相关任务(需<a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a>插件)',
  1844. AsfIpcUrl: 'ASF IPC 地址',
  1845. AsfIpcPassword: 'ASF IPC 密码',
  1846. versionNotMatched: '脚本管理器版本过低,需TamperMonkey >= 5.2.0或TamperMonkey Beta >= 5.2.6196',
  1847. groups: '组',
  1848. officialGroups: '官方组',
  1849. wishlists: '愿望单',
  1850. follows: '游戏关注',
  1851. forums: '论坛',
  1852. workshops: '创意工坊收藏',
  1853. curators: '鉴赏家',
  1854. workshopVotes: '创意工坊点赞',
  1855. announcements: '社区通知',
  1856. steamCommunity: 'Steam社区',
  1857. steamStore: 'Steam商店',
  1858. licenses: '入库免费游戏',
  1859. playtests: '请求访问权限',
  1860. playTime: '挂时长',
  1861. needLoginSteamStore: '请先<a href="https://store.steampowered.com/login/" target="_blank">登录Steam商店</a>',
  1862. needLoginSteamCommunity: '请先<a href="https://steamcommunity.com/login/home/" target="_blank">登录Steam社区</a>',
  1863. joiningSteamGroup: '正在加入Steam组',
  1864. leavingSteamGroup: '正在退出Steam组',
  1865. gettingSteamGroupId: '正在获取Steam组Id',
  1866. joiningSteamOfficialGroup: '正在加入Steam官方组',
  1867. leavingSteamOfficialGroup: '正在退出Steam官方组',
  1868. gettingSteamOfficialGroupId: '正在获取Steam官方组Id',
  1869. subscribingForum: '正在订阅Steam论坛',
  1870. unsubscribingForum: '正在取消订阅Steam论坛',
  1871. gettingForumId: '正在获取Steam论坛Id',
  1872. followingCurator: '正在关注Steam鉴赏家',
  1873. unfollowingCurator: '正在取关Steam鉴赏家',
  1874. gettingCuratorId: '正在获取Steam鉴赏家Id',
  1875. addingToWishlist: '正在添加游戏到Steam愿望单',
  1876. removingFromWishlist: '正在从Steam愿望单移除游戏',
  1877. followingGame: '正在关注Steam游戏',
  1878. unfollowingGame: '正在取关Steam游戏',
  1879. favoritingWorkshop: '正在收藏Steam创意工坊物品',
  1880. unfavoritingWorkshop: '正在取消收藏Steam创意工坊物品',
  1881. gettingWorkshopAppId: '正在获取Steam创意工坊物品Id',
  1882. votingUpWorkshop: '正在点赞Steam创意工坊物品',
  1883. gettingAnnouncementParams: '正在获取Steam通知信息',
  1884. likingAnnouncement: '正在点赞Steam通知',
  1885. changingArea: '正在更换Steam地区: %0...',
  1886. notNeededChangeArea: '当前地区不需要更换',
  1887. noAnotherArea: '请检测是否开启正确开启代理',
  1888. gettingAreaInfo: '正在获取Steam地区信息...',
  1889. changeAreaNotice: '疑似锁区游戏,尝试换区执行',
  1890. steamFinishNotice: 'Steam任务完成,尝试将购物车地区换回',
  1891. gettingSubid: '正在获取游戏subid',
  1892. addingFreeLicense: '正在入库',
  1893. missParams: '缺少参数',
  1894. gettingLicenses: '正在获取Licenses...',
  1895. requestingPlayTestAccess: '正在请求访问权限',
  1896. tryChangeAreaNotice: '此功能无法检测游戏是否限区,因此会尝试换区后再入库,换区失败也不影响后续入库',
  1897. gettingUserLink: '正在获取Steam用户社区链接...',
  1898. retry: '重试',
  1899. owned: '已拥有',
  1900. redirect: '重定向',
  1901. noSubid: '无法获取,跳过',
  1902. noASFInstance: '未启用ASF',
  1903. initingASF: '正在初始化ASF...',
  1904. playingGames: '正在挂游戏时长[%0]...',
  1905. stoppingPlayGames: '正在停止挂游戏时长...',
  1906. stopPlayTimeTitle: 'Steam游戏挂机时长满足,是否结束挂机?',
  1907. stopPlayTimeText: '挂机已超时:%0 分钟',
  1908. servers: '服务器',
  1909. joiningDiscordServer: '正在加入Discord服务器',
  1910. leavingDiscordServer: '正在退出Discord服务器',
  1911. gettingDiscordGuild: '正在获取Discord服务器Id',
  1912. getDiscordAuthFailed: '获取Discord凭证失败,请检测Discord帐号是否已登录',
  1913. discordImportantNotice: '重要提醒!!!',
  1914. discordImportantNoticeText: '由于Discord网站后台更新,目前使用此脚本加组后可能会导致Discord帐号被强制退出,且需要两步验证才能正常登录,请谨慎使用!!!',
  1915. continue: '继续',
  1916. skipDiscordTask: '跳过Discord任务',
  1917. continueAndDontRemindAgain: '继续且不再提醒',
  1918. users: '用户',
  1919. loginIns: '请先<a href="https://www.instagram.com/accounts/login/" target="_blank">登录Instagram</a>',
  1920. insBanned: '您的Instagram账户已被封禁',
  1921. verifyingInsAuth: '正在验证Instagram凭证...',
  1922. gettingInsUserId: '正在获取Instagram用户Id',
  1923. followingIns: '正在关注Instagram用户',
  1924. unfollowingIns: '正在取关Instagram用户',
  1925. reddits: '社区/用户',
  1926. loginReddit: '请先<a href="https://www.reddit.com/login/" target="_blank">登录Reddit</a>',
  1927. changingRedditVersion: '正在切换Reddit为新版页面...',
  1928. joiningReddit: '正在加入Reddit社区',
  1929. leavingReddit: '正在退出Reddit社区',
  1930. followingRedditUser: '正在关注Reddit用户',
  1931. unfollowingRedditUser: '正在取关Reddit用户',
  1932. channels: '频道',
  1933. followingTwitchChannel: '正在关注Twitch频道',
  1934. unfollowingTwitchChannel: '正在取关Twitch频道',
  1935. gettingTwitchChannelId: '正在获取Twitch频道Id',
  1936. checkingTwitchIntegrity: '正在检查Twitch完整性...',
  1937. twitterUser: '推特用户',
  1938. retweets: '转推',
  1939. gettingTwitterUserId: '正在获取推特用户Id',
  1940. followingTwitterUser: '正在关注推特用户',
  1941. unfollowingTwitterUser: '正在取关推特用户',
  1942. retweetting: '正在转推',
  1943. unretweetting: '正在撤销转推',
  1944. names: '组/社区/动态',
  1945. loginVk: '请先<a href="https://vk.com/login/" target="_blank">登录Vk</a>',
  1946. gettingVkId: '正在获取Vk任务Id',
  1947. joiningVkGroup: '正在加入Vk组',
  1948. leavingVkGroup: '正在退出Vk组',
  1949. joiningVkPublic: '正在加入Vk社区',
  1950. leavingVkPublic: '正在退出Vk社区',
  1951. sendingVkWall: '正在转发Vk动态',
  1952. deletingVkWall: '正在撤销转发Vk动态',
  1953. youtubeChannel: 'YouTube频道',
  1954. likes: '点赞',
  1955. loginYtb: '请先<a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">登录YouTube</a>',
  1956. tryUpdateYtbAuth: '请尝试<a href="https://www.youtube.com/#auth" target="_blank">更新YouTube凭证</a>',
  1957. gettingYtbToken: '正在获取YouTube Token...',
  1958. followingYtbChannel: '正在订阅YouTube频道',
  1959. unfollowingYtbChannel: '正在退订YouTube频道',
  1960. likingYtbVideo: '正在点赞YouTube视频',
  1961. unlikingYtbVideo: '正在取消点赞YouTube视频',
  1962. giveKeyNoticeBefore: '每次验证间隔15s',
  1963. giveKeyNoticeAfter: '如果没有key, 请在<a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>查看',
  1964. noPoints: '点数不够,跳过抽奖',
  1965. getNeedPointsFailed: '获取所需点数失败,跳过抽奖',
  1966. joiningLottery: '正在加入抽奖',
  1967. doingGleamTask: '正在做Gleam任务...',
  1968. gettingGleamLink: '正在获取Gleam任务链接...',
  1969. gleamTaskNotice: '如果此页面长时间未关闭,请完成任一任务后自行关闭!',
  1970. verifiedGleamTasks: '已尝试验证所有任务,验证失败的任务请尝试手动验证或完成!',
  1971. campaign: '检测到人机验证,请完成验证后重新验证任务!',
  1972. gsNotice: '为避免得到"0000-0000-0000"key, 已自动屏蔽"Grab Key"按钮,获取key时请关闭脚本!',
  1973. giveeClubVerifyNotice: '正在验证任务...',
  1974. giveeClubVerifyFinished: '请等待验证完成后自行加入赠Key',
  1975. doingKeyhubTask: '正在做Keyhub任务...',
  1976. SweepWidgetNotice: '正在处理并验证任务,每次验证任务有1~3s间隔防止触发验证过快警告...',
  1977. tasksNotCompleted: '任务未完成',
  1978. notConnect: '社交平台未连接,跳过任务',
  1979. tgTaskNotice: '检测到Telegram任务,需要手动完成',
  1980. confirmingTask: '正在跳过警告页面...',
  1981. unSupporttedTaskType: '不支持的任务类型'
  1982. };
  1983. const zh_CN = data;
  1984. const en_US_data = {
  1985. website: 'Website',
  1986. type: 'Type',
  1987. edit: 'Edit',
  1988. whiteList: 'Whitelist',
  1989. skipTask: 'Skip undo task',
  1990. whiteListOptions: 'Whitelist options',
  1991. changeWhiteListOption: 'Whitelist option(%0)',
  1992. whiteListNotFound: 'Cannot find this whitelist: %0',
  1993. changeWhiteListSuccess: 'The whitelist is successfully modified, and the page refresh will take effect!',
  1994. changeWebsiteOptions: 'Website options',
  1995. changeGlobalOptions: 'Global options',
  1996. ok: 'OK',
  1997. save: 'Save',
  1998. close: 'Close',
  1999. return: 'Return',
  2000. option: 'Option',
  2001. value: 'Value',
  2002. websiteOptions: 'Current website settings',
  2003. changeWebsiteOptionsSuccess: 'The current website setting is changed successfully, and the page refresh will take effect!',
  2004. changeGlobalOptionsSuccess: 'The global setting is changed successfully, and the refresh will take effect!',
  2005. needLogin: 'Please log in first!',
  2006. getTasksInfo: 'Obtaining and processing task information...',
  2007. gettingKey: 'Getting Key...',
  2008. verifyingTask: 'Verifying task',
  2009. notice: 'Automatic task script notice',
  2010. noKeysLeft: 'There are no more keys left on this page. Do you want to close it?',
  2011. giveawayEnded: 'This event has ended, do you want to close it?',
  2012. 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?',
  2013. confirm: 'Confirm',
  2014. cancel: 'Cancel',
  2015. unKnown: 'Unknown',
  2016. unKnownTaskType: 'Unrecognized task',
  2017. doing: 'Doing a task',
  2018. allTasksComplete: 'All tasks have been completed!',
  2019. getTaskIdFailed: 'Failed to obtain task Id!',
  2020. initSuccess: '%0 was initialized successfully!',
  2021. initFailed: '%0 initialization failed!',
  2022. errorLink: 'Link error: %0',
  2023. needInit: 'Please initialize first',
  2024. verifyingAuth: 'Verifying %0 token...',
  2025. updatingAuth: 'Update %0 token...',
  2026. refreshingToken: 'Refreshing %0 token...',
  2027. settingToken: 'Setting %0 token...',
  2028. steamStoreTab: 'Steam store (new tab)',
  2029. steamCommunityTab: 'Steam community(new tab)',
  2030. initing: 'Initializing...',
  2031. getFailed: 'Failed to get %0!',
  2032. checkLoginFailed: 'Failed to detect login status!',
  2033. checkLeftKeyFailed: 'Failed to detect the remaining keys!',
  2034. userId: 'User Id',
  2035. joiningGiveaway: 'Joining giveaway',
  2036. needJoinGiveaway: 'Need to join the giveaway first',
  2037. cannotUndo: 'This website does not support canceling tasks',
  2038. verifyAuth: 'Verifying %0 token...',
  2039. closePageNotice: 'f this page does not close automatically, please close this page yourself.',
  2040. errorReport: 'A script error is detected, do you want to report the BUG?',
  2041. visitingLink: 'Visiting link ...',
  2042. doTask: 'DoTask',
  2043. undoTask: 'UndoTask',
  2044. verifyTask: 'Verify',
  2045. getKey: 'GetKey',
  2046. selectAll: 'SelectAll',
  2047. selectNone: 'SelectNone',
  2048. invertSelect: 'InvertSelect',
  2049. doFreeTask: 'FreeTask',
  2050. doPointTask: 'PointTask',
  2051. skipTaskOption: 'Skip task has been configured in the settings',
  2052. other: 'Other',
  2053. globalOptions: 'Global Options',
  2054. checkLogin: 'Login detection</br>Need to log in to the website automatically log in, part of this website supports.',
  2055. checkLeftKey: 'Key remaining detection</br>The end of the giveaway event prompts whether to close or not, part of this website supports.',
  2056. 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.',
  2057. 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.',
  2058. 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.',
  2059. saveGlobalOptions: 'SaveSettings',
  2060. settingPage: 'Setting Page',
  2061. name: 'Name',
  2062. version: 'Version',
  2063. scriptManager: 'Script Manager',
  2064. script: 'Script',
  2065. environment: 'Environment',
  2066. os: 'OS',
  2067. browser: 'Browser',
  2068. getId: 'Get %0 id',
  2069. getTwitterUserId: 'Get Twitter user id (Get id function is only available on the settings page).',
  2070. getYoutubeChannelId: 'Get Youtube channel id (Get id function is only available on the settings page).',
  2071. showButton: 'ShowButton',
  2072. hideButton: 'HideButton',
  2073. showLog: 'ShowLog',
  2074. hideLog: 'HideLog',
  2075. defaultShowButton: 'Default display button',
  2076. defaultShowLog: 'Display log by default',
  2077. debug: 'Output debug log, do not enable this option!',
  2078. receivePreview: 'Receive preview updates',
  2079. position: 'Component position',
  2080. buttonSideX: 'Horizontal positioning of the button area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  2081. 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',
  2082. 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',
  2083. showButtonSideX: 'ShowButton horizontal positioning (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  2084. showButtonSideY: 'ShowButton vertical positioning (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  2085. 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',
  2086. logSideX: 'Horizontal positioning of the log area (real-time preview function is only available on the setting page).' + '</br>left: left | right: right',
  2087. logSideY: 'Vertical positioning of the log area (real-time preview function is only available on the setting page).' + '</br>top: top | bottom: bottom',
  2088. 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',
  2089. hotKey: 'Shortcut key',
  2090. doTaskKey: 'DoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  2091. undoTaskKey: 'UndoTask shortcut keys</br> (real-time preview function is only available on the settings page).',
  2092. toggleLogKey: 'ShowLog/HideLog shortcut keys</br> (real-time preview function is only available on the settings page).',
  2093. tasksHistory: 'TasksHistory',
  2094. clearHistory: 'Clear history',
  2095. clearHistoryFinished: 'The mission history has been cleared!',
  2096. deleteTask: 'Delete task',
  2097. lastChangeTime: 'Last Change Time',
  2098. clearTaskFinished: 'Delete the following tasks completed!',
  2099. clearTaskFailed: 'Failed to delete the task, the task name was not found!',
  2100. syncData: 'DataSync',
  2101. settingData: 'Uploading data...',
  2102. gettingData: 'Getting data...',
  2103. help: 'Help',
  2104. fileName: 'Filename',
  2105. upload2gist: 'Sync to Gist',
  2106. downloadFromGist: 'Sync from Gist',
  2107. saveAndTest: 'Save configuration and test',
  2108. testSuccess: 'Test success!',
  2109. testFailed: 'Test failed!',
  2110. saveAndTestNotice: 'Please save the configuration and test first!',
  2111. processingData: 'Processing data...',
  2112. updatingData: 'Uploading data...',
  2113. syncDataSuccess: 'Synchronized data successfully!',
  2114. syncDataFailed: 'Failed to synchronize data, please check the error message on the console!',
  2115. downloadingData: 'Downloading data...',
  2116. checkedNoData: 'No remote data is detected, please confirm whether the configuration is correct!',
  2117. savingData: 'Saving data...',
  2118. syncHistory: 'Synchronize tasks history',
  2119. checkUpdateFailed: 'Check update failed',
  2120. newVersionNotice: 'Checked a new version V%0, <a class="high-light" href="%1" target="_blank">click to update</a>',
  2121. language: 'Language</br> Currently only supports zh: Chinese, en: English',
  2122. gistOptions: 'Gist Settings',
  2123. 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!',
  2124. 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!',
  2125. noticeLink: 'https://auto-task-doc.js.org/en/guide/#read-me-first',
  2126. toGithub: 'Feedback(Github)',
  2127. toKeylol: 'Feedback(Keylol)',
  2128. copySuccess: 'The error message has been copied to the clipboard. Do you want to go to the Keylol forum to give feedback?',
  2129. copyFailed: 'Please copy the error information below and report back to the Keylol forum!',
  2130. updateText: 'Updates in version %0:',
  2131. Active: 'Active',
  2132. Ended: 'Ended',
  2133. Banned: 'Banned',
  2134. Paused: 'Paused',
  2135. notStart: 'notStart',
  2136. noRemoteData: 'No data remotely',
  2137. errorRemoteDataFormat: 'Remote data has wrong format',
  2138. updateHistory: '<a class="high-light" href="https://auto-task-doc.js.org/logs/" target="_blank">Click here</a>' + ' to view the historical update record.',
  2139. AsfEnabled: 'Use ASF to do Steam related tasks (requires <a href="https://github.com/chr233/ASFEnhance" target="_blank">ASFEnhance</a> plugin)',
  2140. AsfIpcUrl: 'ASF IPC URL',
  2141. AsfIpcPassword: 'ASF IPC Password',
  2142. groups: 'Group',
  2143. officialGroups: 'Official Group',
  2144. wishlists: 'Wishlist',
  2145. follows: 'Follow Game',
  2146. forums: 'Forum',
  2147. workshops: 'Favorite Workshop',
  2148. curators: 'Curator',
  2149. workshopVotes: 'Voteup Workshop',
  2150. announcements: 'Announcement',
  2151. steamCommunity: 'Steam Community',
  2152. steamStore: 'Steam Store',
  2153. licenses: 'Add License',
  2154. playtests: 'Playtest Access',
  2155. needLoginSteamStore: 'Please <a href="https://store.steampowered.com/login/" target="_blank">log in to the Steam Store</a>',
  2156. needLoginSteamCommunity: 'Please <a href="https://steamcommunity.com/login/home/" target="_blank">log in to the Steam Community</a>',
  2157. joiningSteamGroup: 'Joining Steam Group',
  2158. leavingSteamGroup: 'Leaving Steam Group',
  2159. gettingSteamGroupId: 'Getting Steam Group Id',
  2160. joiningSteamOfficialGroup: 'Joining Steam Official Group',
  2161. leavingSteamOfficialGroup: 'Leaving Steam Official Group',
  2162. gettingSteamOfficialGroupId: 'Getting Steam Official Group Id',
  2163. subscribingForum: 'Subscribing the Steam Forum',
  2164. unsubscribingForum: 'Unsubscribing the Steam Forum',
  2165. gettingForumId: 'Getting Steam Forum Id',
  2166. followingCurator: 'Following Steam Curator',
  2167. unfollowingCurator: 'Unfollowing Steam Curator',
  2168. gettingCuratorId: 'Getting Steam Curator Id',
  2169. addingToWishlist: 'Adding the game to the Steam wishlist',
  2170. removingFromWishlist: 'Removing the game from the Steam wishlist',
  2171. followingGame: 'Following Steam games',
  2172. unfollowingGame: 'Unfollowing Steam games',
  2173. favoritingWorkshop: 'Favouring Steam Workshop Items',
  2174. unfavoritingWorkshop: 'Unfavoriting Steam Workshop Items',
  2175. gettingWorkshopAppId: 'Getting Steam Workshop Item Id',
  2176. votingUpWorkshop: 'Liking Steam workshop items',
  2177. gettingAnnouncementParams: 'Getting Steam announcement information',
  2178. likingAnnouncement: 'Liking Steam announcement',
  2179. changingArea: 'Changing Steam area: %0...',
  2180. notNeededChangeArea: 'The current area does not need to be changed',
  2181. noAnotherArea: 'Please check whether the proxy is turned on correctly',
  2182. gettingAreaInfo: 'Getting Steam area information...',
  2183. changeAreaNotice: 'Suspected of a locked zone game, try to change the zone to execute',
  2184. steamFinishNotice: 'Steam task completed, try to change the shopping cart area back to ',
  2185. gettingSubid: 'Getting subid',
  2186. addingFreeLicense: 'Adding free license',
  2187. missParams: 'Missing parameters',
  2188. gettingLicenses: 'Getting licenses...',
  2189. requestingPlayTestAccess: 'Requesting play test access',
  2190. 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.',
  2191. versionNotMatched: 'The script manager version is too low, requiring TamperMonkey >= 5.2.0 or TamperMonkey Beta >= 5.2.6196',
  2192. gettingUserLink: 'Getting steam user community link...',
  2193. retry: 'Retry',
  2194. owned: 'Owned',
  2195. redirect: 'Redirect',
  2196. noSubid: 'skip due to unrecognized',
  2197. noASFInstance: 'ASF is not enabled',
  2198. initingASF: 'Initing ASF...',
  2199. playingGames: 'Playing games [%0]...',
  2200. stoppingPlayGames: 'Stopping play games...',
  2201. stopPlayTimeTitle: 'The Steam game idle time has finished. Do you want to end it?',
  2202. stopPlayTimeText: 'Time out: %0 minutes',
  2203. servers: 'Server',
  2204. joiningDiscordServer: 'Joining Discord Server',
  2205. leavingDiscordServer: 'Leaving Discord Server',
  2206. gettingDiscordGuild: 'Getting Discord server Id',
  2207. getDiscordAuthFailed: 'Failed to get Discord token, please check whether the Discord account is logged in',
  2208. discordImportantNotice: 'Important Reminder! ! !',
  2209. 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! ! !',
  2210. continue: 'Continue',
  2211. skipDiscordTask: 'Skip',
  2212. continueAndDontRemindAgain: 'Continue without Reminders',
  2213. users: 'User',
  2214. loginIns: 'Please <a href="https://www.instagram.com/accounts/login/" target="_blank">log in to Instagram</a>',
  2215. insBanned: 'Your Instagram account has been banned',
  2216. verifyingInsAuth: 'Verifying Instagram token...',
  2217. gettingInsUserId: 'Getting Instagram user Id',
  2218. followingIns: 'Following Instagram user',
  2219. unfollowingIns: 'Unfollowing Instagram user',
  2220. reddits: 'Reddit/User',
  2221. loginReddit: 'Please <a href="https://www.reddit.com/login/" target="_blank">log in to Reddit</a>',
  2222. changingRedditVersion: 'Switching Reddit to a new version page...',
  2223. joiningReddit: 'Joining the Reddit',
  2224. leavingReddit: 'Leaving the Reddit',
  2225. followingRedditUser: 'Following Reddit User',
  2226. unfollowingRedditUser: 'Unfollowing Reddit User',
  2227. channels: 'Channel',
  2228. followingTwitchChannel: 'Following Twitch Channel',
  2229. unfollowingTwitchChannel: 'Unfollowing Twitch Channel',
  2230. gettingTwitchChannelId: 'Getting Twitch Channel Id',
  2231. checkingTwitchIntegrity: 'Checking Twitch integrity...',
  2232. twitterUser: 'Twitter User',
  2233. retweets: 'Retweet',
  2234. gettingTwitterUserId: 'Getting Twitter User Id',
  2235. followingTwitterUser: 'Following Twitter User',
  2236. unfollowingTwitterUser: 'Unfollowing Twitter User',
  2237. retweetting: 'Retweetting',
  2238. unretweetting: 'Unretweetting',
  2239. names: 'Group/Public/Wall',
  2240. loginVk: 'Please <a href="https://vk.com/login/" target="_blank">log in to Vk</a>',
  2241. gettingVkId: 'Getting Vk task Id',
  2242. joiningVkGroup: 'Joining Vk Group',
  2243. leavingVkGroup: 'Leaving Vk Group',
  2244. joiningVkPublic: 'Joining Vk Public',
  2245. leavingVkPublic: 'Leaving Vk Public',
  2246. sendingVkWall: 'Sending Vk Wall',
  2247. deletingVkWall: 'Deleting Vk Wall',
  2248. youtubeChannel: 'YouTube Channel',
  2249. likes: 'Like',
  2250. loginYtb: 'Please <a href="https://accounts.google.com/ServiceLogin?service=youtube" target="_blank">log in to YouTube</a>',
  2251. tryUpdateYtbAuth: 'Please try to <a href="https://www.youtube.com/#auth" target="_blank">update YouTube token</a>',
  2252. gettingYtbToken: 'Getting YouTube Token...',
  2253. followingYtbChannel: 'Subscribing to YouTube channel',
  2254. unfollowingYtbChannel: 'Unsubscribing to YouTube channel',
  2255. likingYtbVideo: 'Liking YouTube video',
  2256. unlikingYtbVideo: 'Unliking YouTube video',
  2257. giveKeyNoticeBefore: 'Each verification interval is 15s',
  2258. giveKeyNoticeAfter: 'If there is no key, please check at <a href="https://givekey.ru/profile" target="_blank">https://givekey.ru/profile</a>',
  2259. noPoints: 'Not enough points, skip the lottery',
  2260. getNeedPointsFailed: 'ailed to obtain the required points, skip the lottery',
  2261. joiningLottery: 'Joining the lottery',
  2262. doingGleamTask: 'Doing Gleam Task...',
  2263. gettingGleamLink: 'Getting Gleam task link...',
  2264. gleamTaskNotice: 'If this page has not been closed for a long time, please close it yourself after completing any task!',
  2265. verifiedGleamTasks: 'Attempted to verify all tasks. If the verification fails, please try to verify manually or complete it!',
  2266. campaign: 'ReCAPTCHA detected, please complete it and re-verify the tasks!',
  2267. 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!',
  2268. giveeClubVerifyNotice: 'Verifying task...',
  2269. giveeClubVerifyFinished: 'Wait for the verification to complete and join it by yourself',
  2270. doingKeyhubTask: 'Doing Keyhub Task...',
  2271. 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...',
  2272. tasksNotCompleted: 'Tasks Not Completed',
  2273. notConnect: 'Social platform is not connectted, skip',
  2274. tgTaskNotice: 'The telegram task is checked, need to do it yourself!',
  2275. confirmingTask: 'Confirming task...',
  2276. unSupporttedTaskType: 'Unsupportted task type'
  2277. };
  2278. const en_US = en_US_data;
  2279. const languages = {
  2280. zh: zh_CN,
  2281. en: en_US
  2282. };
  2283. const language = [ 'zh', 'en' ].includes(globalOptions.other.language) ? globalOptions.other.language : 'en';
  2284. const I18n = (key, ...argvs) => {
  2285. if (!languages[language]?.[key]) {
  2286. return key;
  2287. }
  2288. return languages[language][key].replace(/%([\d]+)/g, (match, index) => argvs[parseInt(index, 10)]);
  2289. };
  2290. const i18n = I18n;
  2291. function throwError(error, name) {
  2292. if (window.TRACE) {
  2293. console.trace('%cAuto-Task[Debug]:', 'color:blue');
  2294. }
  2295. external_Swal_default().fire({
  2296. title: i18n('errorReport'),
  2297. icon: 'error',
  2298. showCancelButton: true,
  2299. confirmButtonText: i18n('toGithub'),
  2300. showDenyButton: true,
  2301. denyButtonText: i18n('toKeylol'),
  2302. cancelButtonText: i18n('close')
  2303. }).then(({
  2304. isDenied,
  2305. isConfirmed
  2306. }) => {
  2307. if (isConfirmed) {
  2308. 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,
  2309. 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'))}`, {
  2310. active: true
  2311. });
  2312. } else if (isDenied) {
  2313. const text = `错误链接: [url=${window.location.href}]${window.location.href}[/url]
  2314.  
  2315. 环境:
  2316.  
  2317. [code]${JSON.stringify((0, javascript_utils_umd_min.ua)(), null, 4)}[/code]
  2318.  
  2319. 脚本管理器: ${GM_info.scriptHandler} ${GM_info.version}
  2320. 脚本版本: ${GM_info.script.version}
  2321.  
  2322. 报错信息:
  2323. [code]${error.stack}[/code]
  2324.  
  2325. 执行日志:
  2326. [code]${$.makeArray($('#auto-task-info>li')).map(element => element.innerText).join('\n')}[/code]`;
  2327. GM_setClipboard(text);
  2328. external_Swal_default().fire({
  2329. title: i18n('copySuccess'),
  2330. icon: 'success',
  2331. confirmButtonText: i18n('ok')
  2332. }).then(() => {
  2333. GM_openInTab('https://keylol.com/forum.php?mod=post&action=reply&fid=319&tid=777450', {
  2334. active: true
  2335. });
  2336. });
  2337. }
  2338. });
  2339. console.log('%c%s', 'color:white;background:red', `Auto-Task[Error]: ${name}\n${error.stack}`);
  2340. }
  2341. class Social {
  2342. tasks;
  2343. getRealParams(name, links, doTask, link2param) {
  2344. try {
  2345. let realParams = [];
  2346. if (links.length > 0) {
  2347. realParams = [ ...realParams, ...links.map(link => link2param(link)).filter(link => link) ];
  2348. }
  2349. if (!doTask && this.tasks[name].length > 0) {
  2350. realParams = [ ...realParams, ...this.tasks[name] ];
  2351. }
  2352. return unique(realParams);
  2353. } catch (error) {
  2354. throwError(error, 'Social.getRealParams');
  2355. return [];
  2356. }
  2357. }
  2358. }
  2359. const social_Social = Social;
  2360. class Discord extends social_Social {
  2361. tasks;
  2362. whiteList;
  2363. #auth = GM_getValue('discordAuth') || {};
  2364. #cache = GM_getValue('discordCache') || {};
  2365. #initialized = false;
  2366. constructor() {
  2367. super();
  2368. const defaultTasksTemplate = {
  2369. servers: []
  2370. };
  2371. this.tasks = defaultTasksTemplate;
  2372. this.whiteList = {
  2373. ...defaultTasksTemplate,
  2374. ...GM_getValue('whiteList')?.discord || {}
  2375. };
  2376. }
  2377. async init(action) {
  2378. try {
  2379. if (!GM_getValue('dontRemindDiscordAgain')) {
  2380. const result = await external_Swal_default().fire({
  2381. title: i18n('discordImportantNotice'),
  2382. text: i18n('discordImportantNoticeText'),
  2383. showCancelButton: true,
  2384. showDenyButton: true,
  2385. confirmButtonText: i18n('continue'),
  2386. cancelButtonText: i18n('skipDiscordTask'),
  2387. denyButtonText: i18n('continueAndDontRemindAgain')
  2388. }).then(({
  2389. isConfirmed,
  2390. isDenied
  2391. }) => {
  2392. if (isConfirmed) {
  2393. return true;
  2394. }
  2395. if (isDenied) {
  2396. GM_setValue('dontRemindDiscordAgain', true);
  2397. return true;
  2398. }
  2399. return false;
  2400. });
  2401. if (!result) {
  2402. this.#initialized = false;
  2403. return 'skip';
  2404. }
  2405. }
  2406. if (GM_getValue('dontRemindDiscordAgain') || action === 'do' && !globalOptions.doTask.discord.servers || action === 'undo' && !globalOptions.undoTask.discord.servers) {
  2407. this.#initialized = false;
  2408. return 'skip';
  2409. }
  2410. if (this.#initialized) {
  2411. return true;
  2412. }
  2413. if (!this.#auth.auth) {
  2414. if (await this.#updateAuth()) {
  2415. this.#initialized = true;
  2416. return true;
  2417. }
  2418. return false;
  2419. }
  2420. const isVerified = await this.#verifyAuth();
  2421. if (isVerified) {
  2422. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  2423. this.#initialized = true;
  2424. return true;
  2425. }
  2426. GM_setValue('discordAuth', {
  2427. auth: null
  2428. });
  2429. if (await this.#updateAuth()) {
  2430. scripts_echoLog({}).success(i18n('initSuccess', 'Discord'));
  2431. this.#initialized = true;
  2432. return true;
  2433. }
  2434. scripts_echoLog({}).error(i18n('initFailed', 'Discord'));
  2435. return false;
  2436. } catch (error) {
  2437. throwError(error, 'Discord.init');
  2438. return false;
  2439. }
  2440. }
  2441. async #verifyAuth() {
  2442. try {
  2443. const logStatus = scripts_echoLog({
  2444. text: i18n('verifyingAuth', 'Discord')
  2445. });
  2446. const {
  2447. result,
  2448. statusText,
  2449. status,
  2450. data
  2451. } = await tools_httpRequest({
  2452. url: 'https://discord.com/api/v6/users/@me',
  2453. method: 'HEAD',
  2454. headers: {
  2455. authorization: this.#auth.auth
  2456. }
  2457. });
  2458. if (result === 'Success') {
  2459. if (data?.status === 200) {
  2460. logStatus.success();
  2461. return true;
  2462. }
  2463. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2464. return false;
  2465. }
  2466. logStatus.error(`${result}:${statusText}(${status})`);
  2467. return false;
  2468. } catch (error) {
  2469. throwError(error, 'Discord.verifyAuth');
  2470. return false;
  2471. }
  2472. }
  2473. async #updateAuth() {
  2474. try {
  2475. const logStatus = scripts_echoLog({
  2476. text: i18n('updatingAuth', 'Discord')
  2477. });
  2478. return await new Promise(resolve => {
  2479. const newTab = GM_openInTab('https://discord.com/channels/@me', {
  2480. active: true,
  2481. insert: true,
  2482. setParent: true
  2483. });
  2484. newTab.name = 'ATv4_discordAuth';
  2485. newTab.onclose = async () => {
  2486. const auth = GM_getValue('discordAuth')?.auth;
  2487. if (auth) {
  2488. this.#auth = {
  2489. auth: auth
  2490. };
  2491. logStatus.success();
  2492. resolve(await this.#verifyAuth());
  2493. } else {
  2494. logStatus.error('Error: Update discord auth failed!');
  2495. resolve(false);
  2496. }
  2497. };
  2498. });
  2499. } catch (error) {
  2500. throwError(error, 'Discord.updateAuth');
  2501. return false;
  2502. }
  2503. }
  2504. async #joinServer(inviteId) {
  2505. try {
  2506. const logStatus = scripts_echoLog({
  2507. type: 'joiningDiscordServer',
  2508. text: inviteId
  2509. });
  2510. const {
  2511. result,
  2512. statusText,
  2513. status,
  2514. data
  2515. } = await tools_httpRequest({
  2516. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2517. method: 'POST',
  2518. dataType: 'json',
  2519. headers: {
  2520. authorization: this.#auth.auth,
  2521. origin: 'https://discord.com',
  2522. referer: `https://discord.com/invite/${inviteId}`
  2523. }
  2524. });
  2525. if (result === 'Success' && data?.status === 200) {
  2526. logStatus.success();
  2527. const guild = String(data.response?.guild?.id);
  2528. if (guild) {
  2529. this.#setCache(inviteId, guild);
  2530. this.tasks.servers = unique([ ...this.tasks.servers, inviteId ]);
  2531. }
  2532. return true;
  2533. }
  2534. logStatus.error(`${result}:${statusText}(${status})`);
  2535. return false;
  2536. } catch (error) {
  2537. throwError(error, 'Discord.joinServer');
  2538. return false;
  2539. }
  2540. }
  2541. async #leaveServer(inviteId) {
  2542. try {
  2543. if (this.whiteList.servers.includes(inviteId)) {
  2544. scripts_echoLog({
  2545. type: 'whiteList',
  2546. text: 'Discord.leaveServer',
  2547. id: inviteId
  2548. });
  2549. return true;
  2550. }
  2551. const guild = await this.#getGuild(inviteId);
  2552. if (!guild) {
  2553. return false;
  2554. }
  2555. const logStatus = scripts_echoLog({
  2556. type: 'leavingDiscordServer',
  2557. text: guild
  2558. });
  2559. const {
  2560. result,
  2561. statusText,
  2562. status,
  2563. data
  2564. } = await tools_httpRequest({
  2565. url: `https://discord.com/api/v9/users/@me/guilds/${guild}`,
  2566. method: 'DELETE',
  2567. headers: {
  2568. authorization: this.#auth.auth
  2569. }
  2570. });
  2571. if (result === 'Success' && data?.status === 204) {
  2572. logStatus.success();
  2573. return true;
  2574. }
  2575. logStatus.error(`${result}:${statusText}(${status})`);
  2576. return false;
  2577. } catch (error) {
  2578. throwError(error, 'Discord.leaveServer');
  2579. return false;
  2580. }
  2581. }
  2582. async #getGuild(inviteId) {
  2583. try {
  2584. const logStatus = scripts_echoLog({
  2585. type: 'gettingDiscordGuild',
  2586. text: inviteId
  2587. });
  2588. const guild = this.#cache[inviteId];
  2589. if (guild) {
  2590. logStatus.success();
  2591. return guild;
  2592. }
  2593. const {
  2594. result,
  2595. statusText,
  2596. status,
  2597. data
  2598. } = await tools_httpRequest({
  2599. url: `https://discord.com/api/v9/invites/${inviteId}`,
  2600. responseType: 'json',
  2601. method: 'GET'
  2602. });
  2603. if (result === 'Success' && data?.status === 200) {
  2604. const guild = data.response?.guild?.id;
  2605. if (guild) {
  2606. logStatus.success();
  2607. this.#setCache(inviteId, guild);
  2608. return guild;
  2609. }
  2610. logStatus.error(`${result}:${statusText}(${status})`);
  2611. return false;
  2612. }
  2613. logStatus.error(`${result}:${statusText}(${status})`);
  2614. return false;
  2615. } catch (error) {
  2616. throwError(error, 'Discord.getGuild');
  2617. return false;
  2618. }
  2619. }
  2620. async toggle({
  2621. doTask = true,
  2622. serverLinks = []
  2623. }) {
  2624. try {
  2625. if (!this.#initialized) {
  2626. scripts_echoLog({
  2627. text: i18n('needInit')
  2628. });
  2629. return false;
  2630. }
  2631. const prom = [];
  2632. if (doTask && !globalOptions.doTask.discord.servers || !doTask && !globalOptions.undoTask.discord.servers) {
  2633. scripts_echoLog({
  2634. type: 'globalOptionsSkip',
  2635. text: 'discord.servers'
  2636. });
  2637. } else {
  2638. const realServers = this.getRealParams('servers', serverLinks, doTask, link => link.match(/invite\/(.+)/)?.[1]);
  2639. if (realServers.length > 0) {
  2640. for (const server of realServers) {
  2641. if (doTask) {
  2642. prom.push(this.#joinServer(server));
  2643. } else {
  2644. prom.push(this.#leaveServer(server));
  2645. }
  2646. await delay(1e3);
  2647. }
  2648. }
  2649. }
  2650. return await Promise.all(prom).then(() => true);
  2651. } catch (error) {
  2652. throwError(error, 'Discord.toggleServers');
  2653. return false;
  2654. }
  2655. }
  2656. #setCache(inviteId, guild) {
  2657. try {
  2658. this.#cache[inviteId] = guild;
  2659. GM_setValue('discordCache', this.#cache);
  2660. } catch (error) {
  2661. throwError(error, 'Discord.setCache');
  2662. }
  2663. }
  2664. }
  2665. const social_Discord = Discord;
  2666. class Instagram extends social_Social {
  2667. tasks;
  2668. whiteList;
  2669. #cache = GM_getValue('instagramCache') || {};
  2670. #auth = {};
  2671. #initialized = false;
  2672. constructor() {
  2673. super();
  2674. const defaultTasksTemplate = {
  2675. users: []
  2676. };
  2677. this.tasks = defaultTasksTemplate;
  2678. this.whiteList = {
  2679. ...defaultTasksTemplate,
  2680. ...GM_getValue('whiteList')?.instagram || {}
  2681. };
  2682. }
  2683. async init() {
  2684. try {
  2685. if (this.#initialized) {
  2686. return true;
  2687. }
  2688. const isVerified = await this.#getUserInfo();
  2689. if (isVerified) {
  2690. scripts_echoLog({}).success(i18n('initSuccess', 'Instagram'));
  2691. this.#initialized = true;
  2692. return true;
  2693. }
  2694. scripts_echoLog({}).error(i18n('initFailed', 'Instagram'));
  2695. return false;
  2696. } catch (error) {
  2697. throwError(error, 'Instagram.init');
  2698. return false;
  2699. }
  2700. }
  2701. async #getUserInfo(name = 'instagram') {
  2702. try {
  2703. const logStatus = scripts_echoLog({
  2704. type: name === 'instagram' ? 'verifyingInsAuth' : 'gettingInsUserId',
  2705. text: name
  2706. });
  2707. const userId = this.#cache[name];
  2708. if (userId && name !== 'instagram') {
  2709. logStatus.success();
  2710. return userId;
  2711. }
  2712. const {
  2713. result,
  2714. statusText,
  2715. status,
  2716. data
  2717. } = await tools_httpRequest({
  2718. url: `https://www.instagram.com/${name}/`,
  2719. method: 'GET'
  2720. });
  2721. if (result === 'Success') {
  2722. if (data?.finalUrl.includes('accounts/login')) {
  2723. logStatus.error(`Error:${i18n('loginIns')}`, true);
  2724. return false;
  2725. } else if (data?.finalUrl.includes('www.instagram.com/challenge')) {
  2726. logStatus.error(`Error:${i18n('insBanned')}`);
  2727. return false;
  2728. }
  2729. if (data?.status === 200) {
  2730. const csrftoken = data.responseText.match(/"csrf_token":"(.+?)"/)?.[1];
  2731. const hash = data.responseText.match(/"rollout_hash":"(.+?)"/)?.[1];
  2732. if (name === 'instagram') {
  2733. if (csrftoken && hash) {
  2734. this.#auth = {
  2735. csrftoken: csrftoken,
  2736. hash: hash
  2737. };
  2738. return true;
  2739. }
  2740. return false;
  2741. }
  2742. const id = data.responseText.match(/"profilePage_([\d]+?)"/)?.[1];
  2743. if (id) {
  2744. this.#setCache(name, id);
  2745. logStatus.success();
  2746. return id;
  2747. }
  2748. logStatus.error('Error: Get ins data error!');
  2749. return false;
  2750. }
  2751. logStatus.error(`${result}:${statusText}(${status})`);
  2752. return false;
  2753. }
  2754. return false;
  2755. } catch (error) {
  2756. throwError(error, 'Instagram.getUserInfo');
  2757. return false;
  2758. }
  2759. }
  2760. async #followUser(name) {
  2761. try {
  2762. const id = await this.#getUserInfo(name);
  2763. if (!id) {
  2764. return false;
  2765. }
  2766. const logStatus = scripts_echoLog({
  2767. type: 'followingIns',
  2768. text: name
  2769. });
  2770. const {
  2771. result,
  2772. statusText,
  2773. status,
  2774. data
  2775. } = await tools_httpRequest({
  2776. url: `https://www.instagram.com/web/friendships/${id}/follow/`,
  2777. method: 'POST',
  2778. dataType: 'json',
  2779. headers: {
  2780. 'x-csrftoken': this.#auth.csrftoken,
  2781. origin: 'https://www.instagram.com',
  2782. referer: `https://www.instagram.com/${name}/`,
  2783. 'content-type': 'application/x-www-form-urlencoded',
  2784. 'sec-fetch-site': 'same-origin',
  2785. 'x-instagram-ajax': this.#auth.hash
  2786. }
  2787. });
  2788. if (result === 'Success') {
  2789. if (data?.status === 200 && data.response?.result === 'following') {
  2790. logStatus.success();
  2791. this.tasks.users = unique([ ...this.tasks.users, name ]);
  2792. return true;
  2793. }
  2794. logStatus.error(`Error:${data?.response?.feedback_message || `${data?.statusText}(${data?.status})`}`);
  2795. return false;
  2796. }
  2797. logStatus.error(`${result}:${statusText}(${status})`);
  2798. return false;
  2799. } catch (error) {
  2800. throwError(error, 'Instagram.followUser');
  2801. return false;
  2802. }
  2803. }
  2804. async #unfollowUser(name) {
  2805. try {
  2806. if (this.whiteList.users.includes(name)) {
  2807. scripts_echoLog({
  2808. type: 'whiteList',
  2809. text: 'Instagram.unfollowUser',
  2810. id: name
  2811. });
  2812. return true;
  2813. }
  2814. const id = await this.#getUserInfo(name);
  2815. if (!id) {
  2816. return false;
  2817. }
  2818. const logStatus = scripts_echoLog({
  2819. type: 'unfollowingIns',
  2820. text: name
  2821. });
  2822. const {
  2823. result,
  2824. statusText,
  2825. status,
  2826. data
  2827. } = await tools_httpRequest({
  2828. url: `https://www.instagram.com/web/friendships/${id}/unfollow/`,
  2829. method: 'POST',
  2830. dataType: 'json',
  2831. headers: {
  2832. 'x-csrftoken': this.#auth.csrftoken,
  2833. origin: 'https://www.instagram.com',
  2834. referer: `https://www.instagram.com/${name}/`,
  2835. 'content-type': 'application/x-www-form-urlencoded',
  2836. 'sec-fetch-site': 'same-origin',
  2837. 'x-instagram-ajax': this.#auth.hash
  2838. }
  2839. });
  2840. if (result === 'Success') {
  2841. if (data?.status === 200 && data.response?.status === 'ok') {
  2842. logStatus.success();
  2843. return true;
  2844. }
  2845. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2846. return false;
  2847. }
  2848. logStatus.error(`${result}:${statusText}(${status})`);
  2849. return false;
  2850. } catch (error) {
  2851. throwError(error, 'Instagram.unfollowUser');
  2852. return false;
  2853. }
  2854. }
  2855. async toggle({
  2856. doTask = true,
  2857. userLinks = []
  2858. }) {
  2859. try {
  2860. if (!this.#initialized) {
  2861. scripts_echoLog({
  2862. text: i18n('needInit')
  2863. });
  2864. return false;
  2865. }
  2866. const prom = [];
  2867. if (doTask && !globalOptions.doTask.instagram.users || !doTask && !globalOptions.undoTask.instagram.users) {
  2868. scripts_echoLog({
  2869. type: 'globalOptionsSkip',
  2870. text: 'instagram.users'
  2871. });
  2872. } else {
  2873. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1]);
  2874. if (realUsers.length > 0) {
  2875. for (const username of realUsers) {
  2876. if (doTask) {
  2877. prom.push(this.#followUser(username));
  2878. } else {
  2879. prom.push(this.#unfollowUser(username));
  2880. }
  2881. await delay(1e3);
  2882. }
  2883. }
  2884. }
  2885. return await Promise.all(prom).then(() => true);
  2886. } catch (error) {
  2887. throwError(error, 'Instagram.toggleUsers');
  2888. return false;
  2889. }
  2890. }
  2891. #setCache(name, id) {
  2892. try {
  2893. this.#cache[name] = id;
  2894. GM_setValue('instagramCache', this.#cache);
  2895. } catch (error) {
  2896. throwError(error, 'Instagram.setCache');
  2897. }
  2898. }
  2899. }
  2900. const social_Instagram = Instagram;
  2901. class Reddit extends social_Social {
  2902. tasks;
  2903. whiteList;
  2904. #auth;
  2905. #initialized = false;
  2906. constructor() {
  2907. super();
  2908. const defaultTasksTemplate = {
  2909. reddits: []
  2910. };
  2911. this.tasks = defaultTasksTemplate;
  2912. this.whiteList = {
  2913. ...defaultTasksTemplate,
  2914. ...GM_getValue('whiteList')?.reddit || {}
  2915. };
  2916. }
  2917. async init() {
  2918. try {
  2919. if (this.#initialized) {
  2920. return true;
  2921. }
  2922. const isVerified = await this.#updateAuth();
  2923. if (isVerified) {
  2924. scripts_echoLog({}).success(i18n('initSuccess', 'Reddit'));
  2925. this.#initialized = true;
  2926. return true;
  2927. }
  2928. scripts_echoLog({}).error(i18n('initFailed', 'Reddit'));
  2929. return false;
  2930. } catch (error) {
  2931. throwError(error, 'Reddit.init');
  2932. return false;
  2933. }
  2934. }
  2935. async #useBeta() {
  2936. try {
  2937. const logStatus = scripts_echoLog({
  2938. text: i18n('changingRedditVersion')
  2939. });
  2940. return await new Promise(resolve => {
  2941. const newTab = GM_openInTab('https://www.reddit.com/', {
  2942. active: true,
  2943. insert: true,
  2944. setParent: true
  2945. });
  2946. newTab.name = 'ATv4_redditAuth';
  2947. newTab.onclose = async () => {
  2948. logStatus.success();
  2949. resolve(await this.#updateAuth(true));
  2950. };
  2951. });
  2952. } catch (error) {
  2953. throwError(error, 'Reddit.useBeta');
  2954. return false;
  2955. }
  2956. }
  2957. async #updateAuth(beta = false) {
  2958. try {
  2959. const logStatus = scripts_echoLog({
  2960. text: i18n('updatingAuth', 'Reddit')
  2961. });
  2962. const {
  2963. result,
  2964. statusText,
  2965. status,
  2966. data
  2967. } = await tools_httpRequest({
  2968. url: 'https://www.reddit.com/',
  2969. method: 'GET',
  2970. nochche: true,
  2971. headers: {
  2972. 'Cache-Control': 'no-cache'
  2973. }
  2974. });
  2975. if (result === 'Success') {
  2976. if (data?.responseText.includes('www.reddit.com/login/')) {
  2977. logStatus.error(`Error:${i18n('loginReddit')}`, true);
  2978. return false;
  2979. }
  2980. if (data?.status === 200) {
  2981. if (data.responseText.includes('redesign-beta-optin-btn') && !beta) {
  2982. return await this.#useBeta();
  2983. }
  2984. const accessToken = data.responseText.match(/"accessToken":"(.*?)","expires":"(.*?)"/)?.[1];
  2985. if (accessToken) {
  2986. this.#auth = {
  2987. token: accessToken
  2988. };
  2989. logStatus.success();
  2990. return true;
  2991. }
  2992. logStatus.error('Error: Parameter "accessToken" not found!');
  2993. return false;
  2994. }
  2995. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  2996. return false;
  2997. }
  2998. logStatus.error(`${result}:${statusText}(${status})`);
  2999. return false;
  3000. } catch (error) {
  3001. throwError(error, 'Reddit.updateAuth');
  3002. return false;
  3003. }
  3004. }
  3005. async #toggleTask({
  3006. name,
  3007. doTask = true
  3008. }) {
  3009. try {
  3010. if (!doTask && this.whiteList.reddits.includes(name)) {
  3011. scripts_echoLog({
  3012. type: 'whiteList',
  3013. text: 'Reddit.undoTask',
  3014. id: name
  3015. });
  3016. return true;
  3017. }
  3018. let type = doTask ? 'joiningReddit' : 'leavingReddit';
  3019. if (/^u_/.test(name)) {
  3020. type = doTask ? 'followingRedditUser' : 'unfollowingRedditUser';
  3021. }
  3022. const logStatus = scripts_echoLog({
  3023. type: type,
  3024. text: name
  3025. });
  3026. const {
  3027. result,
  3028. statusText,
  3029. status,
  3030. data
  3031. } = await tools_httpRequest({
  3032. url: 'https://oauth.reddit.com/api/subscribe?redditWebClient=desktop2x&app=desktop2x-client-production&raw_json=1&gilding_detail=1',
  3033. method: 'POST',
  3034. headers: {
  3035. authorization: `Bearer ${this.#auth.token}`,
  3036. 'content-type': 'application/x-www-form-urlencoded'
  3037. },
  3038. data: $.param({
  3039. action: doTask ? 'sub' : 'unsub',
  3040. sr_name: name,
  3041. api_type: 'json'
  3042. })
  3043. });
  3044. if (result === 'Success') {
  3045. if (data?.status === 200) {
  3046. logStatus.success();
  3047. if (doTask) {
  3048. this.tasks.reddits = unique([ ...this.tasks.reddits, name ]);
  3049. }
  3050. return true;
  3051. }
  3052. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3053. return false;
  3054. }
  3055. logStatus.error(`${result}:${statusText}(${status})`);
  3056. return false;
  3057. } catch (error) {
  3058. throwError(error, 'Reddit.toggleTask');
  3059. return false;
  3060. }
  3061. }
  3062. async toggle({
  3063. doTask = true,
  3064. redditLinks = []
  3065. }) {
  3066. try {
  3067. if (!this.#initialized) {
  3068. scripts_echoLog({
  3069. text: i18n('needInit')
  3070. });
  3071. return false;
  3072. }
  3073. const prom = [];
  3074. if (doTask && !globalOptions.doTask.reddit.reddits || !doTask && !globalOptions.undoTask.reddit.reddits) {
  3075. scripts_echoLog({
  3076. type: 'globalOptionsSkip',
  3077. text: 'reddit.reddits'
  3078. });
  3079. } else {
  3080. const realReddits = this.getRealParams('reddits', redditLinks, doTask, link => {
  3081. const name = link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1];
  3082. const userName = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1];
  3083. if (userName) {
  3084. return name || userName;
  3085. }
  3086. return name;
  3087. });
  3088. if (realReddits.length > 0) {
  3089. for (const name of realReddits) {
  3090. prom.push(this.#toggleTask({
  3091. name: name,
  3092. doTask: doTask
  3093. }));
  3094. await delay(1e3);
  3095. }
  3096. }
  3097. }
  3098. return await Promise.all(prom).then(() => true);
  3099. } catch (error) {
  3100. throwError(error, 'Reddit.toggle');
  3101. return false;
  3102. }
  3103. }
  3104. }
  3105. const social_Reddit = Reddit;
  3106. class Twitch extends social_Social {
  3107. tasks;
  3108. whiteList;
  3109. #auth = GM_getValue('twitchAuth') || {};
  3110. #cache = GM_getValue('twitchCache') || {};
  3111. #initialized = false;
  3112. #integrityToken;
  3113. constructor() {
  3114. super();
  3115. const defaultTasksTemplate = {
  3116. channels: []
  3117. };
  3118. this.tasks = defaultTasksTemplate;
  3119. this.whiteList = {
  3120. ...defaultTasksTemplate,
  3121. ...GM_getValue('whiteList')?.twitch || {}
  3122. };
  3123. }
  3124. async init() {
  3125. try {
  3126. if (this.#initialized) {
  3127. return true;
  3128. }
  3129. if (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId) {
  3130. if (await this.#updateAuth()) {
  3131. this.#initialized = true;
  3132. return true;
  3133. }
  3134. return false;
  3135. }
  3136. const isVerified = await this.#verifyAuth(true);
  3137. if (isVerified) {
  3138. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  3139. this.#initialized = true;
  3140. return true;
  3141. }
  3142. GM_setValue('twitchAuth', null);
  3143. if (await this.#updateAuth()) {
  3144. scripts_echoLog({}).success(i18n('initSuccess', 'Twitch'));
  3145. this.#initialized = true;
  3146. return true;
  3147. }
  3148. scripts_echoLog({}).error(i18n('initFailed', 'Twitch'));
  3149. return false;
  3150. } catch (error) {
  3151. throwError(error, 'Twitch.init');
  3152. return false;
  3153. }
  3154. }
  3155. async #verifyAuth(isFirst) {
  3156. try {
  3157. const logStatus = scripts_echoLog({
  3158. text: i18n('verifyingAuth', 'Twitch')
  3159. });
  3160. const {
  3161. result,
  3162. statusText,
  3163. status,
  3164. data
  3165. } = await tools_httpRequest({
  3166. url: 'https://gql.twitch.tv/gql',
  3167. method: 'POST',
  3168. dataType: 'json',
  3169. headers: {
  3170. Authorization: `OAuth ${this.#auth.authToken}`,
  3171. 'Client-Id': this.#auth.clientId
  3172. },
  3173. data: '[{"operationName":"FrontPageNew_User","variables":{"limit":1},"extensions":{"persistedQuery":{"version":1,' + '"sha256Hash":"64bd07a2cbaca80699d62636d966cf6395a5d14a1f0a14282067dcb28b13eb11"}}}]'
  3174. });
  3175. if (result === 'Success') {
  3176. if (data?.status === 200 && data.response?.[0]?.data?.currentUser) {
  3177. await this.#integrity(isFirst);
  3178. logStatus.success();
  3179. return true;
  3180. }
  3181. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3182. return false;
  3183. }
  3184. logStatus.error(`${result}:${statusText}(${status})`);
  3185. return false;
  3186. } catch (error) {
  3187. throwError(error, 'Twitch.verifyAuth');
  3188. return false;
  3189. }
  3190. }
  3191. async #integrity(isFirst = true, ct = '') {
  3192. try {
  3193. const logStatus = scripts_echoLog({
  3194. text: i18n('checkingTwitchIntegrity')
  3195. });
  3196. if (isFirst && (!this.#auth.authToken || !this.#auth.clientId || !this.#auth.clientVersion || !this.#auth.deviceId || !this.#auth.clientSessionId)) {
  3197. return await this.#updateAuth(false);
  3198. }
  3199. const {
  3200. result,
  3201. statusText,
  3202. status,
  3203. data
  3204. } = await tools_httpRequest({
  3205. url: 'https://gql.twitch.tv/integrity',
  3206. method: 'POST',
  3207. dataType: 'json',
  3208. anonymous: true,
  3209. headers: {
  3210. Origin: 'https://www.twitch.tv',
  3211. Referer: 'https://www.twitch.tv/',
  3212. Authorization: `OAuth ${this.#auth.authToken}`,
  3213. 'Client-Id': this.#auth.clientId,
  3214. 'Client-Version': this.#auth.clientVersion,
  3215. 'X-Device-Id': this.#auth.deviceId,
  3216. 'Client-Session-Id': this.#auth.clientSessionId,
  3217. 'x-kpsdk-ct': ct
  3218. }
  3219. });
  3220. if (result === 'Success') {
  3221. if (!ct && data?.responseHeaders?.['x-kpsdk-ct']) {
  3222. return await this.#integrity(isFirst, data.responseHeaders['x-kpsdk-ct']);
  3223. }
  3224. if (data?.status === 200 && data.response?.token) {
  3225. this.#integrityToken = data.response.token;
  3226. logStatus.success();
  3227. return true;
  3228. }
  3229. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3230. return false;
  3231. }
  3232. logStatus.error(`${result}:${statusText}(${status})`);
  3233. return false;
  3234. } catch (error) {
  3235. throwError(error, 'Twitch.integrity');
  3236. return false;
  3237. }
  3238. }
  3239. async #updateAuth(isFirst = true) {
  3240. try {
  3241. const logStatus = scripts_echoLog({
  3242. text: i18n('updatingAuth', 'Twitch')
  3243. });
  3244. return await new Promise(resolve => {
  3245. const newTab = GM_openInTab('https://www.twitch.tv/', {
  3246. active: true,
  3247. insert: true,
  3248. setParent: true
  3249. });
  3250. newTab.name = 'ATv4_twitchAuth';
  3251. newTab.onclose = async () => {
  3252. const auth = GM_getValue('twitchAuth');
  3253. if (auth) {
  3254. this.#auth = auth;
  3255. logStatus.success();
  3256. resolve(await this.#verifyAuth(isFirst));
  3257. } else {
  3258. logStatus.error('Error: Update twitch auth failed!');
  3259. resolve(false);
  3260. }
  3261. };
  3262. });
  3263. } catch (error) {
  3264. throwError(error, 'Twitch.updateAuth');
  3265. return false;
  3266. }
  3267. }
  3268. async #toggleChannel({
  3269. name,
  3270. doTask = true
  3271. }) {
  3272. try {
  3273. if (!doTask && this.whiteList.channels.includes(name)) {
  3274. scripts_echoLog({
  3275. type: 'whiteList',
  3276. text: 'Twitch.unfollowChannel',
  3277. id: name
  3278. });
  3279. return true;
  3280. }
  3281. const channelId = await this.#getChannelId(name);
  3282. if (!channelId) {
  3283. return false;
  3284. }
  3285. const logStatus = scripts_echoLog({
  3286. type: `${doTask ? '' : 'un'}followingTwitchChannel`,
  3287. text: name
  3288. });
  3289. const followData = `[{"operationName":"FollowButton_FollowUser","variables":{"input":{"disableNotifications":false,"targetID":"${channelId}` + '"}},"extensions":{"persistedQuery":{"version":1,"sha256Hash":"800e7346bdf7e5278a3c1d3f21b2b56e2639928f86815677a7126b093b2fdd08"}}}]';
  3290. const unfollowData = `[{"operationName":"FollowButton_UnfollowUser","variables":{"input":{"targetID":"${channelId}"}},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"f7dae976ebf41c755ae2d758546bfd176b4eeb856656098bb40e0a672ca0d880"}}}]';
  3291. const {
  3292. result,
  3293. statusText,
  3294. status,
  3295. data
  3296. } = await tools_httpRequest({
  3297. url: 'https://gql.twitch.tv/gql',
  3298. method: 'POST',
  3299. dataType: 'json',
  3300. anonymous: true,
  3301. headers: {
  3302. Origin: 'https://www.twitch.tv',
  3303. Referer: 'https://www.twitch.tv/',
  3304. Authorization: `OAuth ${this.#auth.authToken}`,
  3305. 'Client-Id': this.#auth.clientId,
  3306. 'Client-Version': this.#auth.clientVersion,
  3307. 'X-Device-Id': this.#auth.deviceId,
  3308. 'Client-Session-Id': this.#auth.clientSessionId,
  3309. 'Client-Integrity': this.#integrityToken
  3310. },
  3311. data: doTask ? followData : unfollowData
  3312. });
  3313. if (result === 'Success') {
  3314. if (data?.status === 200 && data.response?.[0] && !data.response[0].errors) {
  3315. logStatus.success();
  3316. if (doTask) {
  3317. this.tasks.channels = unique([ ...this.tasks.channels, name ]);
  3318. }
  3319. return true;
  3320. }
  3321. logStatus.error(`Error:${data?.response?.[0].errors?.[0]?.message || `${data?.statusText}(${data?.status})`}`);
  3322. return false;
  3323. }
  3324. logStatus.error(`${result}:${statusText}(${status})`);
  3325. return false;
  3326. } catch (error) {
  3327. throwError(error, 'Twitch.toggleChannel');
  3328. return false;
  3329. }
  3330. }
  3331. async #getChannelId(name) {
  3332. try {
  3333. const logStatus = scripts_echoLog({
  3334. type: 'gettingTwitchChannelId',
  3335. text: name
  3336. });
  3337. const channelId = this.#cache[name];
  3338. if (channelId) {
  3339. logStatus.success();
  3340. return channelId;
  3341. }
  3342. const {
  3343. result,
  3344. statusText,
  3345. status,
  3346. data
  3347. } = await tools_httpRequest({
  3348. url: 'https://gql.twitch.tv/gql',
  3349. method: 'POST',
  3350. headers: {
  3351. Authorization: `OAuth ${this.#auth.authToken}`,
  3352. 'Client-Id': this.#auth.clientId
  3353. },
  3354. responseType: 'json',
  3355. data: `[{"operationName":"ActiveWatchParty","variables":{"channelLogin":"${name}"},` + '"extensions":{"persistedQuery":{"version":1,"sha256Hash":"4a8156c97b19e3a36e081cf6d6ddb5dbf9f9b02ae60e4d2ff26ed70aebc80a30"}}}]'
  3356. });
  3357. if (result === 'Success') {
  3358. if (data?.status === 200) {
  3359. const channelId = data.response?.[0]?.data?.user?.id;
  3360. if (channelId) {
  3361. this.#setCache(name, String(channelId));
  3362. logStatus.success();
  3363. return channelId;
  3364. }
  3365. logStatus.error(`Error:${data.statusText}(${data.status})`);
  3366. return false;
  3367. }
  3368. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3369. return false;
  3370. }
  3371. logStatus.error(`${result}:${statusText}(${status})`);
  3372. return false;
  3373. } catch (error) {
  3374. throwError(error, 'Twitch.getChannelId');
  3375. return false;
  3376. }
  3377. }
  3378. async toggle({
  3379. doTask = true,
  3380. channelLinks = []
  3381. }) {
  3382. try {
  3383. if (!this.#initialized) {
  3384. scripts_echoLog({
  3385. text: i18n('needInit')
  3386. });
  3387. return false;
  3388. }
  3389. const prom = [];
  3390. if (doTask && !globalOptions.doTask.twitch.channels || !doTask && !globalOptions.undoTask.twitch.channels) {
  3391. scripts_echoLog({
  3392. type: 'globalOptionsSkip',
  3393. text: 'twitch.channels'
  3394. });
  3395. } else {
  3396. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2]);
  3397. if (realChannels.length > 0) {
  3398. for (const channel of realChannels) {
  3399. prom.push(this.#toggleChannel({
  3400. name: channel,
  3401. doTask: doTask
  3402. }));
  3403. await delay(1e3);
  3404. }
  3405. }
  3406. }
  3407. return Promise.all(prom).then(() => true);
  3408. } catch (error) {
  3409. throwError(error, 'Twitch.toggle');
  3410. return false;
  3411. }
  3412. }
  3413. #setCache(name, id) {
  3414. try {
  3415. this.#cache[name] = id;
  3416. GM_setValue('twitchCache', this.#cache);
  3417. } catch (error) {
  3418. throwError(error, 'Twitch.setCache');
  3419. }
  3420. }
  3421. }
  3422. const social_Twitch = Twitch;
  3423. var main = __webpack_require__(356);
  3424. class Twitter extends social_Social {
  3425. tasks;
  3426. whiteList;
  3427. #verifyId = globalOptions.other.twitterVerifyId;
  3428. #auth = GM_getValue('twitterAuth') || {};
  3429. #cache = GM_getValue('twitterCache') || {};
  3430. #initialized = false;
  3431. #session;
  3432. constructor() {
  3433. super();
  3434. const defaultTasksTemplate = {
  3435. users: [],
  3436. retweets: [],
  3437. likes: []
  3438. };
  3439. this.tasks = defaultTasksTemplate;
  3440. this.whiteList = {
  3441. ...defaultTasksTemplate,
  3442. ...GM_getValue('whiteList')?.twitter || {}
  3443. };
  3444. }
  3445. async init() {
  3446. try {
  3447. if (this.#initialized) {
  3448. return true;
  3449. }
  3450. if (!this.#auth.ct0) {
  3451. if (await this.#updateAuth()) {
  3452. this.#initialized = true;
  3453. return true;
  3454. }
  3455. return false;
  3456. }
  3457. this.#session = await (0, main.createSession)();
  3458. const isVerified = await this.#verifyAuth();
  3459. if (isVerified) {
  3460. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  3461. this.#initialized = true;
  3462. return true;
  3463. }
  3464. GM_setValue('twitterAuth', null);
  3465. if (await this.#updateAuth()) {
  3466. scripts_echoLog({}).success(i18n('initSuccess', 'Twitter'));
  3467. this.#initialized = true;
  3468. return true;
  3469. }
  3470. scripts_echoLog({}).error(i18n('initFailed', 'Twitter'));
  3471. return false;
  3472. } catch (error) {
  3473. throwError(error, 'Twitter.init');
  3474. return false;
  3475. }
  3476. }
  3477. async #verifyAuth() {
  3478. try {
  3479. return await this.#toggleUser({
  3480. name: 'verify',
  3481. doTask: true,
  3482. verify: true
  3483. });
  3484. } catch (error) {
  3485. throwError(error, 'Twitter.verifyAuth');
  3486. return false;
  3487. }
  3488. }
  3489. async #updateAuth() {
  3490. try {
  3491. const logStatus = scripts_echoLog({
  3492. text: i18n('updatingAuth', 'Twitter')
  3493. });
  3494. return await new Promise(resolve => {
  3495. GM_cookie.list({
  3496. url: 'https://x.com/settings/account'
  3497. }, async (cookies, error) => {
  3498. if (!error) {
  3499. const ct0 = cookies.find(cookie => cookie.name === 'ct0')?.value;
  3500. const isLogin = cookies.find(cookie => cookie.name === 'twid')?.value;
  3501. if (isLogin && ct0) {
  3502. GM_setValue('twitterAuth', {
  3503. ct0: ct0
  3504. });
  3505. this.#auth = {
  3506. ct0: ct0
  3507. };
  3508. logStatus.success();
  3509. resolve(await this.#verifyAuth());
  3510. } else {
  3511. logStatus.error(i18n('needLogin'));
  3512. resolve(false);
  3513. }
  3514. } else {
  3515. logStatus.error('Error: Update twitter auth failed!');
  3516. resolve(false);
  3517. }
  3518. });
  3519. });
  3520. } catch (error) {
  3521. throwError(error, 'Twitter.updateToken');
  3522. return false;
  3523. }
  3524. }
  3525. async #toggleUser({
  3526. name,
  3527. doTask = true,
  3528. verify = false,
  3529. retry = false
  3530. }) {
  3531. try {
  3532. if (!doTask && !verify && this.whiteList.users.includes(name)) {
  3533. scripts_echoLog({
  3534. type: 'whiteList',
  3535. text: 'Twitter.unfollowUser',
  3536. id: name
  3537. });
  3538. return true;
  3539. }
  3540. const userId = verify ? this.#verifyId : await this.userName2id(name);
  3541. if (!userId) {
  3542. return false;
  3543. }
  3544. const logStatus = verify ? scripts_echoLog({
  3545. text: i18n('verifyingAuth', 'Twitter')
  3546. }) : scripts_echoLog({
  3547. type: `${doTask ? '' : 'un'}followingTwitterUser`,
  3548. text: name
  3549. });
  3550. const {
  3551. result,
  3552. statusText,
  3553. status,
  3554. data
  3555. } = await tools_httpRequest({
  3556. url: `https://x.com/i/api/1.1/friendships/${doTask ? 'create' : 'destroy'}.json`,
  3557. method: 'POST',
  3558. headers: {
  3559. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3560. 'Content-Type': 'application/x-www-form-urlencoded',
  3561. 'x-csrf-token': this.#auth.ct0,
  3562. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3563. 'X-Twitter-Active-User': 'yes',
  3564. 'x-client-transaction-id': await this.#session.get('POST', `/i/api/1.1/friendships/${doTask ? 'create' : 'destroy'}.json`)
  3565. },
  3566. responseType: 'json',
  3567. data: $.param({
  3568. include_profile_interstitial_type: 1,
  3569. include_blocking: 1,
  3570. include_blocked_by: 1,
  3571. include_followed_by: 1,
  3572. include_want_retweets: 1,
  3573. include_mute_edge: 1,
  3574. include_can_dm: 1,
  3575. include_can_media_tag: 1,
  3576. skip_status: 1,
  3577. id: userId
  3578. })
  3579. });
  3580. if (result === 'Success') {
  3581. if (data?.status === 200) {
  3582. logStatus.success();
  3583. if (doTask && !verify) {
  3584. this.tasks.users = unique([ ...this.tasks.users, name ]);
  3585. }
  3586. return true;
  3587. }
  3588. if (verify && data?.status === 403) {
  3589. if (data.response?.errors?.[0]?.code === 158) {
  3590. logStatus.success();
  3591. return true;
  3592. }
  3593. if (data.response?.errors?.[0]?.code === 353 && !retry && data.responseHeaders?.['set-cookie']) {
  3594. this.#auth.ct0 = data.responseHeaders['set-cookie']?.find(cookie => cookie.includes('ct0='))?.split(';')?.at(0)?.split('=')?.at(-1) || this.#auth.ct0;
  3595. logStatus.warning(i18n('retry'));
  3596. return this.#toggleUser({
  3597. name: name,
  3598. doTask: doTask,
  3599. verify: verify,
  3600. retry: true
  3601. });
  3602. }
  3603. }
  3604. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3605. return false;
  3606. }
  3607. logStatus.error(`${result}:${statusText}(${status})`);
  3608. return false;
  3609. } catch (error) {
  3610. throwError(error, 'Twitter.toggleUser');
  3611. return false;
  3612. }
  3613. }
  3614. async userName2id(name) {
  3615. try {
  3616. const logStatus = scripts_echoLog({
  3617. type: 'gettingTwitterUserId',
  3618. text: name
  3619. });
  3620. const userId = this.#cache[name];
  3621. if (userId) {
  3622. logStatus.success();
  3623. return userId;
  3624. }
  3625. const {
  3626. result,
  3627. statusText,
  3628. status,
  3629. data
  3630. } = await tools_httpRequest({
  3631. 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`,
  3632. method: 'GET',
  3633. headers: {
  3634. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3635. 'content-type': 'application/json',
  3636. referer: `https://x.com/${name}`,
  3637. 'x-csrf-token': this.#auth.ct0,
  3638. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3639. 'X-Twitter-Active-User': 'yes',
  3640. '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`)
  3641. },
  3642. responseType: 'json'
  3643. });
  3644. if (result === 'Success') {
  3645. if (data?.status === 200) {
  3646. let response = data.response || (typeof data.responseText === 'object' ? data.responseText : null);
  3647. if (!response) {
  3648. try {
  3649. response = JSON.parse(data.responseText);
  3650. } catch (error) {
  3651. response = null;
  3652. }
  3653. }
  3654. const userId = String(response?.data?.user?.result?.rest_id);
  3655. if (userId) {
  3656. this.#setCache(name, userId);
  3657. logStatus.success();
  3658. return userId;
  3659. }
  3660. logStatus.error(`Error:${data.statusText}(${data.status})`);
  3661. return false;
  3662. }
  3663. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3664. return false;
  3665. }
  3666. logStatus.error(`${result}:${statusText}(${status})`);
  3667. return false;
  3668. } catch (error) {
  3669. throwError(error, 'Twitter.getUserId');
  3670. return false;
  3671. }
  3672. }
  3673. async #toggleRetweet({
  3674. retweetId,
  3675. doTask = true
  3676. }) {
  3677. try {
  3678. if (!doTask && this.whiteList.retweets.includes(retweetId)) {
  3679. scripts_echoLog({
  3680. type: 'whiteList',
  3681. text: 'Twitter.unretweet',
  3682. id: retweetId
  3683. });
  3684. return true;
  3685. }
  3686. const logStatus = scripts_echoLog({
  3687. type: `${doTask ? '' : 'un'}retweetting`,
  3688. text: retweetId
  3689. });
  3690. const {
  3691. result,
  3692. statusText,
  3693. status,
  3694. data
  3695. } = await tools_httpRequest({
  3696. url: `https://x.com/i/api/graphql/${doTask ? 'ojPdsZsimiJrUGLR1sjUtA/CreateRetweet' : 'iQtK4dl5hBmXewYZuEOKVw/DeleteRetweet'}`,
  3697. method: 'POST',
  3698. headers: {
  3699. authorization: 'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  3700. 'Content-Type': 'application/json',
  3701. origin: 'https://x.com',
  3702. referer: 'https://x.com/home',
  3703. 'x-csrf-token': this.#auth.ct0,
  3704. 'X-Twitter-Auth-Type': 'OAuth2Session',
  3705. 'X-Twitter-Active-User': 'yes',
  3706. 'x-client-transaction-id': await this.#session.get('POST', `/i/api/graphql/${doTask ? 'ojPdsZsimiJrUGLR1sjUtA/CreateRetweet' : 'iQtK4dl5hBmXewYZuEOKVw/DeleteRetweet'}`)
  3707. },
  3708. data: `{"variables":{"${doTask ? '' : 'source_'}tweet_id":"${retweetId}","dark_request":false},"queryId":"${doTask ? 'ojPdsZsimiJrUGLR1sjUtA' : 'iQtK4dl5hBmXewYZuEOKVw'}"}`,
  3709. responseType: 'json'
  3710. });
  3711. if (result === 'Success') {
  3712. if (data?.status === 200 || data?.status === 403 && data.response?.errors?.[0]?.code === 327) {
  3713. if (data.response?.errors && data.response?.errors?.[0]?.code !== 327) {
  3714. logStatus.error(`Error:${data.response?.errors?.[0]?.message}`);
  3715. return false;
  3716. }
  3717. logStatus.success();
  3718. if (doTask) {
  3719. this.tasks.retweets = unique([ ...this.tasks.retweets, retweetId ]);
  3720. }
  3721. return true;
  3722. }
  3723. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3724. return false;
  3725. }
  3726. logStatus.error(`${result}:${statusText}(${status})`);
  3727. return false;
  3728. } catch (error) {
  3729. throwError(error, 'Twitter.toggleRetweet');
  3730. return false;
  3731. }
  3732. }
  3733. async toggle({
  3734. doTask = true,
  3735. userLinks = [],
  3736. retweetLinks = []
  3737. }) {
  3738. try {
  3739. if (!this.#initialized) {
  3740. scripts_echoLog({
  3741. text: i18n('needInit')
  3742. });
  3743. return false;
  3744. }
  3745. const prom = [];
  3746. if (doTask && !globalOptions.doTask.twitter.users || !doTask && !globalOptions.undoTask.twitter.users) {
  3747. scripts_echoLog({
  3748. type: 'globalOptionsSkip',
  3749. text: 'twitter.users'
  3750. });
  3751. } else {
  3752. const realUsers = this.getRealParams('users', userLinks, doTask, link => link.match(/https:\/\/x\.com\/(.+)/)?.[1] || link.match(/https:\/\/twitter\.com\/(.+)/)?.[1]);
  3753. if (realUsers.length > 0) {
  3754. for (const user of realUsers) {
  3755. prom.push(this.#toggleUser({
  3756. name: user,
  3757. doTask: doTask
  3758. }));
  3759. await delay(1e3);
  3760. }
  3761. }
  3762. }
  3763. if (doTask && !globalOptions.doTask.twitter.retweets || !doTask && !globalOptions.undoTask.twitter.retweets) {
  3764. scripts_echoLog({
  3765. type: 'globalOptionsSkip',
  3766. text: 'twitter.retweets'
  3767. });
  3768. } else {
  3769. const realRetweets = this.getRealParams('retweets', retweetLinks, doTask, link => link.match(/https:\/\/x\.com\/.*?\/status\/([\d]+)/)?.[1] || link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1]);
  3770. if (realRetweets.length > 0) {
  3771. for (const retweet of realRetweets) {
  3772. prom.push(this.#toggleRetweet({
  3773. retweetId: retweet,
  3774. doTask: doTask
  3775. }));
  3776. await delay(1e3);
  3777. }
  3778. }
  3779. }
  3780. return Promise.all(prom).then(() => true);
  3781. } catch (error) {
  3782. throwError(error, 'Twitter.toggle');
  3783. return false;
  3784. }
  3785. }
  3786. #setCache(name, id) {
  3787. try {
  3788. this.#cache[name] = id;
  3789. GM_setValue('twitterCache', this.#cache);
  3790. } catch (error) {
  3791. throwError(error, 'Twitter.setCache');
  3792. }
  3793. }
  3794. }
  3795. const social_Twitter = Twitter;
  3796. class Vk extends social_Social {
  3797. tasks;
  3798. whiteList;
  3799. #username = '';
  3800. #cache = GM_getValue('vkCache') || {};
  3801. #initialized = false;
  3802. constructor() {
  3803. super();
  3804. const defaultTasksTemplate = {
  3805. names: []
  3806. };
  3807. this.tasks = defaultTasksTemplate;
  3808. this.whiteList = {
  3809. ...defaultTasksTemplate,
  3810. ...GM_getValue('whiteList')?.vk || {}
  3811. };
  3812. }
  3813. async init() {
  3814. try {
  3815. if (this.#initialized) {
  3816. return true;
  3817. }
  3818. const isVerified = await this.#verifyAuth();
  3819. if (isVerified) {
  3820. scripts_echoLog({}).success(i18n('initSuccess', 'Vk'));
  3821. this.#initialized = true;
  3822. return true;
  3823. }
  3824. scripts_echoLog({}).error(i18n('initFailed', 'Vk'));
  3825. return false;
  3826. } catch (error) {
  3827. throwError(error, 'Vk.init');
  3828. return false;
  3829. }
  3830. }
  3831. async #verifyAuth() {
  3832. try {
  3833. const logStatus = scripts_echoLog({
  3834. text: i18n('verifyAuth', 'Vk')
  3835. });
  3836. const {
  3837. result,
  3838. statusText,
  3839. status,
  3840. data
  3841. } = await tools_httpRequest({
  3842. url: 'https://vk.com/im',
  3843. method: 'GET'
  3844. });
  3845. if (result === 'Success') {
  3846. if (data?.finalUrl.includes('vk.com/login')) {
  3847. logStatus.error(`Error:${i18n('loginVk')}`, true);
  3848. return false;
  3849. }
  3850. if (data?.status === 200) {
  3851. this.#username = data.responseText.match(/TopNavBtn__profileLink" href="\/(.*?)"/)?.[1] || '';
  3852. logStatus.success();
  3853. return true;
  3854. }
  3855. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3856. return false;
  3857. }
  3858. logStatus.error(`${result}:${statusText}(${status})`);
  3859. return false;
  3860. } catch (error) {
  3861. throwError(error, 'Vk.verifyAuth');
  3862. return false;
  3863. }
  3864. }
  3865. async #toggleGroup(name, dataParam, doTask = true) {
  3866. try {
  3867. const logStatus = scripts_echoLog({
  3868. type: doTask ? 'joiningVkGroup' : 'leavingVkGroup',
  3869. text: name
  3870. });
  3871. if (dataParam.groupAct === 'enter' && !doTask || dataParam.groupAct === 'leave' && doTask) {
  3872. logStatus.success();
  3873. return true;
  3874. }
  3875. const reqData = {
  3876. act: doTask ? 'enter' : 'leave',
  3877. al: 1,
  3878. gid: dataParam.groupId,
  3879. hash: dataParam.groupHash
  3880. };
  3881. if (doTask) {
  3882. reqData.context = '_';
  3883. }
  3884. const {
  3885. result,
  3886. statusText,
  3887. status,
  3888. data
  3889. } = await tools_httpRequest({
  3890. url: 'https://vk.com/al_groups.php',
  3891. method: 'POST',
  3892. headers: {
  3893. origin: 'https://vk.com',
  3894. referer: `https://vk.com/${name}`,
  3895. 'content-type': 'application/x-www-form-urlencoded'
  3896. },
  3897. data: $.param(reqData)
  3898. });
  3899. if (result === 'Success') {
  3900. if (data?.status === 200) {
  3901. logStatus.success();
  3902. if (doTask) {
  3903. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3904. }
  3905. return true;
  3906. }
  3907. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3908. return false;
  3909. }
  3910. logStatus.error(`${result}:${statusText}(${status})`);
  3911. return false;
  3912. } catch (error) {
  3913. throwError(error, 'Vk.toggleGroup');
  3914. return false;
  3915. }
  3916. }
  3917. async #togglePublic(name, dataParam, doTask = true) {
  3918. try {
  3919. const logStatus = scripts_echoLog({
  3920. type: doTask ? 'joiningVkPublic' : 'leavingVkPublic',
  3921. text: name
  3922. });
  3923. if (dataParam.publicJoined && doTask || !dataParam.publicJoined && !doTask) {
  3924. logStatus.success();
  3925. return true;
  3926. }
  3927. const {
  3928. result,
  3929. statusText,
  3930. status,
  3931. data
  3932. } = await tools_httpRequest({
  3933. url: 'https://vk.com/al_public.php',
  3934. method: 'POST',
  3935. headers: {
  3936. origin: 'https://vk.com',
  3937. referer: `https://vk.com/${name}`,
  3938. 'content-type': 'application/x-www-form-urlencoded'
  3939. },
  3940. data: $.param({
  3941. act: doTask ? 'a_enter' : 'a_leave',
  3942. al: 1,
  3943. pid: dataParam.publicPid,
  3944. hash: dataParam.publicHash
  3945. })
  3946. });
  3947. if (result === 'Success') {
  3948. if (data?.status === 200) {
  3949. logStatus.success();
  3950. if (doTask) {
  3951. this.tasks.names = unique([ ...this.tasks.names, name ]);
  3952. }
  3953. return true;
  3954. }
  3955. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  3956. return false;
  3957. }
  3958. logStatus.error(`${result}:${statusText}(${status})`);
  3959. return false;
  3960. } catch (error) {
  3961. throwError(error, 'Vk.togglePublic');
  3962. return false;
  3963. }
  3964. }
  3965. async #toggleLikeWall(name, dataParam, doTask = true) {
  3966. try {
  3967. const logStatus = scripts_echoLog({
  3968. type: doTask ? 'likingVkPublic' : 'unlikingVkPublic',
  3969. text: name
  3970. });
  3971. const postData = {
  3972. act: 'a_set_reaction',
  3973. al: 1,
  3974. event_subtype: 'post_modal',
  3975. from: 'wall_page',
  3976. hash: dataParam.hash,
  3977. object: dataParam.object,
  3978. track_code: dataParam.trackCode,
  3979. wall: 2
  3980. };
  3981. if (doTask) {
  3982. postData.reaction_id = 0;
  3983. }
  3984. const {
  3985. result: resultR,
  3986. statusText: statusTextR,
  3987. status: statusR,
  3988. data: dataR
  3989. } = await tools_httpRequest({
  3990. url: 'https://vk.com/like.php?act=a_set_reaction',
  3991. method: 'POST',
  3992. headers: {
  3993. origin: 'https://vk.com',
  3994. referer: `https://vk.com/${name}`,
  3995. 'content-type': 'application/x-www-form-urlencoded'
  3996. },
  3997. data: $.param(postData)
  3998. });
  3999. if (resultR === 'Success') {
  4000. if (dataR?.status === 200) {
  4001. if (dataR.response?.payload?.[1]?.[1]?.like_my === true) {
  4002. logStatus.success();
  4003. return true;
  4004. }
  4005. }
  4006. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  4007. return false;
  4008. }
  4009. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  4010. return false;
  4011. } catch (error) {
  4012. throwError(error, 'Vk.sendWall');
  4013. return false;
  4014. }
  4015. }
  4016. async #sendWall(name) {
  4017. try {
  4018. const logStatus = scripts_echoLog({
  4019. type: 'sendingVkWall',
  4020. text: name
  4021. });
  4022. const {
  4023. result,
  4024. statusText,
  4025. status,
  4026. data
  4027. } = await tools_httpRequest({
  4028. url: 'https://vk.com/like.php',
  4029. method: 'POST',
  4030. headers: {
  4031. origin: 'https://vk.com',
  4032. referer: `https://vk.com/${name}`,
  4033. 'content-type': 'application/x-www-form-urlencoded'
  4034. },
  4035. data: $.param({
  4036. act: 'publish_box',
  4037. al: 1,
  4038. object: name
  4039. })
  4040. });
  4041. if (result === 'Success') {
  4042. if (data?.status === 200) {
  4043. const hash = data.responseText.match(/shHash:[\s]*'(.*?)'/)?.[1];
  4044. if (hash) {
  4045. const {
  4046. result: resultR,
  4047. statusText: statusTextR,
  4048. status: statusR,
  4049. data: dataR
  4050. } = await tools_httpRequest({
  4051. url: 'https://vk.com/like.php',
  4052. method: 'POST',
  4053. headers: {
  4054. origin: 'https://vk.com',
  4055. referer: `https://vk.com/${name}`,
  4056. 'content-type': 'application/x-www-form-urlencoded'
  4057. },
  4058. data: $.param({
  4059. Message: '',
  4060. act: 'a_do_publish',
  4061. al: 1,
  4062. close_comments: 0,
  4063. friends_only: 0,
  4064. from: 'box',
  4065. hash: hash,
  4066. list: '',
  4067. mark_as_ads: 0,
  4068. mute_notifications: 0,
  4069. object: name,
  4070. ret_data: 1,
  4071. to: 0
  4072. })
  4073. });
  4074. if (resultR === 'Success') {
  4075. if (dataR?.status === 200) {
  4076. const jsonData = JSON.parse(dataR.responseText?.replace('\x3c!--', '') || '{}');
  4077. if (jsonData?.payload?.[1]?.[1]?.share_my === true) {
  4078. logStatus.success();
  4079. const postId = String(jsonData?.payload?.[1]?.[1]?.post_id);
  4080. const ownerId = String(jsonData?.payload?.[1]?.[1]?.owner_id);
  4081. if (postId && ownerId) {
  4082. this.#setCache(name, `${ownerId}_${postId}`);
  4083. }
  4084. this.tasks.names = unique([ ...this.tasks.names, name ]);
  4085. return true;
  4086. }
  4087. }
  4088. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  4089. return false;
  4090. }
  4091. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  4092. return false;
  4093. }
  4094. logStatus.error('Error: Get "hash" failed');
  4095. return false;
  4096. }
  4097. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4098. return false;
  4099. }
  4100. logStatus.error(`${result}:${statusText}(${status})`);
  4101. return false;
  4102. } catch (error) {
  4103. throwError(error, 'Vk.sendWall');
  4104. return false;
  4105. }
  4106. }
  4107. async #deleteWall(name, dataParams) {
  4108. try {
  4109. const logStatus = scripts_echoLog({
  4110. type: 'deletingVkWall',
  4111. text: name
  4112. });
  4113. const {
  4114. result,
  4115. statusText,
  4116. status,
  4117. data
  4118. } = await tools_httpRequest({
  4119. url: 'https://vk.com/al_wall.php?act=delete',
  4120. method: 'POST',
  4121. headers: {
  4122. origin: 'https://vk.com',
  4123. referer: `https://vk.com/${this.#username}?w=wall${this.#cache[name]}%2Fall`,
  4124. 'content-type': 'application/x-www-form-urlencoded'
  4125. },
  4126. data: $.param({
  4127. act: 'delete',
  4128. al: 1,
  4129. confirm: 0,
  4130. from: 'wkview',
  4131. hash: dataParams.wallHash,
  4132. post: this.#cache[name]
  4133. })
  4134. });
  4135. if (result === 'Success') {
  4136. if (data?.status === 200) {
  4137. const jsonData = JSON.parse(data.responseText?.replace('\x3c!--', '') || '{}');
  4138. if (jsonData?.payload?.[1]?.[1]) {
  4139. logStatus.success();
  4140. return true;
  4141. }
  4142. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4143. return false;
  4144. }
  4145. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4146. return false;
  4147. }
  4148. logStatus.error(`${result}:${statusText}(${status})`);
  4149. return false;
  4150. } catch (error) {
  4151. throwError(error, 'Vk.deleteWall');
  4152. return false;
  4153. }
  4154. }
  4155. async #getId(name, doTask) {
  4156. try {
  4157. let url = `https://vk.com/${name}`;
  4158. if (/^wall-/.test(name)) {
  4159. if (doTask) {
  4160. return {
  4161. type: 'sendWall'
  4162. };
  4163. }
  4164. if (!this.#cache[name]) {
  4165. return {
  4166. type: 'unSupport'
  4167. };
  4168. }
  4169. url = `https://vk.com/${this.#username}?w=wall${this.#cache[name]}`;
  4170. }
  4171. const logStatus = scripts_echoLog({
  4172. type: 'gettingVkId',
  4173. text: name
  4174. });
  4175. const {
  4176. result,
  4177. statusText,
  4178. status,
  4179. data
  4180. } = await tools_httpRequest({
  4181. url: url,
  4182. method: 'GET'
  4183. });
  4184. if (result === 'Success') {
  4185. if (data?.status === 200) {
  4186. const [ , groupAct, groupId, , groupHash ] = data.responseText.match(/Groups.(enter|leave)\(.*?,.*?([\d]+?), (&#39;|')(.*?)(&#39;|')/) || [];
  4187. const publicHash = data.responseText.match(/"enterHash":"(.*?)"/)?.[1];
  4188. const publicPid = data.responseText.match(/"public_id":([\d]+?),/)?.[1];
  4189. const publicJoined = !data.responseText.includes('Public.subscribe');
  4190. if (groupAct && groupId && groupHash) {
  4191. logStatus.success();
  4192. return {
  4193. groupAct: groupAct,
  4194. groupId: groupId,
  4195. groupHash: groupHash,
  4196. type: 'group'
  4197. };
  4198. } else if (publicHash && publicPid) {
  4199. logStatus.success();
  4200. return {
  4201. publicHash: publicHash,
  4202. publicPid: publicPid,
  4203. publicJoined: publicJoined,
  4204. type: 'public'
  4205. };
  4206. } else if (name.includes('action=like')) {
  4207. const hash = data.responseText.match(/data-reaction-hash="(.*?)"/)?.[1];
  4208. const trackCode = data.responseText.match(/data-post-track-code="(.*?)"/)?.[1];
  4209. const object = name.match(/wall-[\w_]+/)?.[0];
  4210. if (hash && trackCode && object) {
  4211. logStatus.success();
  4212. return {
  4213. type: 'likeWall',
  4214. hash: hash,
  4215. trackCode: trackCode,
  4216. object: object
  4217. };
  4218. }
  4219. } else if (data.responseText.includes('wall.deletePost') && !doTask) {
  4220. const wallHash = data.responseText.match(/wall\.deletePost\(this, '.*?', '(.*?)'\)/)?.[1];
  4221. if (wallHash) {
  4222. logStatus.success();
  4223. return {
  4224. type: 'deleteWall',
  4225. wallHash: wallHash
  4226. };
  4227. }
  4228. } else if (name.includes('wall') && doTask) {
  4229. logStatus.success();
  4230. return {
  4231. type: 'sendWall'
  4232. };
  4233. }
  4234. logStatus.error('Error: Parameters not found!');
  4235. return false;
  4236. }
  4237. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4238. return false;
  4239. }
  4240. logStatus.error(`${result}:${statusText}(${status})`);
  4241. return false;
  4242. } catch (error) {
  4243. throwError(error, 'Vk.getId');
  4244. return false;
  4245. }
  4246. }
  4247. async #toggleVk({
  4248. name,
  4249. doTask = true
  4250. }) {
  4251. try {
  4252. if (!doTask && this.whiteList.names.includes(name)) {
  4253. scripts_echoLog({
  4254. type: 'whiteList',
  4255. text: 'Vk.undoTask',
  4256. id: name
  4257. });
  4258. return true;
  4259. }
  4260. const formatName = name.replace(/\/$/, '');
  4261. const data = await this.#getId(formatName, doTask);
  4262. if (!data) {
  4263. return false;
  4264. }
  4265. switch (data.type) {
  4266. case 'group':
  4267. return await this.#toggleGroup(formatName, data, doTask);
  4268.  
  4269. case 'public':
  4270. return await this.#togglePublic(formatName, data, doTask);
  4271.  
  4272. case 'likeWall':
  4273. return await this.#toggleLikeWall(formatName, data, doTask);
  4274.  
  4275. case 'sendWall':
  4276. return doTask ? await this.#sendWall(formatName) : true;
  4277.  
  4278. case 'deleteWall':
  4279. return doTask ? true : await this.#deleteWall(formatName, data);
  4280.  
  4281. default:
  4282. return false;
  4283. }
  4284. } catch (error) {
  4285. throwError(error, 'Vk.toggleVk');
  4286. return false;
  4287. }
  4288. }
  4289. async toggle({
  4290. doTask = true,
  4291. nameLinks = []
  4292. }) {
  4293. try {
  4294. if (!this.#initialized) {
  4295. scripts_echoLog({
  4296. text: i18n('needInit')
  4297. });
  4298. return false;
  4299. }
  4300. const prom = [];
  4301. if (doTask && !globalOptions.doTask.vk.names || !doTask && !globalOptions.undoTask.vk.names) {
  4302. scripts_echoLog({
  4303. type: 'globalOptionsSkip',
  4304. text: 'vk.names'
  4305. });
  4306. } else {
  4307. const realNames = this.getRealParams('names', nameLinks, doTask, link => link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1]);
  4308. if (realNames.length > 0) {
  4309. for (const name of realNames) {
  4310. prom.push(this.#toggleVk({
  4311. name: name,
  4312. doTask: doTask
  4313. }));
  4314. await delay(1e3);
  4315. }
  4316. }
  4317. }
  4318. return Promise.all(prom).then(() => true);
  4319. } catch (error) {
  4320. throwError(error, 'Vk.toggle');
  4321. return false;
  4322. }
  4323. }
  4324. #setCache(name, postId) {
  4325. try {
  4326. this.#cache[name] = postId;
  4327. GM_setValue('vkCache', this.#cache);
  4328. } catch (error) {
  4329. throwError(error, 'Vk.setCache');
  4330. }
  4331. }
  4332. }
  4333. const social_Vk = Vk;
  4334. const getInfo = async function(link, type) {
  4335. try {
  4336. const logStatus = scripts_echoLog({
  4337. text: i18n('gettingYtbToken')
  4338. });
  4339. const {
  4340. result,
  4341. statusText,
  4342. status,
  4343. data
  4344. } = await tools_httpRequest({
  4345. url: link,
  4346. method: 'GET'
  4347. });
  4348. if (result === 'Success') {
  4349. if (data?.status === 200) {
  4350. if (data.responseText.includes('accounts.google.com/ServiceLogin?service=youtube')) {
  4351. logStatus.error(`Error:${i18n('loginYtb')}`, true);
  4352. return {
  4353. needLogin: true
  4354. };
  4355. }
  4356. const apiKey = data.responseText.match(/"INNERTUBE_API_KEY":"(.*?)"/)?.[1];
  4357. const context = (data.responseText.match(/\(\{"INNERTUBE_CONTEXT":([\w\W]*?)\}\)/) || data.responseText.match(/"INNERTUBE_CONTEXT":([\w\W]*?\}),"INNERTUBE/))?.[1] || '{}';
  4358. const {
  4359. client,
  4360. request
  4361. } = JSON.parse(context);
  4362. if (apiKey && client && request) {
  4363. client.hl = 'en';
  4364. if (type === 'channel') {
  4365. const channelId = data.responseText.match(/"channelId":"(.+?)"/)?.[1];
  4366. if (channelId) {
  4367. logStatus.success();
  4368. return {
  4369. params: {
  4370. apiKey: apiKey,
  4371. client: client,
  4372. request: request,
  4373. channelId: channelId
  4374. }
  4375. };
  4376. }
  4377. logStatus.error('Error: Get "channelId" failed!');
  4378. return {};
  4379. } else if (type === 'likeVideo') {
  4380. const videoId = data.responseText.match(/<link rel="shortlinkUrl" href="https:\/\/youtu\.be\/(.*?)">/)?.[1];
  4381. const likeParams = data.responseText.match(/"likeParams":"(.*?)"/)?.[1];
  4382. if (videoId) {
  4383. logStatus.success();
  4384. return {
  4385. params: {
  4386. apiKey: apiKey,
  4387. client: client,
  4388. request: request,
  4389. videoId: videoId,
  4390. likeParams: likeParams
  4391. }
  4392. };
  4393. }
  4394. logStatus.error('Error: Get "videoId" failed!');
  4395. return {};
  4396. }
  4397. logStatus.error('Error: Unknown type');
  4398. return {};
  4399. }
  4400. logStatus.error('Error: Parameter "apiKey" not found!');
  4401. return {};
  4402. }
  4403. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4404. return {};
  4405. }
  4406. logStatus.error(`${result}:${statusText}(${status})`);
  4407. return {};
  4408. } catch (error) {
  4409. throwError(error, 'Youtube.getInfo');
  4410. return {};
  4411. }
  4412. };
  4413. class Youtube extends social_Social {
  4414. tasks;
  4415. whiteList;
  4416. #auth = GM_getValue('youtubeAuth') || {};
  4417. #initialized = false;
  4418. #verifyChannel = `https://www.youtube.com/channel/${globalOptions.other.youtubeVerifyChannel}`;
  4419. constructor() {
  4420. super();
  4421. const defaultTasksTemplate = {
  4422. channels: [],
  4423. likes: []
  4424. };
  4425. this.tasks = defaultTasksTemplate;
  4426. this.whiteList = {
  4427. ...defaultTasksTemplate,
  4428. ...GM_getValue('whiteList')?.youtube || {}
  4429. };
  4430. }
  4431. async init() {
  4432. try {
  4433. if (this.#initialized) {
  4434. return true;
  4435. }
  4436. if (!this.#auth.PAPISID) {
  4437. if (await this.#updateAuth()) {
  4438. this.#initialized = true;
  4439. return true;
  4440. }
  4441. return false;
  4442. }
  4443. const isVerified = await this.#verifyAuth();
  4444. if (isVerified) {
  4445. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  4446. this.#initialized = true;
  4447. return true;
  4448. }
  4449. GM_setValue('youtubeAuth', null);
  4450. if (await this.#updateAuth()) {
  4451. scripts_echoLog({}).success(i18n('initSuccess', 'Youtube'));
  4452. this.#initialized = true;
  4453. return true;
  4454. }
  4455. scripts_echoLog({}).error(i18n('initFailed', 'Youtube'));
  4456. return false;
  4457. } catch (error) {
  4458. throwError(error, 'Youtube.init');
  4459. return false;
  4460. }
  4461. }
  4462. async #verifyAuth() {
  4463. try {
  4464. return await this.#toggleChannel({
  4465. link: this.#verifyChannel,
  4466. doTask: true,
  4467. verify: true
  4468. });
  4469. } catch (error) {
  4470. throwError(error, 'Youtube.verifyAuth');
  4471. return false;
  4472. }
  4473. }
  4474. async #updateAuth() {
  4475. try {
  4476. const logStatus = scripts_echoLog({
  4477. text: i18n('updatingAuth', 'Youtube')
  4478. });
  4479. return await new Promise(resolve => {
  4480. GM_cookie.list({
  4481. url: 'https://www.youtube.com/@YouTube'
  4482. }, async (cookies, error) => {
  4483. if (!error) {
  4484. const PAPISID = cookies.find(cookie => cookie.name === '__Secure-3PAPISID')?.value;
  4485. if (PAPISID) {
  4486. GM_setValue('youtubeAuth', {
  4487. PAPISID: PAPISID
  4488. });
  4489. this.#auth = {
  4490. PAPISID: PAPISID
  4491. };
  4492. logStatus.success();
  4493. resolve(await this.#verifyAuth());
  4494. } else {
  4495. logStatus.error(i18n('needLogin'));
  4496. resolve(false);
  4497. }
  4498. } else {
  4499. logStatus.error('Error: Update youtube auth failed!');
  4500. resolve(false);
  4501. }
  4502. });
  4503. });
  4504. } catch (error) {
  4505. throwError(error, 'Youtube.updateAuth');
  4506. return false;
  4507. }
  4508. }
  4509. #getInfo(link, type) {
  4510. return getInfo(link, type);
  4511. }
  4512. async #toggleChannel({
  4513. link,
  4514. doTask = true,
  4515. verify = false
  4516. }) {
  4517. try {
  4518. const {
  4519. params,
  4520. needLogin
  4521. } = await this.#getInfo(link, 'channel');
  4522. const {
  4523. apiKey,
  4524. client,
  4525. request,
  4526. channelId
  4527. } = params || {};
  4528. if (needLogin) {
  4529. scripts_echoLog({
  4530. html: i18n('loginYtb')
  4531. });
  4532. return false;
  4533. }
  4534. if (!(apiKey && client && request && channelId)) {
  4535. scripts_echoLog({
  4536. text: '"getYtbToken" failed'
  4537. });
  4538. return false;
  4539. }
  4540. if (!doTask && !verify && this.whiteList.channels.includes(channelId)) {
  4541. scripts_echoLog({
  4542. type: 'whiteList',
  4543. text: 'Youtube.unfollowChannel',
  4544. id: channelId
  4545. });
  4546. return true;
  4547. }
  4548. const logStatus = verify ? scripts_echoLog({
  4549. text: i18n('verifyingAuth', 'Youtube')
  4550. }) : scripts_echoLog({
  4551. type: doTask ? 'followingYtbChannel' : 'unfollowingYtbChannel',
  4552. text: channelId
  4553. });
  4554. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  4555. const {
  4556. result,
  4557. statusText,
  4558. status,
  4559. data
  4560. } = await tools_httpRequest({
  4561. url: `https://www.youtube.com/youtubei/v1/subscription/${doTask ? '' : 'un'}subscribe?key=${apiKey}&prettyPrint=false`,
  4562. method: 'POST',
  4563. headers: {
  4564. origin: 'https://www.youtube.com',
  4565. referer: `https://www.youtube.com/channel/${channelId}`,
  4566. 'content-type': 'application/json',
  4567. 'x-goog-authuser': '0',
  4568. 'x-goog-visitor-id': client?.visitorData,
  4569. 'x-origin': 'https://www.youtube.com',
  4570. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  4571. },
  4572. data: JSON.stringify({
  4573. context: {
  4574. client: client,
  4575. request: {
  4576. sessionId: request?.sessionId,
  4577. internalExperimentFlags: [],
  4578. consistencyTokenJars: []
  4579. },
  4580. user: {}
  4581. },
  4582. channelIds: [ channelId ],
  4583. params: doTask ? 'EgIIAhgA' : 'CgIIAhgA'
  4584. })
  4585. });
  4586. if (result === 'Success') {
  4587. if (data?.status === 200) {
  4588. if (doTask && (/"subscribed":true/.test(data.responseText) || data.responseText.includes('The subscription already exists')) || !doTask && /"subscribed":false/.test(data.responseText)) {
  4589. logStatus.success();
  4590. if (doTask && !verify) {
  4591. this.tasks.channels = unique([ ...this.tasks.channels, link ]);
  4592. }
  4593. return true;
  4594. }
  4595. if (verify && data.responseText.includes('You may not subscribe to yourself')) {
  4596. logStatus.success();
  4597. return true;
  4598. }
  4599. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4600. return false;
  4601. }
  4602. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4603. return false;
  4604. }
  4605. logStatus.error(`${result}:${statusText}(${status})`);
  4606. return false;
  4607. } catch (error) {
  4608. throwError(error, 'Youtube.toggleChannel');
  4609. return false;
  4610. }
  4611. }
  4612. async #toggleLikeVideo({
  4613. link,
  4614. doTask = true
  4615. }) {
  4616. try {
  4617. const {
  4618. params,
  4619. needLogin
  4620. } = await this.#getInfo(link, 'likeVideo');
  4621. const {
  4622. apiKey,
  4623. client,
  4624. request,
  4625. videoId,
  4626. likeParams
  4627. } = params || {};
  4628. if (needLogin) {
  4629. scripts_echoLog({
  4630. html: `${i18n('loginYtb')}`
  4631. });
  4632. return false;
  4633. }
  4634. if (!(apiKey && client && request && videoId && likeParams)) {
  4635. scripts_echoLog({
  4636. text: '"getYtbToken" failed'
  4637. });
  4638. return false;
  4639. }
  4640. if (!doTask && this.whiteList.likes.includes(videoId)) {
  4641. scripts_echoLog({
  4642. type: 'whiteList',
  4643. text: 'Youtube.unlikeVideo',
  4644. id: videoId
  4645. });
  4646. return true;
  4647. }
  4648. const logStatus = scripts_echoLog({
  4649. type: doTask ? 'likingYtbVideo' : 'unlikingYtbVideo',
  4650. text: videoId
  4651. });
  4652. const nowTime = parseInt(String(new Date().getTime() / 1e3), 10);
  4653. const likeVideoData = {
  4654. context: {
  4655. client: client,
  4656. request: {
  4657. sessionId: request.sessionId,
  4658. internalExperimentFlags: [],
  4659. consistencyTokenJars: []
  4660. },
  4661. user: {}
  4662. },
  4663. target: {
  4664. videoId: videoId
  4665. }
  4666. };
  4667. if (doTask) {
  4668. if (likeParams) {
  4669. likeVideoData.params = likeParams;
  4670. } else {
  4671. logStatus.error('Empty likeParams');
  4672. return false;
  4673. }
  4674. }
  4675. const {
  4676. result,
  4677. statusText,
  4678. status,
  4679. data
  4680. } = await tools_httpRequest({
  4681. url: `https://www.youtube.com/youtubei/v1/like/${doTask ? '' : 'remove'}like?key=${apiKey}`,
  4682. method: 'POST',
  4683. headers: {
  4684. origin: 'https://www.youtube.com',
  4685. referer: `https://www.youtube.com/watch?v=${videoId}`,
  4686. 'content-type': 'application/json',
  4687. 'x-goog-authuser': '0',
  4688. 'x-goog-visitor-id': client.visitorData,
  4689. 'x-origin': 'https://www.youtube.com',
  4690. authorization: `SAPISIDHASH ${nowTime}_${sha1(`${nowTime} ${this.#auth.PAPISID} https://www.youtube.com`)}`
  4691. },
  4692. data: JSON.stringify(likeVideoData)
  4693. });
  4694. if (result === 'Success') {
  4695. if (data?.status === 200) {
  4696. if (doTask && data.responseText.includes('Added to Liked videos') || !doTask && (data.responseText.includes('Removed from Liked videos') || data.responseText.includes('Dislike removed'))) {
  4697. logStatus.success();
  4698. if (doTask) {
  4699. this.tasks.likes = unique([ ...this.tasks.likes, link ]);
  4700. }
  4701. return true;
  4702. }
  4703. logStatus.error(i18n('tryUpdateYtbAuth'), true);
  4704. return false;
  4705. }
  4706. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4707. return false;
  4708. }
  4709. logStatus.error(`${result}:${statusText}(${status})`);
  4710. return false;
  4711. } catch (error) {
  4712. throwError(error, 'Youtube.toggleLikeVideo');
  4713. return false;
  4714. }
  4715. }
  4716. async toggle({
  4717. doTask = true,
  4718. channelLinks = [],
  4719. videoLinks = []
  4720. }) {
  4721. try {
  4722. if (!this.#initialized) {
  4723. scripts_echoLog({
  4724. text: i18n('needInit')
  4725. });
  4726. return false;
  4727. }
  4728. const prom = [];
  4729. if (doTask && !globalOptions.doTask.youtube.channels || !doTask && !globalOptions.undoTask.youtube.channels) {
  4730. scripts_echoLog({
  4731. type: 'globalOptionsSkip',
  4732. text: 'youtube.channels'
  4733. });
  4734. } else {
  4735. const realChannels = this.getRealParams('channels', channelLinks, doTask, link => {
  4736. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4737. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4738. }
  4739. return link;
  4740. });
  4741. if (realChannels.length > 0) {
  4742. for (const channel of realChannels) {
  4743. prom.push(this.#toggleChannel({
  4744. link: channel,
  4745. doTask: doTask
  4746. }));
  4747. await delay(1e3);
  4748. }
  4749. }
  4750. }
  4751. if (doTask && !globalOptions.doTask.youtube.likes || !doTask && !globalOptions.undoTask.youtube.likes) {
  4752. scripts_echoLog({
  4753. type: 'globalOptionsSkip',
  4754. text: 'youtube.likes'
  4755. });
  4756. } else {
  4757. const realLikes = this.getRealParams('likes', videoLinks, doTask, link => {
  4758. if (/^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www\.youtube\.com\/.*/.test(link)) {
  4759. return link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1];
  4760. }
  4761. return link;
  4762. });
  4763. if (realLikes.length > 0) {
  4764. for (const video of realLikes) {
  4765. prom.push(this.#toggleLikeVideo({
  4766. link: video,
  4767. doTask: doTask
  4768. }));
  4769. await delay(1e3);
  4770. }
  4771. }
  4772. }
  4773. return Promise.all(prom).then(() => true);
  4774. } catch (error) {
  4775. throwError(error, 'Youtube.toggle');
  4776. return false;
  4777. }
  4778. }
  4779. }
  4780. class SteamASF {
  4781. #asfOptions;
  4782. #botName = 'asf';
  4783. #groupInfo;
  4784. async init() {
  4785. try {
  4786. const asfCommandsUrl = new URL('/Api/Command/', globalOptions.ASF.AsfIpcUrl);
  4787. this.#asfOptions = {
  4788. url: asfCommandsUrl.href,
  4789. method: 'POST',
  4790. responseType: 'json',
  4791. headers: {
  4792. accept: 'application/json',
  4793. 'Content-Type': 'application/json',
  4794. Host: asfCommandsUrl.host,
  4795. Origin: asfCommandsUrl.origin,
  4796. Referer: asfCommandsUrl.href,
  4797. Authentication: globalOptions.ASF.AsfIpcPassword
  4798. }
  4799. };
  4800. if (globalOptions.ASF.AsfBotname) {
  4801. this.#botName = globalOptions.ASF.AsfBotname;
  4802. }
  4803. const logStatus = scripts_echoLog({
  4804. text: i18n('initingASF')
  4805. });
  4806. const {
  4807. result,
  4808. statusText,
  4809. status,
  4810. data
  4811. } = await tools_httpRequest({
  4812. ...this.#asfOptions,
  4813. data: '{"Command":"!stats"}'
  4814. });
  4815. if (result === 'Success') {
  4816. if (data?.response?.Success === true && data.response.Message === 'OK' && data.response.Result) {
  4817. logStatus.success();
  4818. return true;
  4819. }
  4820. if (data?.response?.Result || data?.response?.Message) {
  4821. logStatus.error(data?.response?.Result || data.response.Message);
  4822. return false;
  4823. }
  4824. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  4825. return false;
  4826. }
  4827. logStatus.error(`${result}:${statusText}(${status})`);
  4828. return false;
  4829. } catch (error) {
  4830. throwError(error, 'SteamASF.init');
  4831. return false;
  4832. }
  4833. }
  4834. async joinGroup(groupName) {
  4835. try {
  4836. const logStatus = scripts_echoLog({
  4837. type: 'joiningSteamGroup',
  4838. text: groupName
  4839. });
  4840. const {
  4841. result,
  4842. statusText,
  4843. status,
  4844. data
  4845. } = await tools_httpRequest({
  4846. ...this.#asfOptions,
  4847. data: JSON.stringify({
  4848. Command: `!JOINGROUP ${this.#botName} ${groupName}`
  4849. })
  4850. });
  4851. if (result === 'Success') {
  4852. if (data?.status === 200 && [ '已加入', '已申请', 'Joined', 'Applied', 'Присоединился', 'costs' ].find(text => data.response?.Result?.includes(text))) {
  4853. logStatus.success();
  4854. return true;
  4855. }
  4856. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4857. return false;
  4858. }
  4859. logStatus.error(`${result}:${statusText}(${status})`);
  4860. return false;
  4861. } catch (error) {
  4862. throwError(error, 'SteamASF.joinGroup');
  4863. return false;
  4864. }
  4865. }
  4866. async leaveGroup(groupName) {
  4867. try {
  4868. if (!this.#groupInfo) {
  4869. if (!await this.#getGroupId()) {
  4870. return false;
  4871. }
  4872. }
  4873. const groupId = await this.#groupInfo[groupName];
  4874. if (!groupId) {
  4875. return false;
  4876. }
  4877. const logStatus = scripts_echoLog({
  4878. type: 'leavingSteamGroup',
  4879. text: groupName
  4880. });
  4881. const {
  4882. result,
  4883. statusText,
  4884. status,
  4885. data
  4886. } = await tools_httpRequest({
  4887. ...this.#asfOptions,
  4888. data: JSON.stringify({
  4889. Command: `!LEAVEGROUP ${this.#botName} ${groupId}`
  4890. })
  4891. });
  4892. if (result === 'Success') {
  4893. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4894. logStatus.success();
  4895. return true;
  4896. }
  4897. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4898. return false;
  4899. }
  4900. logStatus.error(`${result}:${statusText}(${status})`);
  4901. return false;
  4902. } catch (error) {
  4903. throwError(error, 'SteamASF.leaveGroup');
  4904. return false;
  4905. }
  4906. }
  4907. async #getGroupId() {
  4908. try {
  4909. const logStatus = scripts_echoLog({
  4910. type: 'gettingSteamGroupId',
  4911. text: 'All'
  4912. });
  4913. const {
  4914. result,
  4915. statusText,
  4916. status,
  4917. data
  4918. } = await tools_httpRequest({
  4919. ...this.#asfOptions,
  4920. data: JSON.stringify({
  4921. Command: `!GROUPLIST ${this.#botName}`
  4922. })
  4923. });
  4924. if (result === 'Success') {
  4925. if (data?.status === 200 && data.response?.Result?.includes('|')) {
  4926. this.#groupInfo = Object.fromEntries(data.response.Result.split('\n').map(line => {
  4927. const [ , name, id ] = line.trim().split('|');
  4928. if (name && id) {
  4929. return [ name, id ];
  4930. }
  4931. return null;
  4932. }).filter(ele => ele));
  4933. logStatus.success();
  4934. return true;
  4935. }
  4936. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4937. return false;
  4938. }
  4939. logStatus.error(`${result}:${statusText}(${status})`);
  4940. return false;
  4941. } catch (error) {
  4942. throwError(error, 'SteamASF.getGroupID');
  4943. return false;
  4944. }
  4945. }
  4946. async addToWishlist(gameId) {
  4947. try {
  4948. const logStatus = scripts_echoLog({
  4949. type: 'addingToWishlist',
  4950. text: gameId
  4951. });
  4952. if ((await this.#checkGame(gameId)).wishlist === true) {
  4953. logStatus.success();
  4954. return true;
  4955. }
  4956. const {
  4957. result,
  4958. statusText,
  4959. status,
  4960. data
  4961. } = await tools_httpRequest({
  4962. ...this.#asfOptions,
  4963. data: JSON.stringify({
  4964. Command: `!ADDWISHLIST ${this.#botName} ${gameId}`
  4965. })
  4966. });
  4967. if (result === 'Success') {
  4968. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  4969. logStatus.success();
  4970. return true;
  4971. }
  4972. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  4973. return false;
  4974. }
  4975. logStatus.error(`${result}:${statusText}(${status})`);
  4976. return false;
  4977. } catch (error) {
  4978. throwError(error, 'SteamASF.addToWishlist');
  4979. return false;
  4980. }
  4981. }
  4982. async removeFromWishlist(gameId) {
  4983. try {
  4984. const logStatus = scripts_echoLog({
  4985. type: 'removingFromWishlist',
  4986. text: gameId
  4987. });
  4988. if ((await this.#checkGame(gameId)).wishlist === false) {
  4989. logStatus.success();
  4990. return true;
  4991. }
  4992. const {
  4993. result,
  4994. statusText,
  4995. status,
  4996. data
  4997. } = await tools_httpRequest({
  4998. ...this.#asfOptions,
  4999. data: JSON.stringify({
  5000. Command: `!REMOVEWISHLIST ${this.#botName} ${gameId}`
  5001. })
  5002. });
  5003. if (result === 'Success') {
  5004. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  5005. logStatus.success();
  5006. return true;
  5007. }
  5008. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5009. return false;
  5010. }
  5011. logStatus.error(`${result}:${statusText}(${status})`);
  5012. return false;
  5013. } catch (error) {
  5014. throwError(error, 'SteamASF.removeFromWishlist');
  5015. return false;
  5016. }
  5017. }
  5018. async toggleFollowGame(gameId, doTask) {
  5019. try {
  5020. const logStatus = scripts_echoLog({
  5021. type: `${doTask ? '' : 'un'}followingGame`,
  5022. text: gameId
  5023. });
  5024. if (doTask && (await this.#checkGame(gameId)).followed === true || !doTask && (await this.#checkGame(gameId)).followed === false) {
  5025. logStatus.success();
  5026. return true;
  5027. }
  5028. const {
  5029. result,
  5030. statusText,
  5031. status,
  5032. data
  5033. } = await tools_httpRequest({
  5034. ...this.#asfOptions,
  5035. data: JSON.stringify({
  5036. Command: `!${doTask ? '' : 'UN'}FOLLOWGAME ${this.#botName} ${gameId}`
  5037. })
  5038. });
  5039. if (result === 'Success') {
  5040. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  5041. logStatus.success();
  5042. return true;
  5043. }
  5044. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5045. return false;
  5046. }
  5047. logStatus.error(`${result}:${statusText}(${status})`);
  5048. return false;
  5049. } catch (error) {
  5050. throwError(error, 'SteamASF.toggleFollowGame');
  5051. return false;
  5052. }
  5053. }
  5054. async #checkGame(gameId) {
  5055. try {
  5056. const {
  5057. result,
  5058. data
  5059. } = await tools_httpRequest({
  5060. ...this.#asfOptions,
  5061. data: JSON.stringify({
  5062. Command: `!CHECK ${this.#botName} ${gameId}`
  5063. })
  5064. });
  5065. if (result === 'Success') {
  5066. if (data?.status === 200 && data.response?.Result?.includes(gameId)) {
  5067. const matchedResult = data.response.Result.split('\n').find(result => result.includes(gameId))?.split('|');
  5068. if (matchedResult?.length > 3) {
  5069. return {
  5070. wishlist: matchedResult.at(-3).trim() === '√' || matchedResult.at(-2).trim() === '√',
  5071. followed: matchedResult.at(-1).trim() === '√'
  5072. };
  5073. }
  5074. return {};
  5075. }
  5076. return {};
  5077. }
  5078. return {};
  5079. } catch (error) {
  5080. throwError(error, 'SteamASF.checkGame');
  5081. return {};
  5082. }
  5083. }
  5084. async toggleCurator(curatorId, doTask = true) {
  5085. try {
  5086. const logStatus = scripts_echoLog({
  5087. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  5088. text: curatorId
  5089. });
  5090. const {
  5091. result,
  5092. statusText,
  5093. status,
  5094. data
  5095. } = await tools_httpRequest({
  5096. ...this.#asfOptions,
  5097. data: JSON.stringify({
  5098. Command: `!${doTask ? '' : 'UN'}FOLLOWCURATOR ${this.#botName} ${curatorId}`
  5099. })
  5100. });
  5101. if (result === 'Success') {
  5102. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  5103. logStatus.success();
  5104. return true;
  5105. }
  5106. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5107. return false;
  5108. }
  5109. logStatus.error(`${result}:${statusText}(${status})`);
  5110. return false;
  5111. } catch (error) {
  5112. throwError(error, 'Steam.toggleCurator');
  5113. return false;
  5114. }
  5115. }
  5116. async addLicense(id) {
  5117. try {
  5118. const [ type, ids ] = id.split('-');
  5119. const idsArr = ids.split(',');
  5120. if (type === 'appid') {
  5121. const logStatus = scripts_echoLog({
  5122. type: 'addingFreeLicense',
  5123. text: ids
  5124. });
  5125. const {
  5126. result,
  5127. statusText,
  5128. status,
  5129. data
  5130. } = await tools_httpRequest({
  5131. ...this.#asfOptions,
  5132. data: JSON.stringify({
  5133. Command: `!addlicense ${this.#botName} ${idsArr.map(id => `app/${id}`).join(',')}`
  5134. })
  5135. });
  5136. if (result === 'Success') {
  5137. if (data?.status === 200 && [ 'AlreadyPurchased', 'OK' ].find(text => data.response?.Result?.includes(text))) {
  5138. logStatus.success();
  5139. return true;
  5140. }
  5141. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5142. return false;
  5143. }
  5144. logStatus.error(`${result}:${statusText}(${status})`);
  5145. return false;
  5146. } else if (type === 'subid') {
  5147. const logStatus = scripts_echoLog({
  5148. type: 'addingFreeLicenseSubid',
  5149. text: ids
  5150. });
  5151. const {
  5152. result,
  5153. statusText,
  5154. status,
  5155. data
  5156. } = await tools_httpRequest({
  5157. ...this.#asfOptions,
  5158. data: JSON.stringify({
  5159. Command: `!addlicense ${this.#botName} ${idsArr.map(id => `sub/${id}`).join(',')}`
  5160. })
  5161. });
  5162. if (result === 'Success') {
  5163. if (data?.status === 200 && data.response?.Result) {
  5164. const resultLines = data.response.Result.split('\n');
  5165. idsArr.forEach(subid => {
  5166. const targetLine = resultLines.find(text => text.includes(subid));
  5167. if (targetLine && [ '成功', 'Success', 'Успех' ].find(text => targetLine.includes(text))) {
  5168. scripts_echoLog({}).success(targetLine);
  5169. } else {
  5170. scripts_echoLog({}).error(targetLine);
  5171. }
  5172. });
  5173. return true;
  5174. }
  5175. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5176. return false;
  5177. }
  5178. logStatus.error(`${result}:${statusText}(${status})`);
  5179. return false;
  5180. }
  5181. return false;
  5182. } catch (error) {
  5183. throwError(error, 'SteamASF.addLicense');
  5184. return false;
  5185. }
  5186. }
  5187. async requestPlayTestAccess(id) {
  5188. try {
  5189. const logStatus = scripts_echoLog({
  5190. type: 'requestingPlayTestAccess',
  5191. text: id
  5192. });
  5193. const {
  5194. result,
  5195. statusText,
  5196. status,
  5197. data
  5198. } = await tools_httpRequest({
  5199. ...this.#asfOptions,
  5200. data: JSON.stringify({
  5201. Command: `!REQUESTACCESS ${this.#botName} ${id}`
  5202. })
  5203. });
  5204. if (result === 'Success') {
  5205. if (data?.status === 200 && [ '成功', 'Success', 'Успех' ].find(text => data.response?.Result?.includes(text))) {
  5206. logStatus.success();
  5207. return true;
  5208. }
  5209. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5210. return false;
  5211. }
  5212. logStatus.error(`${result}:${statusText}(${status})`);
  5213. return false;
  5214. } catch (error) {
  5215. throwError(error, 'SteamASF.requestPlayTestAccess');
  5216. return false;
  5217. }
  5218. }
  5219. async playGames(ids) {
  5220. try {
  5221. await this.addLicense(`appid-${ids}`);
  5222. const logStatus = scripts_echoLog({
  5223. text: i18n('playingGames', ids)
  5224. });
  5225. const {
  5226. result,
  5227. statusText,
  5228. status,
  5229. data
  5230. } = await tools_httpRequest({
  5231. ...this.#asfOptions,
  5232. data: JSON.stringify({
  5233. Command: `!play ${this.#botName} ${ids}`
  5234. })
  5235. });
  5236. if (result === 'Success') {
  5237. if (data?.status === 200 && [ '正在运行' ].find(text => data.response?.Result?.includes(text))) {
  5238. logStatus.success();
  5239. return true;
  5240. }
  5241. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5242. return false;
  5243. }
  5244. logStatus.error(`${result}:${statusText}(${status})`);
  5245. return false;
  5246. } catch (error) {
  5247. throwError(error, 'SteamASF.playGames');
  5248. return false;
  5249. }
  5250. }
  5251. async stopPlayGames() {
  5252. try {
  5253. const logStatus = scripts_echoLog({
  5254. text: i18n('stoppingPlayGames')
  5255. });
  5256. const {
  5257. result,
  5258. statusText,
  5259. status,
  5260. data
  5261. } = await tools_httpRequest({
  5262. ...this.#asfOptions,
  5263. data: JSON.stringify({
  5264. Command: `!reset ${this.#botName}`
  5265. })
  5266. });
  5267. if (result === 'Success') {
  5268. if (data?.status === 200 && [ '完成' ].find(text => data.response?.Result?.includes(text))) {
  5269. logStatus.success();
  5270. return true;
  5271. }
  5272. logStatus.error(`Error:${data?.response?.Result || data?.response?.Message || data?.statusText}(${data?.status})`);
  5273. return false;
  5274. }
  5275. logStatus.error(`${result}:${statusText}(${status})`);
  5276. return false;
  5277. } catch (error) {
  5278. throwError(error, 'SteamASF.stopPlayGames');
  5279. return false;
  5280. }
  5281. }
  5282. }
  5283. const social_SteamASF = SteamASF;
  5284. class Steam extends social_Social {
  5285. tasks;
  5286. whiteList;
  5287. #cache = {
  5288. ...{
  5289. group: {},
  5290. officialGroup: {},
  5291. forum: {},
  5292. workshop: {},
  5293. curator: {}
  5294. },
  5295. ...GM_getValue('steamCache')
  5296. };
  5297. #auth = {};
  5298. #storeInitialized = false;
  5299. #communityInitialized = false;
  5300. #area = 'CN';
  5301. #oldArea;
  5302. #areaStatus = 'end';
  5303. #ASF;
  5304. constructor() {
  5305. super();
  5306. const defaultTasksTemplate = {
  5307. groups: [],
  5308. officialGroups: [],
  5309. wishlists: [],
  5310. follows: [],
  5311. forums: [],
  5312. workshops: [],
  5313. workshopVotes: [],
  5314. curators: [],
  5315. curatorLikes: [],
  5316. announcements: [],
  5317. licenses: [],
  5318. playtests: [],
  5319. playTime: []
  5320. };
  5321. this.tasks = defaultTasksTemplate;
  5322. this.whiteList = {
  5323. ...defaultTasksTemplate,
  5324. ...GM_getValue('whiteList')?.steam || {}
  5325. };
  5326. }
  5327. async init(type = 'all') {
  5328. try {
  5329. if (globalOptions.ASF.AsfEnabled && globalOptions.ASF.AsfIpcUrl && globalOptions.ASF.AsfIpcPassword) {
  5330. this.#ASF = new social_SteamASF();
  5331. if (await this.#ASF.init()) {
  5332. this.#storeInitialized = true;
  5333. this.#communityInitialized = true;
  5334. return true;
  5335. }
  5336. return false;
  5337. }
  5338. if (type === 'store') {
  5339. if (this.#storeInitialized) {
  5340. return true;
  5341. }
  5342. let storeInitialized = await this.#updateStoreAuth();
  5343. if (!storeInitialized) {
  5344. storeInitialized = await this.#updateStoreAuthTab();
  5345. }
  5346. this.#storeInitialized = storeInitialized;
  5347. if (!this.#storeInitialized) {
  5348. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  5349. return false;
  5350. }
  5351. scripts_echoLog({}).success(i18n('initSuccess', 'SteamStore'));
  5352. return true;
  5353. }
  5354. if (type === 'community') {
  5355. if (this.#communityInitialized) {
  5356. return true;
  5357. }
  5358. let communityInitialized = await this.#updateCommunityAuth();
  5359. if (!communityInitialized) {
  5360. communityInitialized = await this.#updateCommunityAuthTab();
  5361. GM_setValue('steamCommunityAuth', null);
  5362. }
  5363. this.#communityInitialized = communityInitialized;
  5364. if (!this.#communityInitialized) {
  5365. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  5366. return false;
  5367. }
  5368. scripts_echoLog({}).success(i18n('initSuccess', 'SteamCommunity'));
  5369. return true;
  5370. }
  5371. if (this.#storeInitialized && this.#communityInitialized) {
  5372. scripts_echoLog({}).success(i18n('initSuccess', 'Steam'));
  5373. return true;
  5374. }
  5375. scripts_echoLog({}).error(i18n('initFailed', 'Steam'));
  5376. return false;
  5377. } catch (error) {
  5378. throwError(error, 'Steam.init');
  5379. return false;
  5380. }
  5381. }
  5382. async #refreshToken(type = 'steamStore') {
  5383. try {
  5384. const host = {
  5385. steamStore: 'store.steampowered.com',
  5386. steamCommunity: 'steamcommunity.com'
  5387. };
  5388. const logStatus = scripts_echoLog({
  5389. text: i18n('refreshingToken', i18n(type))
  5390. });
  5391. const formData = new FormData();
  5392. formData.append('redir', `https://${host[type]}/`);
  5393. const {
  5394. result,
  5395. statusText,
  5396. status,
  5397. data
  5398. } = await tools_httpRequest({
  5399. url: 'https://login.steampowered.com/jwt/ajaxrefresh',
  5400. method: 'POST',
  5401. responseType: 'json',
  5402. headers: {
  5403. Host: 'login.steampowered.com',
  5404. Origin: `https://${host[type]}`,
  5405. Referer: `https://${host[type]}/`
  5406. },
  5407. data: formData
  5408. });
  5409. if (result === 'Success') {
  5410. if (data?.response?.success) {
  5411. if (await this.#setStoreToken(data.response, type)) {
  5412. logStatus.success();
  5413. return true;
  5414. }
  5415. logStatus.error('Error');
  5416. return false;
  5417. }
  5418. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5419. return false;
  5420. }
  5421. logStatus.error(`${result}:${statusText}(${status})`);
  5422. return false;
  5423. } catch (error) {
  5424. throwError(error, 'Steam.refreshToken');
  5425. return false;
  5426. }
  5427. }
  5428. async #setStoreToken(param, type) {
  5429. try {
  5430. const host = {
  5431. steamStore: 'store.steampowered.com',
  5432. steamCommunity: 'steamcommunity.com'
  5433. };
  5434. const logStatus = scripts_echoLog({
  5435. text: i18n('settingToken', i18n(type))
  5436. });
  5437. const formData = new FormData();
  5438. formData.append('steamID', param.steamID);
  5439. formData.append('nonce', param.nonce);
  5440. formData.append('redir', param.redir);
  5441. formData.append('auth', param.auth);
  5442. const {
  5443. result,
  5444. statusText,
  5445. status,
  5446. data
  5447. } = await tools_httpRequest({
  5448. url: `https://${host[type]}/login/settoken`,
  5449. method: 'POST',
  5450. headers: {
  5451. Accept: 'application/json, text/plain, */*',
  5452. Host: host[type],
  5453. Origin: `https://${host[type]}`
  5454. },
  5455. data: formData
  5456. });
  5457. if (result === 'Success') {
  5458. if (data?.status === 200) {
  5459. logStatus.success();
  5460. return true;
  5461. }
  5462. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5463. return false;
  5464. }
  5465. logStatus.error(`${result}:${statusText}(${status})`);
  5466. return false;
  5467. } catch (error) {
  5468. throwError(error, 'Steam.setStoreToken');
  5469. return false;
  5470. }
  5471. }
  5472. async #updateStoreAuth(retry = false) {
  5473. try {
  5474. const logStatus = scripts_echoLog({
  5475. text: i18n('updatingAuth', i18n('steamStore'))
  5476. });
  5477. const {
  5478. result,
  5479. statusText,
  5480. status,
  5481. data
  5482. } = await tools_httpRequest({
  5483. url: 'https://store.steampowered.com/',
  5484. method: 'GET',
  5485. headers: {
  5486. 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',
  5487. 'Sec-Fetch-Dest': 'document',
  5488. 'Sec-Fetch-Mode': 'navigate',
  5489. 'Upgrade-Insecure-Requests': '1'
  5490. },
  5491. fetch: false,
  5492. redirect: 'manual'
  5493. });
  5494. if (data?.status === 200) {
  5495. if (!data.responseText.includes('data-miniprofile=')) {
  5496. if (await this.#refreshToken('steamStore')) {
  5497. logStatus.warning(i18n('retry'));
  5498. if (retry) {
  5499. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  5500. return false;
  5501. }
  5502. return this.#updateStoreAuth(true);
  5503. }
  5504. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  5505. return false;
  5506. }
  5507. const storeSessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  5508. if (storeSessionID) {
  5509. this.#auth.storeSessionID = storeSessionID;
  5510. logStatus.success();
  5511. return true;
  5512. }
  5513. logStatus.error('Error: Get "sessionID" failed');
  5514. return false;
  5515. }
  5516. if ([ 301, 302 ].includes(data?.status)) {
  5517. if (await this.#refreshToken('steamStore')) {
  5518. logStatus.warning(i18n('retry'));
  5519. if (retry) {
  5520. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  5521. return false;
  5522. }
  5523. return this.#updateStoreAuth(true);
  5524. }
  5525. logStatus.error(`Error:${i18n('needLoginSteamStore')}`, true);
  5526. return false;
  5527. }
  5528. logStatus.error(`${result}:${statusText}(${status})`);
  5529. return false;
  5530. } catch (error) {
  5531. throwError(error, 'Steam.updateStoreAuth');
  5532. return false;
  5533. }
  5534. }
  5535. async #updateStoreAuthTab() {
  5536. try {
  5537. const logStatus = scripts_echoLog({
  5538. text: i18n('updatingAuth', i18n('steamStoreTab'))
  5539. });
  5540. return await new Promise(resolve => {
  5541. GM_deleteValue('steamStoreAuth');
  5542. GM_setValue('ATv4_updateStoreAuth', true);
  5543. const newTab = GM_openInTab('https://store.steampowered.com/', {
  5544. active: true,
  5545. setParent: true
  5546. });
  5547. newTab.name = 'ATv4_updateStoreAuth';
  5548. const listenerId = GM_addValueChangeListener('steamStoreAuth', (key, oldValue, newValue) => {
  5549. GM_removeValueChangeListener(listenerId);
  5550. GM_deleteValue('ATv4_updateStoreAuth');
  5551. newTab?.close();
  5552. window.focus();
  5553. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  5554. this.#auth.storeSessionID = newValue.storeSessionID;
  5555. logStatus.success();
  5556. resolve(true);
  5557. return;
  5558. }
  5559. logStatus.error('Failed');
  5560. resolve(false);
  5561. });
  5562. newTab.onclose = () => {
  5563. GM_deleteValue('ATv4_updateStoreAuth');
  5564. };
  5565. });
  5566. } catch (error) {
  5567. throwError(error, 'Steam.updateStoreAuthTab');
  5568. return false;
  5569. }
  5570. }
  5571. async #updateCommunityAuthTab() {
  5572. try {
  5573. const logStatus = scripts_echoLog({
  5574. text: i18n('updatingAuth', i18n('steamCommunityTab'))
  5575. });
  5576. return await new Promise(resolve => {
  5577. GM_deleteValue('steamCommunityAuth');
  5578. GM_setValue('ATv4_updateCommunityAuth', true);
  5579. const newTab = GM_openInTab('https://steamcommunity.com/my', {
  5580. active: true,
  5581. setParent: true
  5582. });
  5583. newTab.name = 'ATv4_updateCommunityAuth';
  5584. const listenerId = GM_addValueChangeListener('steamCommunityAuth', (key, oldValue, newValue) => {
  5585. GM_removeValueChangeListener(listenerId);
  5586. GM_deleteValue('ATv4_updateCommunityAuth');
  5587. newTab?.close();
  5588. window.focus();
  5589. if (newValue && JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
  5590. this.#auth.steam64Id = newValue.steam64Id;
  5591. this.#auth.communitySessionID = newValue.communitySessionID;
  5592. logStatus.success();
  5593. resolve(true);
  5594. return;
  5595. }
  5596. logStatus.error('Failed');
  5597. resolve(false);
  5598. });
  5599. newTab.onclose = () => {
  5600. GM_deleteValue('ATv4_updateCommunityAuth');
  5601. };
  5602. });
  5603. } catch (error) {
  5604. throwError(error, 'Steam.updateCommunityAuthTab');
  5605. return false;
  5606. }
  5607. }
  5608. async #updateCommunityAuth() {
  5609. try {
  5610. const logStatus = scripts_echoLog({
  5611. text: i18n('gettingUserLink')
  5612. });
  5613. const {
  5614. result,
  5615. statusText,
  5616. status,
  5617. data
  5618. } = await tools_httpRequest({
  5619. url: 'https://steamcommunity.com/my',
  5620. method: 'GET',
  5621. headers: {
  5622. 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',
  5623. Host: 'steamcommunity.com',
  5624. 'Sec-Fetch-Dest': 'document',
  5625. 'Sec-Fetch-Mode': 'navigate'
  5626. },
  5627. fetch: false
  5628. });
  5629. if (data?.status === 200) {
  5630. if (data.finalUrl.includes('https://steamcommunity.com/login/home')) {
  5631. logStatus.error(`Error:${i18n('needLoginSteamCommunity')}`, true);
  5632. return false;
  5633. }
  5634. const steam64Id = data.responseText.match(/g_steamID = "(.+?)";/)?.[1];
  5635. const communitySessionID = data.responseText.match(/g_sessionID = "(.+?)";/)?.[1];
  5636. if (steam64Id && communitySessionID) {
  5637. this.#auth.steam64Id = steam64Id;
  5638. this.#auth.communitySessionID = communitySessionID;
  5639. logStatus.success();
  5640. return true;
  5641. }
  5642. logStatus.error('Error: Get "sessionID" failed');
  5643. return false;
  5644. }
  5645. logStatus.error(`${result}:${statusText}(${status})`);
  5646. return false;
  5647. } catch (error) {
  5648. throwError(error, 'Steam.updateCommunityAuth');
  5649. return false;
  5650. }
  5651. }
  5652. async #getAreaInfo() {
  5653. try {
  5654. const logStatus = scripts_echoLog({
  5655. text: i18n('gettingAreaInfo')
  5656. });
  5657. const {
  5658. result,
  5659. statusText,
  5660. status,
  5661. data
  5662. } = await tools_httpRequest({
  5663. url: 'https://store.steampowered.com/cart/',
  5664. method: 'GET'
  5665. });
  5666. if (result === 'Success') {
  5667. if (data?.status === 200) {
  5668. const cartConfigRaw = data.responseText.match(/data-cart_config="(.*?)"/)?.[1];
  5669. const temp = document.createElement('div');
  5670. temp.innerHTML = cartConfigRaw || '{}';
  5671. const cartConfigStr = temp.textContent || temp.innerText;
  5672. let cartConfig;
  5673. try {
  5674. cartConfig = JSON.parse(cartConfigStr);
  5675. } catch (error) {
  5676. logStatus.error('Error: get country info filed');
  5677. console.error(error);
  5678. return {};
  5679. }
  5680. if (!cartConfig.rgUserCountryOptions) {
  5681. logStatus.warning('Warning: Area cannot be changed');
  5682. return {};
  5683. }
  5684. const userInfoRaw = data.responseText.match(/data-userinfo="(.*?)"/)?.[1];
  5685. const temp1 = document.createElement('div');
  5686. temp1.innerHTML = userInfoRaw || '{}';
  5687. const userInfoStr = temp1.textContent || temp1.innerText;
  5688. let userInfo;
  5689. try {
  5690. userInfo = JSON.parse(userInfoStr);
  5691. } catch (error) {
  5692. logStatus.error('Error: get country info filed');
  5693. console.error(error);
  5694. return {};
  5695. }
  5696. const currentArea = userInfo.country_code;
  5697. const areas = Object.keys(cartConfig.rgUserCountryOptions).filter(area => area !== 'help');
  5698. if (currentArea && areas.length > 0) {
  5699. this.#area = currentArea;
  5700. logStatus.success();
  5701. return {
  5702. currentArea: currentArea,
  5703. areas: areas
  5704. };
  5705. }
  5706. logStatus.error('Error: get country info filed');
  5707. return {};
  5708. }
  5709. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5710. return {};
  5711. }
  5712. logStatus.error(`${result}:${statusText}(${status})`);
  5713. return {};
  5714. } catch (error) {
  5715. throwError(error, 'Steam.getAreaInfo');
  5716. return {};
  5717. }
  5718. }
  5719. async #changeArea(area) {
  5720. try {
  5721. if (this.#areaStatus === 'waiting') {
  5722. await new Promise(resolve => {
  5723. const checker = setInterval(() => {
  5724. if (this.#areaStatus !== 'waiting') {
  5725. clearInterval(checker);
  5726. resolve(true);
  5727. }
  5728. });
  5729. });
  5730. }
  5731. if (this.#area === area || !area && this.#area !== 'CN') {
  5732. return true;
  5733. }
  5734. this.#areaStatus = 'waiting';
  5735. let aimedArea = area;
  5736. if (!aimedArea) {
  5737. const {
  5738. currentArea,
  5739. areas
  5740. } = await this.#getAreaInfo();
  5741. if (!currentArea || !areas) {
  5742. this.#areaStatus = 'error';
  5743. return false;
  5744. }
  5745. if (currentArea !== 'CN') {
  5746. this.#areaStatus = 'skip';
  5747. scripts_echoLog({
  5748. text: 'notNeededChangeArea'
  5749. });
  5750. return 'skip';
  5751. }
  5752. const anotherArea = areas.filter(area => area && area !== 'CN');
  5753. if (!anotherArea || anotherArea.length === 0) {
  5754. this.#areaStatus = 'noAnotherArea';
  5755. scripts_echoLog({
  5756. text: 'noAnotherArea'
  5757. });
  5758. return false;
  5759. }
  5760. [ aimedArea ] = anotherArea;
  5761. }
  5762. const logStatus = scripts_echoLog({
  5763. text: i18n('changingArea', aimedArea)
  5764. });
  5765. const {
  5766. result,
  5767. statusText,
  5768. status,
  5769. data
  5770. } = await tools_httpRequest({
  5771. url: 'https://store.steampowered.com/country/setcountry',
  5772. method: 'POST',
  5773. headers: {
  5774. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5775. },
  5776. data: $.param({
  5777. cc: aimedArea,
  5778. sessionid: this.#auth.storeSessionID
  5779. })
  5780. });
  5781. if (result === 'Success') {
  5782. if (data?.status === 200 && data.responseText === 'true') {
  5783. const {
  5784. currentArea
  5785. } = await this.#getAreaInfo();
  5786. if (currentArea) {
  5787. this.#area = currentArea;
  5788. if (!this.#oldArea) {
  5789. this.#oldArea = currentArea;
  5790. }
  5791. }
  5792. if (currentArea === aimedArea) {
  5793. this.#areaStatus = 'success';
  5794. logStatus.success();
  5795. return currentArea;
  5796. }
  5797. this.#areaStatus = 'error';
  5798. logStatus.error('Error: change country filed');
  5799. return 'CN';
  5800. }
  5801. this.#areaStatus = 'error';
  5802. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5803. return 'CN';
  5804. }
  5805. this.#areaStatus = 'error';
  5806. logStatus.error(`${result}:${statusText}(${status})`);
  5807. return 'CN';
  5808. } catch (error) {
  5809. this.#areaStatus = 'error';
  5810. throwError(error, 'Steam.changeArea');
  5811. return false;
  5812. }
  5813. }
  5814. async #joinGroup(groupName) {
  5815. try {
  5816. if (this.#ASF) {
  5817. if (await this.#ASF.joinGroup(groupName)) {
  5818. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5819. return true;
  5820. }
  5821. return false;
  5822. }
  5823. const logStatus = scripts_echoLog({
  5824. type: 'joiningSteamGroup',
  5825. text: groupName
  5826. });
  5827. const {
  5828. result,
  5829. statusText,
  5830. status,
  5831. data
  5832. } = await tools_httpRequest({
  5833. url: `https://steamcommunity.com/groups/${groupName}`,
  5834. method: 'POST',
  5835. headers: {
  5836. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5837. },
  5838. data: $.param({
  5839. action: 'join',
  5840. sessionID: this.#auth.communitySessionID
  5841. })
  5842. });
  5843. if (result === 'Success') {
  5844. if (data?.status === 200 && !data.responseText.includes('grouppage_join_area')) {
  5845. logStatus.success();
  5846. this.tasks.groups = unique([ ...this.tasks.groups, groupName ]);
  5847. return true;
  5848. }
  5849. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5850. return false;
  5851. }
  5852. logStatus.error(`${result}:${statusText}(${status})`);
  5853. return false;
  5854. } catch (error) {
  5855. throwError(error, 'Steam.joinGroup');
  5856. return false;
  5857. }
  5858. }
  5859. async #leaveGroup(groupName) {
  5860. try {
  5861. if (this.whiteList.groups.includes(groupName)) {
  5862. scripts_echoLog({
  5863. type: 'whiteList',
  5864. text: 'Steam.leaveGroup',
  5865. id: groupName
  5866. });
  5867. return true;
  5868. }
  5869. if (this.#ASF) {
  5870. return await this.#ASF.leaveGroup(groupName);
  5871. }
  5872. const groupId = await this.#getGroupId(groupName);
  5873. if (!groupId) {
  5874. return false;
  5875. }
  5876. const logStatus = scripts_echoLog({
  5877. type: 'leavingSteamGroup',
  5878. text: groupName
  5879. });
  5880. const {
  5881. result,
  5882. statusText,
  5883. status,
  5884. data
  5885. } = await tools_httpRequest({
  5886. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  5887. method: 'POST',
  5888. headers: {
  5889. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5890. },
  5891. data: $.param({
  5892. sessionID: this.#auth.communitySessionID,
  5893. action: 'leaveGroup',
  5894. groupId: groupId
  5895. })
  5896. });
  5897. if (result === 'Success') {
  5898. 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) {
  5899. logStatus.success();
  5900. return true;
  5901. }
  5902. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5903. return false;
  5904. }
  5905. logStatus.error(`${result}:${statusText}(${status})`);
  5906. return false;
  5907. } catch (error) {
  5908. throwError(error, 'Steam.leaveGroup');
  5909. return false;
  5910. }
  5911. }
  5912. async #getGroupId(groupName) {
  5913. try {
  5914. const logStatus = scripts_echoLog({
  5915. type: 'gettingSteamGroupId',
  5916. text: groupName
  5917. });
  5918. const groupId = this.#cache.group[groupName];
  5919. if (groupId) {
  5920. logStatus.success();
  5921. return groupId;
  5922. }
  5923. const {
  5924. result,
  5925. statusText,
  5926. status,
  5927. data
  5928. } = await tools_httpRequest({
  5929. url: `https://steamcommunity.com/groups/${groupName}`,
  5930. method: 'GET',
  5931. headers: {
  5932. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5933. }
  5934. });
  5935. if (result === 'Success') {
  5936. if (data?.status === 200) {
  5937. const groupId = data.responseText.match(/OpenGroupChat\( '([0-9]+)'/)?.[1];
  5938. if (groupId) {
  5939. this.#setCache('group', groupName, groupId);
  5940. logStatus.success();
  5941. return groupId;
  5942. }
  5943. logStatus.error(`Error:${data.statusText}(${data.status})`);
  5944. return false;
  5945. }
  5946. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5947. return false;
  5948. }
  5949. logStatus.error(`${result}:${statusText}(${status})`);
  5950. return false;
  5951. } catch (error) {
  5952. throwError(error, 'Steam.getGroupID');
  5953. return false;
  5954. }
  5955. }
  5956. async #joinOfficialGroup(gameId) {
  5957. try {
  5958. if (this.#ASF) {
  5959. if (await this.#ASF.joinGroup(gameId)) {
  5960. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5961. return true;
  5962. }
  5963. return false;
  5964. }
  5965. const logStatus = scripts_echoLog({
  5966. type: 'joiningSteamOfficialGroup',
  5967. text: gameId
  5968. });
  5969. const {
  5970. result,
  5971. statusText,
  5972. status,
  5973. data
  5974. } = await tools_httpRequest({
  5975. url: `https://steamcommunity.com/games/${gameId}?action=join&sessionID=${this.#auth.communitySessionID}`,
  5976. method: 'GET',
  5977. headers: {
  5978. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  5979. }
  5980. });
  5981. if (result === 'Success') {
  5982. if (data?.status === 200 && !data.responseText.includes('id="publicGroupJoin"')) {
  5983. logStatus.success();
  5984. this.tasks.officialGroups = unique([ ...this.tasks.officialGroups, gameId ]);
  5985. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  5986. if (groupId) {
  5987. this.#setCache('officialGroup', gameId, groupId);
  5988. }
  5989. return true;
  5990. }
  5991. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  5992. return false;
  5993. }
  5994. logStatus.error(`${result}:${statusText}(${status})`);
  5995. return false;
  5996. } catch (error) {
  5997. throwError(error, 'Steam.joinOfficialGroup');
  5998. return false;
  5999. }
  6000. }
  6001. async #leaveOfficialGroup(gameId) {
  6002. try {
  6003. if (this.whiteList.officialGroups.includes(gameId)) {
  6004. scripts_echoLog({
  6005. type: 'whiteList',
  6006. text: 'Steam.leaveOfficialGroup',
  6007. id: gameId
  6008. });
  6009. return true;
  6010. }
  6011. if (this.#ASF) {
  6012. return await this.#ASF.leaveGroup(gameId);
  6013. }
  6014. const groupId = await this.#getOfficialGroupId(gameId);
  6015. if (!groupId) {
  6016. return false;
  6017. }
  6018. const logStatus = scripts_echoLog({
  6019. type: 'leavingSteamOfficialGroup',
  6020. text: gameId
  6021. });
  6022. const {
  6023. result,
  6024. statusText,
  6025. status,
  6026. data
  6027. } = await tools_httpRequest({
  6028. url: `https://steamcommunity.com/profiles/${this.#auth.steam64Id}/home_process`,
  6029. method: 'POST',
  6030. headers: {
  6031. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6032. },
  6033. data: $.param({
  6034. sessionID: this.#auth.communitySessionID,
  6035. action: 'leaveGroup',
  6036. groupId: groupId
  6037. })
  6038. });
  6039. if (result === 'Success') {
  6040. if (data?.status === 200) {
  6041. const {
  6042. result: resultR,
  6043. statusText: statusTextR,
  6044. status: statusR,
  6045. data: dataR
  6046. } = await tools_httpRequest({
  6047. url: `https://steamcommunity.com/games/${gameId}`,
  6048. method: 'GET',
  6049. headers: {
  6050. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6051. }
  6052. });
  6053. if (resultR === 'Success') {
  6054. if (dataR?.status === 200 && dataR.responseText.includes('id="publicGroupJoin"')) {
  6055. logStatus.success();
  6056. return true;
  6057. }
  6058. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  6059. return false;
  6060. }
  6061. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  6062. return false;
  6063. }
  6064. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6065. return false;
  6066. }
  6067. logStatus.error(`${result}:${statusText}(${status})`);
  6068. return false;
  6069. } catch (error) {
  6070. throwError(error, 'Steam.leaveOfficialGroup');
  6071. return false;
  6072. }
  6073. }
  6074. async #getOfficialGroupId(gameId) {
  6075. try {
  6076. const logStatus = scripts_echoLog({
  6077. type: 'gettingSteamOfficialGroupId',
  6078. text: gameId
  6079. });
  6080. const groupId = this.#cache.officialGroup[gameId];
  6081. if (groupId) {
  6082. logStatus.success();
  6083. return groupId;
  6084. }
  6085. const {
  6086. result,
  6087. statusText,
  6088. status,
  6089. data
  6090. } = await tools_httpRequest({
  6091. url: `https://steamcommunity.com/games/${gameId}`,
  6092. method: 'GET',
  6093. headers: {
  6094. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6095. }
  6096. });
  6097. if (result === 'Success') {
  6098. if (data?.status === 200) {
  6099. const groupId = data.responseText.match(/steam:\/\/friends\/joinchat\/([0-9]+)/)?.[1];
  6100. if (groupId) {
  6101. this.#setCache('officialGroup', gameId, groupId);
  6102. logStatus.success();
  6103. return groupId;
  6104. }
  6105. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6106. return false;
  6107. }
  6108. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6109. return false;
  6110. }
  6111. logStatus.error(`${result}:${statusText}(${status})`);
  6112. return false;
  6113. } catch (error) {
  6114. throwError(error, 'Steam.getGroupID');
  6115. return false;
  6116. }
  6117. }
  6118. async #addToWishlist(gameId) {
  6119. try {
  6120. if (this.#ASF) {
  6121. if (await this.#ASF.addToWishlist(gameId)) {
  6122. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  6123. return true;
  6124. }
  6125. return false;
  6126. }
  6127. const logStatus = scripts_echoLog({
  6128. type: 'addingToWishlist',
  6129. text: gameId
  6130. });
  6131. const {
  6132. result,
  6133. data
  6134. } = await tools_httpRequest({
  6135. url: 'https://store.steampowered.com/api/addtowishlist',
  6136. method: 'POST',
  6137. headers: {
  6138. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6139. },
  6140. data: $.param({
  6141. sessionid: this.#auth.storeSessionID,
  6142. appid: gameId
  6143. }),
  6144. dataType: 'json'
  6145. });
  6146. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  6147. logStatus.success();
  6148. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  6149. return true;
  6150. }
  6151. const {
  6152. result: resultR,
  6153. statusText: statusTextR,
  6154. status: statusR,
  6155. data: dataR
  6156. } = await tools_httpRequest({
  6157. url: `https://store.steampowered.com/app/${gameId}`,
  6158. method: 'GET'
  6159. });
  6160. if (resultR === 'Success') {
  6161. if (dataR?.status === 200) {
  6162. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  6163. logStatus.warning(i18n('changeAreaNotice'));
  6164. if (!await this.#changeArea()) {
  6165. return false;
  6166. }
  6167. return await this.#addToWishlist(gameId);
  6168. }
  6169. if (dataR.responseText.includes('class="queue_actions_ctn"') && dataR.responseText.includes('class="already_in_library"')) {
  6170. logStatus.success();
  6171. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  6172. return true;
  6173. } 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"')) {
  6174. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  6175. return false;
  6176. }
  6177. logStatus.success();
  6178. this.tasks.wishlists = unique([ ...this.tasks.wishlists, gameId ]);
  6179. return true;
  6180. }
  6181. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  6182. return false;
  6183. }
  6184. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  6185. return false;
  6186. } catch (error) {
  6187. throwError(error, 'Steam.addToWishlist');
  6188. return false;
  6189. }
  6190. }
  6191. async #removeFromWishlist(gameId) {
  6192. try {
  6193. if (this.whiteList.wishlists.includes(gameId)) {
  6194. scripts_echoLog({
  6195. type: 'whiteList',
  6196. text: 'Steam.removeFromWishlist',
  6197. id: gameId
  6198. });
  6199. return true;
  6200. }
  6201. if (this.#ASF) {
  6202. return await this.#ASF.removeFromWishlist(gameId);
  6203. }
  6204. const logStatus = scripts_echoLog({
  6205. type: 'removingFromWishlist',
  6206. text: gameId
  6207. });
  6208. const {
  6209. result,
  6210. data
  6211. } = await tools_httpRequest({
  6212. url: 'https://store.steampowered.com/api/removefromwishlist',
  6213. method: 'POST',
  6214. headers: {
  6215. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6216. },
  6217. data: $.param({
  6218. sessionid: this.#auth.storeSessionID,
  6219. appid: gameId
  6220. }),
  6221. dataType: 'json'
  6222. });
  6223. if (result === 'Success' && data?.status === 200 && data.response?.success === true) {
  6224. logStatus.success();
  6225. return true;
  6226. }
  6227. const {
  6228. result: resultR,
  6229. statusText: statusTextR,
  6230. status: statusR,
  6231. data: dataR
  6232. } = await tools_httpRequest({
  6233. url: `https://store.steampowered.com/app/${gameId}`,
  6234. method: 'GET'
  6235. });
  6236. if (resultR === 'Success') {
  6237. if (dataR?.status === 200) {
  6238. if (this.#area === 'CN' && dataR.responseText.includes('id="error_box"')) {
  6239. logStatus.warning(i18n('changeAreaNotice'));
  6240. const result = await this.#changeArea();
  6241. if (!result || result === 'CN' || result === 'skip') {
  6242. return false;
  6243. }
  6244. return await this.#removeFromWishlist(gameId);
  6245. }
  6246. if (dataR.responseText.includes('class="queue_actions_ctn"') && (dataR.responseText.includes('ds_owned_flag ds_flag') || dataR.responseText.includes('add_to_wishlist_area'))) {
  6247. logStatus.success();
  6248. return true;
  6249. }
  6250. logStatus.error(`Error:${dataR.statusText}(${dataR.status})`);
  6251. return false;
  6252. }
  6253. logStatus.error(`Error:${dataR?.statusText}(${dataR?.status})`);
  6254. return false;
  6255. }
  6256. logStatus.error(`${resultR}:${statusTextR}(${statusR})`);
  6257. return false;
  6258. } catch (error) {
  6259. throwError(error, 'Steam.removeFromWishlist');
  6260. return false;
  6261. }
  6262. }
  6263. async #toggleFollowGame(gameId, doTask) {
  6264. try {
  6265. if (!doTask && this.whiteList.follows.includes(gameId)) {
  6266. scripts_echoLog({
  6267. type: 'whiteList',
  6268. text: 'Steam.unfollowGame',
  6269. id: gameId
  6270. });
  6271. return true;
  6272. }
  6273. if (this.#ASF) {
  6274. if (await this.#ASF.toggleFollowGame(gameId, doTask)) {
  6275. if (doTask) {
  6276. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  6277. }
  6278. return true;
  6279. }
  6280. return false;
  6281. }
  6282. const logStatus = scripts_echoLog({
  6283. type: `${doTask ? '' : 'un'}followingGame`,
  6284. text: gameId
  6285. });
  6286. const requestData = {
  6287. sessionid: this.#auth.storeSessionID,
  6288. appid: gameId
  6289. };
  6290. if (!doTask) {
  6291. requestData.unfollow = '1';
  6292. }
  6293. const {
  6294. result,
  6295. data
  6296. } = await tools_httpRequest({
  6297. url: 'https://store.steampowered.com/explore/followgame/',
  6298. method: 'POST',
  6299. headers: {
  6300. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6301. },
  6302. data: $.param(requestData)
  6303. });
  6304. if (result === 'Success' && data?.status === 200 && data.responseText === 'true') {
  6305. logStatus.success();
  6306. return true;
  6307. }
  6308. const followed = await this.#isFollowedGame(gameId);
  6309. if (this.#area === 'CN' && followed === 'areaLocked') {
  6310. logStatus.warning(i18n('changeAreaNotice'));
  6311. if (!await this.#changeArea()) {
  6312. return false;
  6313. }
  6314. return await this.#toggleFollowGame(gameId, doTask);
  6315. }
  6316. if (doTask === followed) {
  6317. logStatus.success();
  6318. if (doTask) {
  6319. this.tasks.follows = unique([ ...this.tasks.follows, gameId ]);
  6320. }
  6321. return true;
  6322. }
  6323. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6324. return false;
  6325. } catch (error) {
  6326. throwError(error, 'Steam.toggleFollowGame');
  6327. return false;
  6328. }
  6329. }
  6330. async #isFollowedGame(gameId) {
  6331. try {
  6332. const {
  6333. result,
  6334. data
  6335. } = await tools_httpRequest({
  6336. url: `https://store.steampowered.com/app/${gameId}`,
  6337. method: 'GET'
  6338. });
  6339. if (result === 'Success') {
  6340. if (data?.status === 200) {
  6341. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6342. return 'areaLocked';
  6343. }
  6344. if ($(data.responseText.replace(/<img.*?>/g, '')).find('.queue_control_button.queue_btn_follow>.btnv6_blue_hoverfade.btn_medium.queue_btn_active').css('display') !== 'none') {
  6345. return true;
  6346. }
  6347. return false;
  6348. }
  6349. return false;
  6350. }
  6351. return false;
  6352. } catch (error) {
  6353. throwError(error, 'Steam.isFollowedGame');
  6354. return false;
  6355. }
  6356. }
  6357. async #toggleForum(gameId, doTask = true) {
  6358. try {
  6359. if (!doTask && this.whiteList.forums.includes(gameId)) {
  6360. scripts_echoLog({
  6361. type: 'whiteList',
  6362. text: 'Steam.unsubscribeForum',
  6363. id: gameId
  6364. });
  6365. return true;
  6366. }
  6367. const forumId = await this.#getForumId(gameId);
  6368. if (!forumId) {
  6369. return false;
  6370. }
  6371. const logStatus = scripts_echoLog({
  6372. type: `${doTask ? '' : 'un'}subscribingForum`,
  6373. text: gameId
  6374. });
  6375. const [ id, feature ] = forumId.split('_');
  6376. const {
  6377. result,
  6378. statusText,
  6379. status,
  6380. data
  6381. } = await tools_httpRequest({
  6382. url: `https://steamcommunity.com/forum/${id}/General/${doTask ? '' : 'un'}subscribe/${feature || '0'}/`,
  6383. method: 'POST',
  6384. responseType: 'json',
  6385. headers: {
  6386. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6387. },
  6388. data: $.param({
  6389. sessionid: this.#auth.communitySessionID
  6390. })
  6391. });
  6392. if (result === 'Success') {
  6393. if (data?.status === 200 && (data.response?.success === 1 || data.response?.success === 29)) {
  6394. if (doTask) {
  6395. this.tasks.forums = unique([ ...this.tasks.forums, gameId ]);
  6396. }
  6397. logStatus.success();
  6398. return true;
  6399. }
  6400. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6401. return true;
  6402. }
  6403. logStatus.error(`${result}:${statusText}(${status})`);
  6404. return true;
  6405. } catch (error) {
  6406. throwError(error, 'Steam.toggleForum');
  6407. return true;
  6408. }
  6409. }
  6410. async #getForumId(gameId) {
  6411. try {
  6412. const logStatus = scripts_echoLog({
  6413. type: 'gettingForumId',
  6414. text: gameId
  6415. });
  6416. const forumId = this.#cache.forum[gameId];
  6417. if (forumId) {
  6418. logStatus.success();
  6419. return forumId;
  6420. }
  6421. const {
  6422. result,
  6423. statusText,
  6424. status,
  6425. data
  6426. } = await tools_httpRequest({
  6427. url: `https://steamcommunity.com/app/${gameId}/discussions/`,
  6428. method: 'GET'
  6429. });
  6430. if (result === 'Success') {
  6431. if (data?.status === 200) {
  6432. const forumId = data.responseText?.match(/General_([\d]+(_[\d]+)?)/)?.[1];
  6433. if (forumId) {
  6434. this.#setCache('forum', gameId, forumId);
  6435. logStatus.success();
  6436. return forumId;
  6437. }
  6438. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6439. return false;
  6440. }
  6441. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6442. return false;
  6443. }
  6444. logStatus.error(`${result}:${statusText}(${status})`);
  6445. return false;
  6446. } catch (error) {
  6447. throwError(error, 'Steam.getForumId');
  6448. return false;
  6449. }
  6450. }
  6451. async #toggleFavoriteWorkshop(id, doTask = true) {
  6452. try {
  6453. if (!doTask && this.whiteList.workshops.includes(id)) {
  6454. scripts_echoLog({
  6455. type: 'whiteList',
  6456. text: 'Steam.unfavoriteWorkshop',
  6457. id: id
  6458. });
  6459. return true;
  6460. }
  6461. const appid = await this.#getWorkshopAppId(id);
  6462. if (!appid) {
  6463. return false;
  6464. }
  6465. const logStatus = scripts_echoLog({
  6466. type: doTask ? 'favoritingWorkshop' : 'unfavoritingWorkshop',
  6467. text: id
  6468. });
  6469. const {
  6470. result,
  6471. statusText,
  6472. status,
  6473. data
  6474. } = await tools_httpRequest({
  6475. url: `https://steamcommunity.com/sharedfiles/${doTask ? '' : 'un'}favorite`,
  6476. method: 'POST',
  6477. headers: {
  6478. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6479. },
  6480. data: $.param({
  6481. id: id,
  6482. appid: appid,
  6483. sessionid: this.#auth.communitySessionID
  6484. })
  6485. });
  6486. if (result === 'Success') {
  6487. if (data?.status === 200 && !data.responseText) {
  6488. if (doTask) {
  6489. this.tasks.workshops = unique([ ...this.tasks.workshops, id ]);
  6490. }
  6491. logStatus.success();
  6492. return true;
  6493. }
  6494. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6495. return false;
  6496. }
  6497. logStatus.error(`${result}:${statusText}(${status})`);
  6498. return false;
  6499. } catch (error) {
  6500. throwError(error, 'Steam.toggleFavoriteWorkshop');
  6501. return false;
  6502. }
  6503. }
  6504. async #getWorkshopAppId(id) {
  6505. try {
  6506. const logStatus = scripts_echoLog({
  6507. type: 'gettingWorkshopAppId',
  6508. text: id
  6509. });
  6510. const appId = this.#cache.workshop[id];
  6511. if (appId) {
  6512. logStatus.success();
  6513. return appId;
  6514. }
  6515. const {
  6516. result,
  6517. statusText,
  6518. status,
  6519. data
  6520. } = await tools_httpRequest({
  6521. url: `https://steamcommunity.com/sharedfiles/filedetails/?id=${id}`,
  6522. method: 'GET'
  6523. });
  6524. if (result === 'Success') {
  6525. if (data?.status === 200) {
  6526. const appId = data.responseText.match(/<input type="hidden" name="appid" value="([\d]+?)" \/>/)?.[1];
  6527. if (appId) {
  6528. this.#setCache('workshop', id, appId);
  6529. logStatus.success();
  6530. return appId;
  6531. }
  6532. logStatus.error('Error: getWorkshopAppId failed');
  6533. return false;
  6534. }
  6535. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6536. return false;
  6537. }
  6538. logStatus.error(`${result}:${statusText}(${status})`);
  6539. return false;
  6540. } catch (error) {
  6541. throwError(error, 'Steam.getWorkshopAppId');
  6542. return false;
  6543. }
  6544. }
  6545. async #voteUpWorkshop(id) {
  6546. try {
  6547. const logStatus = scripts_echoLog({
  6548. type: 'votingUpWorkshop',
  6549. text: id
  6550. });
  6551. const {
  6552. result,
  6553. statusText,
  6554. status,
  6555. data
  6556. } = await tools_httpRequest({
  6557. url: 'https://steamcommunity.com/sharedfiles/voteup',
  6558. method: 'POST',
  6559. responseType: 'json',
  6560. headers: {
  6561. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6562. },
  6563. data: $.param({
  6564. id: id,
  6565. sessionid: this.#auth.communitySessionID
  6566. })
  6567. });
  6568. if (result === 'Success') {
  6569. if (data?.status === 200 && data.response?.success === 1) {
  6570. logStatus.success();
  6571. return true;
  6572. }
  6573. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6574. return true;
  6575. }
  6576. logStatus.error(`${result}:${statusText}(${status})`);
  6577. return true;
  6578. } catch (error) {
  6579. throwError(error, 'Steam.voteupWorkshop');
  6580. return true;
  6581. }
  6582. }
  6583. async #toggleCurator(curatorId, doTask = true) {
  6584. try {
  6585. if (!doTask && this.whiteList.curators.includes(curatorId)) {
  6586. scripts_echoLog({
  6587. type: 'whiteList',
  6588. text: 'Steam.unfollowCurator',
  6589. id: curatorId
  6590. });
  6591. return true;
  6592. }
  6593. if (this.#ASF) {
  6594. return await this.#ASF.toggleCurator(curatorId, doTask);
  6595. }
  6596. const logStatus = scripts_echoLog({
  6597. type: doTask ? 'followingCurator' : 'unfollowingCurator',
  6598. text: curatorId
  6599. });
  6600. const {
  6601. result,
  6602. statusText,
  6603. status,
  6604. data
  6605. } = await tools_httpRequest({
  6606. url: 'https://store.steampowered.com/curators/ajaxfollow',
  6607. method: 'POST',
  6608. headers: {
  6609. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6610. },
  6611. data: $.param({
  6612. clanid: curatorId,
  6613. sessionid: this.#auth.storeSessionID,
  6614. follow: doTask
  6615. }),
  6616. dataType: 'json'
  6617. });
  6618. if (result === 'Success') {
  6619. if (data?.status === 200 && data.response?.success?.success === 1) {
  6620. logStatus.success();
  6621. return true;
  6622. }
  6623. logStatus.error(`Error:${data?.statusText}(${data?.response?.success}` || `${data?.status})`);
  6624. return false;
  6625. }
  6626. logStatus.error(`${result}:${statusText}(${status})`);
  6627. return false;
  6628. } catch (error) {
  6629. throwError(error, 'Steam.toggleCurator');
  6630. return false;
  6631. }
  6632. }
  6633. async getCuratorId(path, name) {
  6634. try {
  6635. const logStatus = scripts_echoLog({
  6636. type: 'gettingCuratorId',
  6637. text: `${path}/${name}`
  6638. });
  6639. const curatorId = this.#cache.curator[`${path}/${name}`];
  6640. if (curatorId) {
  6641. logStatus.success();
  6642. return curatorId;
  6643. }
  6644. const {
  6645. result,
  6646. statusText,
  6647. status,
  6648. data
  6649. } = await tools_httpRequest({
  6650. url: `https://store.steampowered.com/${path}/${name}`,
  6651. method: 'GET',
  6652. headers: {
  6653. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6654. }
  6655. });
  6656. if (result === 'Success') {
  6657. if (data?.status === 200) {
  6658. const curatorId = data.responseText.match(/g_pagingData.*?"clanid":([\d]+)/)?.[1];
  6659. if (curatorId) {
  6660. this.#setCache('curator', `${path}/${name}`, curatorId);
  6661. logStatus.success();
  6662. return curatorId;
  6663. }
  6664. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6665. return false;
  6666. }
  6667. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6668. return false;
  6669. }
  6670. logStatus.error(`${result}:${statusText}(${status})`);
  6671. return false;
  6672. } catch (error) {
  6673. throwError(error, 'Steam.getCuratorID');
  6674. return false;
  6675. }
  6676. }
  6677. async #toggleCuratorLike(link, doTask = true) {
  6678. try {
  6679. const [ path, name ] = link.split('/');
  6680. if (!(path && name)) {
  6681. scripts_echoLog({
  6682. text: i18n('errorLink', link)
  6683. });
  6684. return false;
  6685. }
  6686. const curatorId = await this.getCuratorId(path, name);
  6687. if (curatorId) {
  6688. return await this.#toggleCurator(curatorId, doTask);
  6689. }
  6690. return false;
  6691. } catch (error) {
  6692. throwError(error, 'Steam.toggleCuratorLike');
  6693. return false;
  6694. }
  6695. }
  6696. async #getAnnouncementParams(appId, viewId) {
  6697. try {
  6698. const logStatus = scripts_echoLog({
  6699. type: 'gettingAnnouncementParams',
  6700. text: appId,
  6701. id: viewId
  6702. });
  6703. const {
  6704. result,
  6705. statusText,
  6706. status,
  6707. data
  6708. } = await tools_httpRequest({
  6709. 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`,
  6710. method: 'GET',
  6711. responseType: 'json',
  6712. headers: {
  6713. Host: 'store.steampowered.com',
  6714. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6715. }
  6716. });
  6717. if (result === 'Success') {
  6718. if (data?.status === 200 && data?.response?.success === 1) {
  6719. const {
  6720. clanid,
  6721. gid
  6722. } = data.response.event?.announcement_body || {};
  6723. if (clanid) {
  6724. logStatus.success();
  6725. return {
  6726. clanId: clanid,
  6727. gid: gid
  6728. };
  6729. }
  6730. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6731. return {};
  6732. }
  6733. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6734. return {};
  6735. }
  6736. logStatus.error(`${result}:${statusText}(${status})`);
  6737. return {};
  6738. } catch (error) {
  6739. throwError(error, 'Steam.likeAnnouncement');
  6740. return {};
  6741. }
  6742. }
  6743. async #likeAnnouncement(id) {
  6744. try {
  6745. const [ appId, viewId ] = id.split('/');
  6746. if (!(appId && viewId)) {
  6747. scripts_echoLog({}).error(`${i18n('missParams')}(id)`);
  6748. return false;
  6749. }
  6750. const {
  6751. clanId,
  6752. gid
  6753. } = await this.#getAnnouncementParams(appId, viewId);
  6754. if (!clanId) {
  6755. return false;
  6756. }
  6757. const logStatus = scripts_echoLog({
  6758. type: 'likingAnnouncement',
  6759. text: appId,
  6760. id: viewId
  6761. });
  6762. const {
  6763. result,
  6764. statusText,
  6765. status,
  6766. data
  6767. } = await tools_httpRequest({
  6768. url: `https://store.steampowered.com/updated/ajaxrateupdate/${gid || viewId}`,
  6769. method: 'POST',
  6770. headers: {
  6771. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6772. Host: 'store.steampowered.com',
  6773. Origin: 'https://store.steampowered.com',
  6774. Referer: `https://store.steampowered.com/news/app/${appId}/view/${viewId}`
  6775. },
  6776. data: $.param({
  6777. sessionid: this.#auth.storeSessionID,
  6778. voteup: 1,
  6779. clanid: clanId,
  6780. ajax: 1
  6781. }),
  6782. dataType: 'json'
  6783. });
  6784. if (result === 'Success') {
  6785. if (data?.status === 200 && data.response.success === 1) {
  6786. logStatus.success();
  6787. return true;
  6788. }
  6789. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6790. return false;
  6791. }
  6792. logStatus.error(`${result}:${statusText}(${status})`);
  6793. return false;
  6794. } catch (error) {
  6795. throwError(error, 'Steam.likeAnnouncement');
  6796. return false;
  6797. }
  6798. }
  6799. async #appid2subid(id) {
  6800. try {
  6801. const logStatus = scripts_echoLog({
  6802. type: 'gettingSubid',
  6803. text: id
  6804. });
  6805. const {
  6806. result,
  6807. statusText,
  6808. status,
  6809. data
  6810. } = await tools_httpRequest({
  6811. url: `https://store.steampowered.com/app/${id}`,
  6812. method: 'GET',
  6813. headers: {
  6814. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  6815. }
  6816. });
  6817. if (result === 'Success') {
  6818. if (data?.status === 200) {
  6819. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6820. logStatus.success(i18n('owned'));
  6821. return false;
  6822. }
  6823. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6824. logStatus.warning(i18n('changeAreaNotice'));
  6825. const result = await this.#changeArea();
  6826. if (!result || result === 'CN' || result === 'skip') {
  6827. return false;
  6828. }
  6829. return await this.#appid2subid(id);
  6830. }
  6831. let subid = data.responseText.match(/name="subid" value="([\d]+?)"/)?.[1];
  6832. if (subid) {
  6833. logStatus.success();
  6834. return subid;
  6835. }
  6836. subid = data.responseText.match(/AddFreeLicense\(\s*(\d+)/)?.[1];
  6837. if (subid) {
  6838. logStatus.success();
  6839. return subid;
  6840. }
  6841. logStatus.error(`Error:${i18n('noSubid')}`);
  6842. return false;
  6843. }
  6844. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6845. return false;
  6846. }
  6847. logStatus.error(`${result}:${statusText}(${status})`);
  6848. return false;
  6849. } catch (error) {
  6850. throwError(error, 'Steam.appid2subid');
  6851. return false;
  6852. }
  6853. }
  6854. async #getLicenses() {
  6855. try {
  6856. const logStatus = scripts_echoLog({
  6857. text: i18n('gettingLicenses')
  6858. });
  6859. const {
  6860. result,
  6861. statusText,
  6862. status,
  6863. data
  6864. } = await tools_httpRequest({
  6865. url: `https://store.steampowered.com/dynamicstore/userdata/?t=${new Date().getTime()}`,
  6866. method: 'GET',
  6867. responseType: 'json'
  6868. });
  6869. if (result === 'Success') {
  6870. if (data?.status === 200) {
  6871. logStatus.success();
  6872. return data.response?.rgOwnedPackages;
  6873. }
  6874. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6875. return false;
  6876. }
  6877. logStatus.error(`${result}:${statusText}(${status})`);
  6878. return false;
  6879. } catch (error) {
  6880. throwError(error, 'Steam.getLicenses');
  6881. return false;
  6882. }
  6883. }
  6884. async #addLicense(id) {
  6885. try {
  6886. if (this.#ASF) {
  6887. return await this.#ASF.addLicense(id);
  6888. }
  6889. const [ type, ids ] = id.split('-');
  6890. if (type === 'appid') {
  6891. const subid = await this.#appid2subid(ids);
  6892. if (!subid) {
  6893. return false;
  6894. }
  6895. const logStatus = scripts_echoLog({
  6896. type: 'addingFreeLicense',
  6897. text: ids
  6898. });
  6899. if (!await this.#addFreeLicense(subid, logStatus)) {
  6900. return false;
  6901. }
  6902. const {
  6903. result,
  6904. statusText,
  6905. status,
  6906. data
  6907. } = await tools_httpRequest({
  6908. url: `https://store.steampowered.com/app/${ids}`,
  6909. method: 'GET'
  6910. });
  6911. if (result === 'Success') {
  6912. if (data?.status === 200) {
  6913. if (data.responseText.includes('ds_owned_flag ds_flag') || data.responseText.includes('class="already_in_library"')) {
  6914. logStatus.success();
  6915. return true;
  6916. }
  6917. logStatus.error(`Error:${data.statusText}(${data.status})`);
  6918. return false;
  6919. }
  6920. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  6921. return false;
  6922. }
  6923. logStatus.error(`${result}:${statusText}(${status})`);
  6924. return false;
  6925. } else if (type === 'subid') {
  6926. if (this.#area === 'CN') {
  6927. scripts_echoLog({}).success(i18n('tryChangeAreaNotice'));
  6928. await this.#changeArea();
  6929. }
  6930. const logStatusArr = {};
  6931. const idsArr = ids.split(',');
  6932. for (const subid of idsArr) {
  6933. const logStatus = scripts_echoLog({
  6934. type: 'addingFreeLicenseSubid',
  6935. text: subid
  6936. });
  6937. if (!await this.#addFreeLicense(subid, logStatus)) {
  6938. return false;
  6939. }
  6940. logStatusArr[subid] = logStatus;
  6941. }
  6942. const licenses = await this.#getLicenses();
  6943. if (!licenses) {
  6944. return false;
  6945. }
  6946. for (const subid of idsArr) {
  6947. if (licenses.includes(parseInt(subid, 10))) {
  6948. logStatusArr[subid].success();
  6949. } else {
  6950. logStatusArr[subid].error();
  6951. }
  6952. }
  6953. return true;
  6954. }
  6955. return false;
  6956. } catch (error) {
  6957. throwError(error, 'Steam.addLicense');
  6958. return false;
  6959. }
  6960. }
  6961. async #addFreeLicense(id, logStatusPre) {
  6962. try {
  6963. const logStatus = logStatusPre || scripts_echoLog({
  6964. type: 'addingFreeLicenseSubid',
  6965. text: id
  6966. });
  6967. const {
  6968. result,
  6969. statusText,
  6970. status,
  6971. data
  6972. } = await tools_httpRequest({
  6973. url: `https://store.steampowered.com/freelicense/addfreelicense/${id}`,
  6974. method: 'POST',
  6975. headers: {
  6976. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  6977. Host: 'store.steampowered.com',
  6978. Origin: 'https://store.steampowered.com',
  6979. Referer: 'https://store.steampowered.com/account/licenses/'
  6980. },
  6981. data: $.param({
  6982. ajax: true,
  6983. sessionid: this.#auth.storeSessionID
  6984. }),
  6985. dataType: 'json'
  6986. });
  6987. if (result === 'Success') {
  6988. if (data?.status === 200) {
  6989. if (this.#area === 'CN' && data.responseText.includes('id="error_box"')) {
  6990. logStatus.warning(i18n('changeAreaNotice'));
  6991. const result = await this.#changeArea();
  6992. if (!result || [ 'CN', 'skip' ].includes(result)) {
  6993. return false;
  6994. }
  6995. return await this.#addFreeLicense(id);
  6996. }
  6997. logStatus.success();
  6998. return true;
  6999. }
  7000. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7001. return false;
  7002. }
  7003. logStatus.error(`${result}:${statusText}(${status})`);
  7004. return false;
  7005. } catch (error) {
  7006. throwError(error, 'Steam.addFreeLicense');
  7007. return false;
  7008. }
  7009. }
  7010. async #requestPlayTestAccess(id) {
  7011. try {
  7012. if (this.#ASF) {
  7013. return await this.#ASF.requestPlayTestAccess(id);
  7014. }
  7015. const logStatus = scripts_echoLog({
  7016. type: 'requestingPlayTestAccess',
  7017. text: id
  7018. });
  7019. const {
  7020. result,
  7021. statusText,
  7022. status,
  7023. data
  7024. } = await tools_httpRequest({
  7025. url: `https://store.steampowered.com/ajaxrequestplaytestaccess/${id}`,
  7026. method: 'POST',
  7027. headers: {
  7028. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  7029. Host: 'store.steampowered.com',
  7030. Origin: 'https://store.steampowered.com',
  7031. Referer: `https://store.steampowered.com/app/${id}`
  7032. },
  7033. data: $.param({
  7034. sessionid: this.#auth.storeSessionID
  7035. }),
  7036. dataType: 'json'
  7037. });
  7038. if (result === 'Success') {
  7039. if (data?.status === 200 && data?.response?.success === 1) {
  7040. logStatus.success();
  7041. return true;
  7042. }
  7043. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7044. return false;
  7045. }
  7046. logStatus.error(`${result}:${statusText}(${status})`);
  7047. return false;
  7048. } catch (error) {
  7049. throwError(error, 'Steam.requestPlayTestAccess');
  7050. return false;
  7051. }
  7052. }
  7053. async #playGames(ids, playTime, doTask = true) {
  7054. try {
  7055. if (playTime <= 0) {
  7056. return true;
  7057. }
  7058. if (!this.#ASF) {
  7059. scripts_echoLog({}).warning(i18n('noASFInstance'));
  7060. return false;
  7061. }
  7062. if (!doTask) {
  7063. return await this.#ASF.stopPlayGames();
  7064. }
  7065. const result = await this.#ASF.playGames(ids);
  7066. if (!result) {
  7067. return false;
  7068. }
  7069. const stopPlayTime = Date.now() + (playTime + 10) * 60 * 1e3;
  7070. const stopPlayTimeOld = GM_getValue('stopPlayTime', 0) || 0;
  7071. GM_setValue('stopPlayTime', stopPlayTime > stopPlayTimeOld ? stopPlayTime : stopPlayTimeOld);
  7072. return true;
  7073. } catch (error) {
  7074. throwError(error, 'Steam.playGames');
  7075. return false;
  7076. }
  7077. }
  7078. async toggle({
  7079. doTask = true,
  7080. groupLinks = [],
  7081. officialGroupLinks = [],
  7082. wishlistLinks = [],
  7083. followLinks = [],
  7084. forumLinks = [],
  7085. workshopLinks = [],
  7086. workshopVoteLinks = [],
  7087. curatorLinks = [],
  7088. curatorLikeLinks = [],
  7089. announcementLinks = [],
  7090. licenseLinks = [],
  7091. playtestLinks = [],
  7092. playTimeLinks = []
  7093. }) {
  7094. try {
  7095. if ([ ...groupLinks, ...officialGroupLinks, ...forumLinks, ...workshopLinks, ...workshopVoteLinks ].length > 0 && !this.#communityInitialized) {
  7096. scripts_echoLog({
  7097. text: i18n('needInit')
  7098. });
  7099. return false;
  7100. }
  7101. if ([ ...wishlistLinks, ...followLinks, ...curatorLinks, ...curatorLikeLinks, ...announcementLinks, ...licenseLinks, ...playtestLinks, ...playTimeLinks ].length > 0 && !this.#storeInitialized) {
  7102. scripts_echoLog({
  7103. text: i18n('needInit')
  7104. });
  7105. return false;
  7106. }
  7107. const prom = [];
  7108. if (doTask && !globalOptions.doTask.steam.groups || !doTask && !globalOptions.undoTask.steam.groups) {
  7109. scripts_echoLog({
  7110. type: 'globalOptionsSkip',
  7111. text: 'steam.groups'
  7112. });
  7113. } else {
  7114. const realGroups = this.getRealParams('groups', groupLinks, doTask, link => link.match(/groups\/(.+)\/?/)?.[1]?.split('/')?.[0]);
  7115. if (realGroups.length > 0) {
  7116. for (const group of realGroups) {
  7117. if (doTask) {
  7118. prom.push(this.#joinGroup(group));
  7119. } else {
  7120. prom.push(this.#leaveGroup(group));
  7121. }
  7122. await delay(1e3);
  7123. }
  7124. }
  7125. }
  7126. if (doTask && !globalOptions.doTask.steam.officialGroups || !doTask && !globalOptions.undoTask.steam.officialGroups) {
  7127. scripts_echoLog({
  7128. type: 'globalOptionsSkip',
  7129. text: 'steam.officialGroups'
  7130. });
  7131. } else {
  7132. const realOfficialGroups = this.getRealParams('officialGroups', officialGroupLinks, doTask, link => link.match(/games\/(.+)\/?/)?.[1]);
  7133. if (realOfficialGroups.length > 0) {
  7134. for (const officialGroup of realOfficialGroups) {
  7135. if (doTask) {
  7136. prom.push(this.#joinOfficialGroup(officialGroup));
  7137. } else {
  7138. prom.push(this.#leaveOfficialGroup(officialGroup));
  7139. }
  7140. await delay(1e3);
  7141. }
  7142. }
  7143. }
  7144. if (doTask && !globalOptions.doTask.steam.wishlists || !doTask && !globalOptions.undoTask.steam.wishlists) {
  7145. scripts_echoLog({
  7146. type: 'globalOptionsSkip',
  7147. text: 'steam.wishlists'
  7148. });
  7149. } else {
  7150. const realWishlists = this.getRealParams('wishlists', wishlistLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  7151. if (realWishlists.length > 0) {
  7152. for (const game of realWishlists) {
  7153. if (doTask) {
  7154. prom.push(this.#addToWishlist(game));
  7155. } else {
  7156. prom.push(this.#removeFromWishlist(game));
  7157. }
  7158. await delay(1e3);
  7159. }
  7160. }
  7161. }
  7162. if (doTask && !globalOptions.doTask.steam.follows || !doTask && !globalOptions.undoTask.steam.follows) {
  7163. scripts_echoLog({
  7164. type: 'globalOptionsSkip',
  7165. text: 'steam.follows'
  7166. });
  7167. } else {
  7168. const realFollows = this.getRealParams('follows', followLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  7169. if (realFollows.length > 0) {
  7170. for (const game of realFollows) {
  7171. prom.push(this.#toggleFollowGame(game, doTask));
  7172. await delay(1e3);
  7173. }
  7174. }
  7175. }
  7176. if (doTask && !globalOptions.doTask.steam.playTime || !doTask && !globalOptions.undoTask.steam.playTime) {
  7177. scripts_echoLog({
  7178. type: 'globalOptionsSkip',
  7179. text: 'steam.playTime'
  7180. });
  7181. } else {
  7182. const realGames = this.getRealParams('playTime', playTimeLinks, doTask, link => `${link.split('-')[0]}-${link.match(/app\/([\d]+)/)?.[1] || ''}`);
  7183. if (realGames.length > 0) {
  7184. let maxTime = 0;
  7185. const games = [];
  7186. for (const info of realGames) {
  7187. const [ time, game ] = info.split('-');
  7188. maxTime = Math.max(maxTime, parseInt(time, 10) || 0);
  7189. if ((parseInt(time, 10) || 0) > 0 && game) {
  7190. games.push(game);
  7191. }
  7192. }
  7193. prom.push(this.#playGames(games.join(','), maxTime, doTask));
  7194. await delay(1e3);
  7195. }
  7196. }
  7197. if (doTask && !globalOptions.doTask.steam.forums || !doTask && !globalOptions.undoTask.steam.forums) {
  7198. scripts_echoLog({
  7199. type: 'globalOptionsSkip',
  7200. text: 'steam.forums'
  7201. });
  7202. } else {
  7203. const realForums = this.getRealParams('forums', forumLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  7204. if (realForums.length > 0) {
  7205. for (const forum of realForums) {
  7206. prom.push(this.#toggleForum(forum, doTask));
  7207. await delay(1e3);
  7208. }
  7209. }
  7210. }
  7211. if (doTask && !globalOptions.doTask.steam.workshops || !doTask && !globalOptions.undoTask.steam.workshops) {
  7212. scripts_echoLog({
  7213. type: 'globalOptionsSkip',
  7214. text: 'steam.workshops'
  7215. });
  7216. } else {
  7217. const realWorkshops = this.getRealParams('workshops', workshopLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  7218. if (realWorkshops.length > 0) {
  7219. for (const workshop of realWorkshops) {
  7220. prom.push(this.#toggleFavoriteWorkshop(workshop, doTask));
  7221. await delay(1e3);
  7222. }
  7223. }
  7224. }
  7225. if (doTask && !globalOptions.doTask.steam.workshopVotes) {
  7226. scripts_echoLog({
  7227. type: 'globalOptionsSkip',
  7228. text: 'steam.workshopVotes'
  7229. });
  7230. } else {
  7231. const realworkshopVotes = this.getRealParams('workshopVotes', workshopVoteLinks, doTask, link => link.match(/\?id=([\d]+)/)?.[1]);
  7232. if (doTask && realworkshopVotes.length > 0) {
  7233. for (const workshop of realworkshopVotes) {
  7234. prom.push(this.#voteUpWorkshop(workshop));
  7235. await delay(1e3);
  7236. }
  7237. }
  7238. }
  7239. if (doTask && !globalOptions.doTask.steam.curators || !doTask && !globalOptions.undoTask.steam.curators) {
  7240. scripts_echoLog({
  7241. type: 'globalOptionsSkip',
  7242. text: 'steam.curators'
  7243. });
  7244. } else {
  7245. const realCurators = this.getRealParams('curators', curatorLinks, doTask, link => link.match(/curator\/([\d]+)/)?.[1]);
  7246. const realCuratorLikes = this.getRealParams('curatorLikes', curatorLikeLinks, doTask, link => link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3).join('/'));
  7247. if (realCurators.length > 0) {
  7248. for (const curator of realCurators) {
  7249. prom.push(this.#toggleCurator(curator, doTask));
  7250. await delay(1e3);
  7251. }
  7252. }
  7253. if (realCuratorLikes.length > 0) {
  7254. for (const curatorLike of realCuratorLikes) {
  7255. prom.push(this.#toggleCuratorLike(curatorLike, doTask));
  7256. await delay(1e3);
  7257. }
  7258. }
  7259. }
  7260. if (doTask && !globalOptions.doTask.steam.announcements) {
  7261. scripts_echoLog({
  7262. type: 'globalOptionsSkip',
  7263. text: 'steam.announcements'
  7264. });
  7265. } else {
  7266. const realAnnouncements = this.getRealParams('announcements', announcementLinks, doTask, link => {
  7267. if (link.includes('store.steampowered.com')) {
  7268. return link.match(/store\.steampowered\.com\/news\/app\/([\d]+)\/view\/([\d]+)/)?.slice(1, 3).join('/');
  7269. }
  7270. return link.match(/steamcommunity\.com\/games\/([\d]+)\/announcements\/detail\/([\d]+)/)?.slice(1, 3).join('/');
  7271. });
  7272. if (doTask && realAnnouncements.length > 0) {
  7273. for (const id of realAnnouncements) {
  7274. prom.push(this.#likeAnnouncement(id));
  7275. await delay(1e3);
  7276. }
  7277. }
  7278. }
  7279. if (doTask && !globalOptions.doTask.steam.licenses) {
  7280. scripts_echoLog({
  7281. type: 'globalOptionsSkip',
  7282. text: 'steam.licenses'
  7283. });
  7284. } else if (doTask && globalOptions.doTask.steam.licenses && licenseLinks.length > 0) {
  7285. for (const ids of licenseLinks) {
  7286. const [ type, idsStr ] = ids.split('-');
  7287. const idsArr = idsStr.split(',');
  7288. for (const id of idsArr) {
  7289. prom.push(this.#addLicense(`${type}-${id}`));
  7290. await delay(1e3);
  7291. }
  7292. }
  7293. }
  7294. if (doTask && !globalOptions.doTask.steam.playtests) {
  7295. scripts_echoLog({
  7296. type: 'globalOptionsSkip',
  7297. text: 'steam.playtests'
  7298. });
  7299. } else {
  7300. const realPlaytests = this.getRealParams('playtests', playtestLinks, doTask, link => link.match(/app\/([\d]+)/)?.[1]);
  7301. if (doTask && globalOptions.doTask.steam.playtests && realPlaytests.length > 0) {
  7302. for (const id of realPlaytests) {
  7303. prom.push(this.#requestPlayTestAccess(id));
  7304. await delay(1e3);
  7305. }
  7306. }
  7307. }
  7308. return Promise.all(prom).then(async () => {
  7309. if (this.#oldArea && this.#area !== this.#oldArea) {
  7310. scripts_echoLog({}).warning(i18n('steamFinishNotice') + this.#oldArea);
  7311. await this.#changeArea(this.#oldArea);
  7312. }
  7313. return true;
  7314. });
  7315. } catch (error) {
  7316. throwError(error, 'Steam.toggle');
  7317. return false;
  7318. }
  7319. }
  7320. #setCache(type, name, id) {
  7321. try {
  7322. this.#cache[type][name] = id;
  7323. GM_setValue('steamCache', this.#cache);
  7324. } catch (error) {
  7325. throwError(error, 'Steam.setCache');
  7326. }
  7327. }
  7328. }
  7329. const social_Steam = Steam;
  7330. class Website {
  7331. undoneTasks;
  7332. socialTasks;
  7333. giveawayId;
  7334. socialInitialized = {
  7335. discord: false,
  7336. instagram: false,
  7337. reddit: false,
  7338. twitch: false,
  7339. twitter: false,
  7340. vk: false,
  7341. youtube: false,
  7342. steamStore: false,
  7343. steamCommunity: false
  7344. };
  7345. initialized = false;
  7346. steamTaskType = {
  7347. steamStore: false,
  7348. steamCommunity: false
  7349. };
  7350. social = {};
  7351. async #bind(name, init) {
  7352. try {
  7353. return {
  7354. name: name,
  7355. result: await init
  7356. };
  7357. } catch (error) {
  7358. throwError(error, 'Website.bind');
  7359. return {
  7360. name: name,
  7361. result: false
  7362. };
  7363. }
  7364. }
  7365. async initSocial(action) {
  7366. try {
  7367. const pro = [];
  7368. const tasks = action === 'do' ? this.undoneTasks : this.socialTasks;
  7369. if (tasks.discord) {
  7370. const hasDiscord = Object.values(tasks.discord).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7371. if (hasDiscord && (!this.socialInitialized.discord || !this.social.discord)) {
  7372. this.social.discord = new social_Discord();
  7373. pro.push(this.#bind('discord', this.social.discord.init(action)));
  7374. }
  7375. }
  7376. if (tasks.instagram) {
  7377. const hasInstagram = Object.values(tasks.instagram).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7378. if (hasInstagram && (!this.socialInitialized.instagram || !this.social.instagram)) {
  7379. this.social.instagram = new social_Instagram();
  7380. pro.push(this.#bind('instagram', this.social.instagram.init()));
  7381. }
  7382. }
  7383. if (tasks.reddit) {
  7384. const hasReddit = Object.values(tasks.reddit).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7385. if (hasReddit && (!this.socialInitialized.reddit || !this.social.reddit)) {
  7386. this.social.reddit = new social_Reddit();
  7387. pro.push(this.#bind('reddit', this.social.reddit.init()));
  7388. }
  7389. }
  7390. if (tasks.twitch) {
  7391. const hasTwitch = Object.values(tasks.twitch).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7392. if (hasTwitch && (!this.socialInitialized.twitch || !this.social.twitch)) {
  7393. this.social.twitch = new social_Twitch();
  7394. pro.push(this.#bind('twitch', this.social.twitch.init()));
  7395. }
  7396. }
  7397. if (tasks.twitter) {
  7398. const hasTwitter = Object.values(tasks.twitter).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7399. if (hasTwitter && (!this.socialInitialized.twitter || !this.social.twitter)) {
  7400. this.social.twitter = new social_Twitter();
  7401. pro.push(this.#bind('twitter', this.social.twitter.init()));
  7402. }
  7403. }
  7404. if (tasks.vk) {
  7405. const hasVk = Object.values(tasks.vk).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7406. if (hasVk && (!this.socialInitialized.vk || !this.social.vk)) {
  7407. this.social.vk = new social_Vk();
  7408. pro.push(this.#bind('vk', this.social.vk.init()));
  7409. }
  7410. }
  7411. if (tasks.youtube) {
  7412. const hasYoutube = Object.values(tasks.youtube).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7413. if (hasYoutube && (!this.socialInitialized.youtube || !this.social.youtube)) {
  7414. this.social.youtube = new Youtube();
  7415. pro.push(this.#bind('youtube', this.social.youtube.init()));
  7416. }
  7417. }
  7418. if (tasks.steam) {
  7419. const steamLength = Object.values(tasks.steam).reduce((total, arr) => [ ...total, ...arr ]).length;
  7420. if (steamLength > 0) {
  7421. if (!this.social.steam) {
  7422. this.social.steam = new social_Steam();
  7423. }
  7424. 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);
  7425. if (steamLength - steamCommunityLength > 0) {
  7426. this.steamTaskType.steamStore = true;
  7427. if (!this.socialInitialized.steamStore) {
  7428. pro.push(this.#bind('steamStore', this.social.steam.init('store')));
  7429. }
  7430. }
  7431. if (steamCommunityLength > 0) {
  7432. if (!this.socialInitialized.steamCommunity) {
  7433. this.steamTaskType.steamCommunity = true;
  7434. pro.push(this.#bind('steamCommunity', this.social.steam.init('community')));
  7435. }
  7436. }
  7437. }
  7438. }
  7439. if (tasks.links && tasks.links.length > 0) {
  7440. this.social.visitLink = visitLink;
  7441. }
  7442. return await Promise.all(pro).then(result => {
  7443. let checked = true;
  7444. for (const data of result) {
  7445. if (data.result) {
  7446. this.socialInitialized[data.name] = data.result;
  7447. } else {
  7448. checked = false;
  7449. }
  7450. }
  7451. return checked;
  7452. });
  7453. } catch (error) {
  7454. throwError(error, 'Website.initSocial');
  7455. return false;
  7456. }
  7457. }
  7458. uniqueTasks(allTasks) {
  7459. try {
  7460. const result = {};
  7461. for (const [ social, types ] of Object.entries(allTasks)) {
  7462. result[social] = {};
  7463. for (const [ type, tasks ] of Object.entries(types)) {
  7464. result[social][type] = unique(tasks);
  7465. }
  7466. }
  7467. return result;
  7468. } catch (error) {
  7469. throwError(error, 'Website.uniqueTasks');
  7470. return allTasks;
  7471. }
  7472. }
  7473. async toggleTask(action) {
  7474. try {
  7475. if (!this.initialized && !this.init()) {
  7476. return false;
  7477. }
  7478. if (!await this.classifyTask(action)) {
  7479. return false;
  7480. }
  7481. await this.initSocial(action);
  7482. const pro = [];
  7483. const doTask = action === 'do';
  7484. const tasks = doTask ? this.undoneTasks : this.socialTasks;
  7485. if (this.socialInitialized.discord === true && this.social.discord) {
  7486. pro.push(this.social.discord.toggle({
  7487. doTask: doTask,
  7488. ...tasks.discord
  7489. }));
  7490. }
  7491. if (this.socialInitialized.instagram === true && this.social.instagram) {
  7492. pro.push(this.social.instagram.toggle({
  7493. doTask: doTask,
  7494. ...tasks.instagram
  7495. }));
  7496. }
  7497. if (this.socialInitialized.reddit === true && this.social.reddit) {
  7498. pro.push(this.social.reddit.toggle({
  7499. doTask: doTask,
  7500. ...tasks.reddit
  7501. }));
  7502. }
  7503. if (this.socialInitialized.twitch === true && this.social.twitch) {
  7504. pro.push(this.social.twitch.toggle({
  7505. doTask: doTask,
  7506. ...tasks.twitch
  7507. }));
  7508. }
  7509. if (this.socialInitialized.twitter === true && this.social.twitter) {
  7510. pro.push(this.social.twitter.toggle({
  7511. doTask: doTask,
  7512. ...tasks.twitter
  7513. }));
  7514. }
  7515. if (this.socialInitialized.vk === true && this.social.vk) {
  7516. pro.push(this.social.vk.toggle({
  7517. doTask: doTask,
  7518. ...tasks.vk
  7519. }));
  7520. }
  7521. if (this.socialInitialized.youtube === true && this.social.youtube) {
  7522. pro.push(this.social.youtube.toggle({
  7523. doTask: doTask,
  7524. ...tasks.youtube
  7525. }));
  7526. }
  7527. if ((this.steamTaskType.steamCommunity ? this.socialInitialized.steamCommunity === true : true) && (this.steamTaskType.steamStore ? this.socialInitialized.steamStore === true : true) && this.social.steam) {
  7528. pro.push(this.social.steam.toggle({
  7529. doTask: doTask,
  7530. ...tasks.steam
  7531. }));
  7532. }
  7533. if (this.social.visitLink && tasks.links && doTask) {
  7534. for (const link of tasks.links) {
  7535. pro.push(this.social.visitLink(link));
  7536. }
  7537. }
  7538. if (doTask && tasks.extra && this.extraDoTask) {
  7539. const hasExtra = Object.values(tasks.extra).reduce((total, arr) => [ ...total, ...arr ]).length > 0;
  7540. if (hasExtra) {
  7541. pro.push(this.extraDoTask(tasks.extra));
  7542. }
  7543. }
  7544. await Promise.all(pro);
  7545. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7546. return true;
  7547. } catch (error) {
  7548. throwError(error, 'Website.toggleTask');
  7549. return false;
  7550. }
  7551. }
  7552. async doTask() {
  7553. try {
  7554. return await this.toggleTask('do');
  7555. } catch (error) {
  7556. throwError(error, 'Website.doTask');
  7557. return false;
  7558. }
  7559. }
  7560. async undoTask() {
  7561. try {
  7562. return await this.toggleTask('undo');
  7563. } catch (error) {
  7564. throwError(error, 'Website.undoTask');
  7565. return false;
  7566. }
  7567. }
  7568. }
  7569. const website_Website = Website;
  7570. const defaultTasksTemplate = {
  7571. steam: {
  7572. groupLinks: [],
  7573. wishlistLinks: [],
  7574. curatorLinks: [],
  7575. followLinks: []
  7576. },
  7577. discord: {
  7578. serverLinks: []
  7579. },
  7580. vk: {
  7581. nameLinks: []
  7582. },
  7583. extra: {
  7584. website: []
  7585. }
  7586. };
  7587. const defaultTasks = JSON.stringify(defaultTasksTemplate);
  7588. class FreeAnyWhere extends website_Website {
  7589. name = 'FreeAnyWhere';
  7590. tasks = [];
  7591. socialTasks = JSON.parse(defaultTasks);
  7592. undoneTasks = JSON.parse(defaultTasks);
  7593. buttons = [ 'doTask', 'undoTask', 'verifyTask', 'getKey' ];
  7594. static test() {
  7595. return window.location.host === 'freeanywhere.net';
  7596. }
  7597. async init() {
  7598. try {
  7599. const logStatus = scripts_echoLog({
  7600. text: i18n('initing')
  7601. });
  7602. debug('检测登录按钮');
  7603. if ($('div.header__login a[href*=logout]').length === 0) {
  7604. window.open('https://freeanywhere.net/game.php?steam_login', '_self');
  7605. logStatus.warning(i18n('needLogin'));
  7606. return false;
  7607. }
  7608. debug('检测是否为登录页面');
  7609. if (window.location.href.includes('/login')) {
  7610. logStatus.warning(i18n('needLogin'));
  7611. return false;
  7612. }
  7613. this.initialized = true;
  7614. logStatus.success();
  7615. return true;
  7616. } catch (error) {
  7617. throwError(error, 'Freeanywhere.init');
  7618. return false;
  7619. }
  7620. }
  7621. async classifyTask(action) {
  7622. try {
  7623. const logStatus = scripts_echoLog({
  7624. text: i18n('getTasksInfo')
  7625. });
  7626. if (action === 'undo') {
  7627. this.socialTasks = GM_getValue(`fawTasks-${this.giveawayId}`)?.tasks || JSON.parse(defaultTasks);
  7628. }
  7629. const tasks = $('div.game__content-tasks__task').map((index, element) => ({
  7630. id: $(element).attr('data-id'),
  7631. social: $(element).find('div.task-img img').attr('alt'),
  7632. link: $(element).find('div.task-link a').attr('href'),
  7633. title: $(element).find('div.task-link').text().trim(),
  7634. type: $(element).attr('data-type'),
  7635. isSuccess: $(element).hasClass('done')
  7636. })).toArray();
  7637. if (tasks.length === 0) {
  7638. logStatus.success();
  7639. return false;
  7640. }
  7641. if (action === 'verify') {
  7642. this.tasks = [];
  7643. }
  7644. for (const task of tasks) {
  7645. debug('任务分类', task);
  7646. const {
  7647. id,
  7648. social,
  7649. title,
  7650. type,
  7651. link,
  7652. isSuccess
  7653. } = task;
  7654. const taskInfo = {
  7655. id: id,
  7656. title: title,
  7657. social: social,
  7658. type: type
  7659. };
  7660. if (action === 'verify' && !isSuccess) {
  7661. this.tasks.push(taskInfo);
  7662. continue;
  7663. }
  7664. switch (type) {
  7665. case 'steam_account_verify':
  7666. break;
  7667.  
  7668. case 'steam_game_wishlist':
  7669. if (action === 'undo' && link) {
  7670. this.socialTasks.steam.wishlistLinks.push(link);
  7671. }
  7672. if (action === 'do' && !isSuccess && link) {
  7673. this.undoneTasks.steam.wishlistLinks.push(link);
  7674. }
  7675. break;
  7676.  
  7677. case 'steam_group_sub':
  7678. if (action === 'undo' && link) {
  7679. this.socialTasks.steam.groupLinks.push(link);
  7680. }
  7681. if (action === 'do' && !isSuccess && link) {
  7682. this.undoneTasks.steam.groupLinks.push(link);
  7683. }
  7684. break;
  7685.  
  7686. case 'site_visit':
  7687. if (action === 'do' && !isSuccess) {
  7688. this.undoneTasks.extra.website.push(`id=${id}&type=${type}&task=true`);
  7689. }
  7690. break;
  7691.  
  7692. case 'vk_community_sub':
  7693. if (action === 'undo' && link) {
  7694. this.socialTasks.vk.nameLinks.push(link);
  7695. }
  7696. if (action === 'do' && !isSuccess && link) {
  7697. this.undoneTasks.vk.nameLinks.push(link);
  7698. }
  7699. break;
  7700.  
  7701. case 'vk_post_like':
  7702. if (action === 'undo' && link) {
  7703. this.socialTasks.vk.nameLinks.push(`${link}&action=like`);
  7704. }
  7705. if (action === 'do' && !isSuccess && link) {
  7706. this.undoneTasks.vk.nameLinks.push(`${link}&action=like`);
  7707. }
  7708. break;
  7709.  
  7710. case 'discord_server_sub':
  7711. if (action === 'undo' && link) {
  7712. this.socialTasks.discord.serverLinks.push(link);
  7713. }
  7714. if (action === 'do' && !isSuccess && link) {
  7715. this.undoneTasks.discord.serverLinks.push(link);
  7716. }
  7717. break;
  7718.  
  7719. case 'telegram_channel_sub':
  7720. scripts_echoLog({}).warning(`${i18n('tgTaskNotice')}`);
  7721. break;
  7722.  
  7723. case 'none':
  7724. scripts_echoLog({}).warning(`${i18n('notConnect')}`);
  7725. break;
  7726.  
  7727. default:
  7728. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${type}`);
  7729. break;
  7730. }
  7731. }
  7732. logStatus.success();
  7733. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  7734. this.socialTasks = this.uniqueTasks(this.socialTasks);
  7735. if (window.DEBUG) {
  7736. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  7737. }
  7738. GM_setValue(`fawTasks-${this.giveawayId}`, {
  7739. tasks: this.socialTasks,
  7740. time: new Date().getTime()
  7741. });
  7742. return true;
  7743. } catch (error) {
  7744. throwError(error, 'Freeanywhere.classifyTask');
  7745. return false;
  7746. }
  7747. }
  7748. async verifyTask() {
  7749. try {
  7750. if (!this.initialized && !this.init()) {
  7751. debug('未初始化');
  7752. return false;
  7753. }
  7754. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  7755. debug('任务列表为空', this.tasks);
  7756. return false;
  7757. }
  7758. const pro = [];
  7759. for (const task of this.tasks) {
  7760. pro.push(this.#verify(task));
  7761. await delay(1e3);
  7762. }
  7763. await Promise.all(pro);
  7764. scripts_echoLog({}).success(i18n('allTasksComplete'));
  7765. return !!await this.getKey(true);
  7766. } catch (error) {
  7767. throwError(error, 'Freeanywhere.verifyTask');
  7768. return false;
  7769. }
  7770. }
  7771. async extraDoTask({
  7772. website
  7773. }) {
  7774. try {
  7775. const pro = [];
  7776. for (const link of website) {
  7777. pro.push(this.#doVisitWebsite(link));
  7778. }
  7779. return Promise.all(pro).then(() => true);
  7780. } catch (error) {
  7781. throwError(error, 'FreeAnyWhere.extraDoTask');
  7782. return false;
  7783. }
  7784. }
  7785. async #doVisitWebsite(link) {
  7786. try {
  7787. const logStatus = scripts_echoLog({
  7788. text: i18n('visitingLink')
  7789. });
  7790. const {
  7791. result,
  7792. statusText,
  7793. status
  7794. } = await tools_httpRequest({
  7795. url: 'https://freeanywhere.net/php/task_site_visit_done.php',
  7796. method: 'POST',
  7797. headers: {
  7798. 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  7799. },
  7800. data: link
  7801. });
  7802. if (result === 'Success') {
  7803. logStatus.success();
  7804. return true;
  7805. }
  7806. logStatus.error(`${result}:${statusText}(${status})`);
  7807. return false;
  7808. } catch (error) {
  7809. throwError(error, 'FreeAnyWhere.doVisitWebsite');
  7810. return false;
  7811. }
  7812. }
  7813. async getKey(initialized) {
  7814. try {
  7815. if (!initialized && !this.initialized && !this.init()) {
  7816. debug('未初始化');
  7817. return false;
  7818. }
  7819. const logStatus = scripts_echoLog({
  7820. text: i18n('gettingKey')
  7821. });
  7822. const {
  7823. result,
  7824. statusText,
  7825. status,
  7826. data
  7827. } = await tools_httpRequest({
  7828. url: 'https://freeanywhere.net/php/user_get_key.php',
  7829. method: 'POST'
  7830. });
  7831. if (result === 'Success') {
  7832. if (data?.responseText.indexOf('bad') !== -1 || data?.responseText.length > 50) {
  7833. logStatus.error(data?.responseText);
  7834. return false;
  7835. }
  7836. logStatus.success();
  7837. scripts_echoLog({}).success(data.responseText);
  7838. return data.responseText;
  7839. }
  7840. logStatus.error(`${result}:${statusText}(${status})`);
  7841. return false;
  7842. } catch (error) {
  7843. throwError(error, 'FreeAnyWhere.getGiveawayId');
  7844. return false;
  7845. }
  7846. }
  7847. async #verify(task) {
  7848. try {
  7849. const logStatus = scripts_echoLog({
  7850. html: `<li>${i18n('verifyingTask')}${task.title.trim()}...<font></font></li>`
  7851. });
  7852. const {
  7853. result,
  7854. statusText,
  7855. status,
  7856. data
  7857. } = await tools_httpRequest({
  7858. url: 'https://freeanywhere.net/php/user_task_update.php',
  7859. method: 'POST',
  7860. headers: {
  7861. 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
  7862. },
  7863. data: `id=${task.id}&type=${task.type}`
  7864. });
  7865. if (result === 'Success') {
  7866. if (data?.responseText.trim() === 'good') {
  7867. logStatus.success();
  7868. return true;
  7869. }
  7870. debug('任务验证结果', data?.response);
  7871. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  7872. return false;
  7873. }
  7874. logStatus.error(`${result}:${statusText}(${status})`);
  7875. return false;
  7876. } catch (error) {
  7877. throwError(error, 'Freeanywhere.verify');
  7878. return false;
  7879. }
  7880. }
  7881. }
  7882. const Freeanywhere = FreeAnyWhere;
  7883. const Giveawaysu_defaultTasks = {
  7884. steam: {
  7885. groupLinks: [],
  7886. wishlistLinks: [],
  7887. curatorLinks: [],
  7888. curatorLikeLinks: [],
  7889. followLinks: [],
  7890. forumLinks: [],
  7891. announcementLinks: [],
  7892. workshopVoteLinks: [],
  7893. playtestLinks: [],
  7894. playTimeLinks: []
  7895. },
  7896. discord: {
  7897. serverLinks: []
  7898. },
  7899. instagram: {
  7900. userLinks: []
  7901. },
  7902. vk: {
  7903. nameLinks: []
  7904. },
  7905. twitch: {
  7906. channelLinks: []
  7907. },
  7908. reddit: {
  7909. redditLinks: []
  7910. },
  7911. youtube: {
  7912. channelLinks: [],
  7913. likeLinks: []
  7914. },
  7915. twitter: {
  7916. userLinks: [],
  7917. retweetLinks: []
  7918. }
  7919. };
  7920. class GiveawaySu extends website_Website {
  7921. name = 'GiveawaySu';
  7922. socialTasks = Giveawaysu_defaultTasks;
  7923. undoneTasks = Giveawaysu_defaultTasks;
  7924. buttons = [ 'doTask', 'undoTask' ];
  7925. static test() {
  7926. return /^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(window.location.href);
  7927. }
  7928. async after() {
  7929. try {
  7930. if (!this.#checkLogin()) {
  7931. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  7932. }
  7933. if (!await this.#checkLeftKey()) {
  7934. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  7935. }
  7936. scripts_echoLog({}).warning(i18n('gsNotice'));
  7937. } catch (error) {
  7938. throwError(error, 'Giveawaysu.after');
  7939. }
  7940. }
  7941. init() {
  7942. try {
  7943. const logStatus = scripts_echoLog({
  7944. text: i18n('initing')
  7945. });
  7946. if ($('a.steam-login').length > 0) {
  7947. window.open('/steam/redirect', '_self');
  7948. logStatus.warning(i18n('needLogin'));
  7949. return false;
  7950. }
  7951. if (!this.#getGiveawayId()) {
  7952. return false;
  7953. }
  7954. this.initialized = true;
  7955. logStatus.success();
  7956. return true;
  7957. } catch (error) {
  7958. throwError(error, 'Giveawaysu.init');
  7959. return false;
  7960. }
  7961. }
  7962. async classifyTask(action) {
  7963. try {
  7964. const logStatus = scripts_echoLog({
  7965. text: i18n('getTasksInfo')
  7966. });
  7967. if (action === 'undo') {
  7968. this.socialTasks = GM_getValue(`gasTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  7969. return true;
  7970. }
  7971. const pro = [];
  7972. const tasks = $('#actions tr');
  7973. if ($('div.bind-discord').is(':visible')) {
  7974. $('div.bind-discord a')[0].click();
  7975. }
  7976. if ($('div.bind-twitch').is(':visible')) {
  7977. $('div.bind-twitch a')[0].click();
  7978. }
  7979. for (const task of tasks) {
  7980. pro.push(new Promise(resolve => {
  7981. const td = $(task).find('td:not(".hidden")');
  7982. const colorfulTask = td.eq(1).find('a:not([data-trigger="link"])');
  7983. const colorlessTask = td.eq(2).find('a:not([data-trigger="link"])');
  7984. const taskDes = colorfulTask.length > 0 ? colorfulTask : colorlessTask;
  7985. const taskIcon = td.eq(0).find('i').attr('class') || '';
  7986. const taskName = taskDes.text().trim();
  7987. if (taskIcon.includes('ban') || /disable adblock/gi.test(taskName)) {
  7988. return resolve(true);
  7989. }
  7990. getRedirectLink(taskDes.attr('href')).then(taskLink => {
  7991. if (!taskLink) {
  7992. return resolve(false);
  7993. }
  7994. if (taskIcon.includes('steam') && /join/gi.test(taskName)) {
  7995. this.undoneTasks.steam.groupLinks.push(taskLink);
  7996. } else if (/like.*announcement/gi.test(taskName)) {
  7997. this.undoneTasks.steam.announcementLinks.push(taskLink);
  7998. } else if (/(follow|subscribe).*curator/gim.test(taskName) && /^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  7999. this.undoneTasks.steam.curatorLinks.push(taskLink);
  8000. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  8001. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  8002. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  8003. this.undoneTasks.steam.forumLinks.push(taskLink);
  8004. } else if (taskIcon.includes('thumbs-up') && /^https?:\/\/steamcommunity\.com\/sharedfiles\/filedetails\/\?id=[\d]+/.test(taskLink)) {
  8005. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  8006. } else if (taskIcon.includes('plus') && /request.*playtest/gim.test(taskName)) {
  8007. this.undoneTasks.steam.playtestLinks.push(taskLink);
  8008. } else if (taskIcon.includes('discord') || /join.*discord/gim.test(taskName)) {
  8009. this.undoneTasks.discord.serverLinks.push(taskLink);
  8010. } else if (taskIcon.includes('instagram') || /follow.*instagram/gim.test(taskName)) {
  8011. this.undoneTasks.instagram.userLinks.push(taskLink);
  8012. } else if (taskIcon.includes('twitch') || /follow.*twitch.*channel/gim.test(taskName)) {
  8013. this.undoneTasks.twitch.channelLinks.push(taskLink);
  8014. } else if (taskIcon.includes('reddit') || /subscribe.*subreddit/gim.test(taskName) || /follow.*reddit/gim.test(taskName)) {
  8015. this.undoneTasks.reddit.redditLinks.push(taskLink);
  8016. } else if (/watch.*art/gim.test(taskName)) {
  8017. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  8018. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  8019. this.undoneTasks.youtube.channelLinks.push(taskLink);
  8020. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  8021. this.undoneTasks.youtube.likeLinks.push(taskLink);
  8022. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  8023. this.undoneTasks.vk.nameLinks.push(taskLink);
  8024. } else {
  8025. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  8026. if (/wishlist.*game|add.*wishlist/gim.test(taskName)) {
  8027. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  8028. }
  8029. if (/follow.*button/gim.test(taskName)) {
  8030. this.undoneTasks.steam.followLinks.push(taskLink);
  8031. }
  8032. }
  8033. }
  8034. resolve(true);
  8035. }).catch(error => {
  8036. throwError(error, 'Giveawaysu.classifyTask->getRedirectLink');
  8037. return false;
  8038. });
  8039. }));
  8040. }
  8041. await Promise.all(pro);
  8042. logStatus.success();
  8043. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8044. this.socialTasks = this.undoneTasks;
  8045. if (window.DEBUG) {
  8046. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8047. }
  8048. GM_setValue(`gasTasks-${this.giveawayId}`, {
  8049. tasks: this.socialTasks,
  8050. time: new Date().getTime()
  8051. });
  8052. return true;
  8053. } catch (error) {
  8054. throwError(error, 'Giveawaysu.classifyTask');
  8055. return false;
  8056. }
  8057. }
  8058. #checkLogin() {
  8059. try {
  8060. if (!globalOptions.other.checkLogin) {
  8061. return true;
  8062. }
  8063. if ($('a.steam-login').length > 0) {
  8064. window.open('/steam/redirect', '_self');
  8065. }
  8066. return true;
  8067. } catch (error) {
  8068. throwError(error, 'Giveawaysu.checkLogin');
  8069. return false;
  8070. }
  8071. }
  8072. async #checkLeftKey() {
  8073. try {
  8074. if (!globalOptions.other.checkLeftKey) {
  8075. return true;
  8076. }
  8077. if ($('.giveaway-ended').length > 0 && $('.giveaway-key').length === 0) {
  8078. await external_Swal_default().fire({
  8079. icon: 'warning',
  8080. title: i18n('notice'),
  8081. text: i18n('noKeysLeft'),
  8082. confirmButtonText: i18n('confirm'),
  8083. cancelButtonText: i18n('cancel'),
  8084. showCancelButton: true
  8085. }).then(({
  8086. value
  8087. }) => {
  8088. if (value) {
  8089. window.close();
  8090. }
  8091. });
  8092. }
  8093. return true;
  8094. } catch (error) {
  8095. throwError(error, 'Giveawaysu.checkLeftKey');
  8096. return false;
  8097. }
  8098. }
  8099. #getGiveawayId() {
  8100. try {
  8101. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  8102. if (giveawayId) {
  8103. this.giveawayId = giveawayId;
  8104. return true;
  8105. }
  8106. scripts_echoLog({
  8107. text: i18n('getFailed', 'GiveawayId')
  8108. });
  8109. return false;
  8110. } catch (error) {
  8111. throwError(error, 'Giveawaysu.getGiveawayId');
  8112. return false;
  8113. }
  8114. }
  8115. }
  8116. class Indiedb {
  8117. name = 'Indiedb';
  8118. buttons = [ 'doTask' ];
  8119. static test() {
  8120. return window.location.host === 'www.indiedb.com';
  8121. }
  8122. async after() {
  8123. try {
  8124. if (!this.#checkLogin()) {
  8125. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8126. }
  8127. if (!await this.#checkLeftKey()) {
  8128. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8129. }
  8130. } catch (error) {
  8131. throwError(error, 'Indiedb.after');
  8132. }
  8133. }
  8134. async doTask() {
  8135. try {
  8136. if (!await this.#join()) {
  8137. return false;
  8138. }
  8139. return await this.#do();
  8140. } catch (error) {
  8141. throwError(error, 'Indiedb.doTask');
  8142. return false;
  8143. }
  8144. }
  8145. async #join() {
  8146. try {
  8147. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  8148. scripts_echoLog({}).error(i18n('needLogin'));
  8149. return false;
  8150. }
  8151. const currentoption = $('a.buttonenter.buttongiveaway');
  8152. if (/join giveaway/gim.test(currentoption.text())) {
  8153. const logStatus = scripts_echoLog({
  8154. text: `${i18n('joiningGiveaway')}...`
  8155. });
  8156. const {
  8157. result,
  8158. statusText,
  8159. status,
  8160. data
  8161. } = await tools_httpRequest({
  8162. url: currentoption.attr('href'),
  8163. method: 'POST',
  8164. data: 'ajax=t',
  8165. dataType: 'json',
  8166. headers: {
  8167. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  8168. Accept: 'application/json, text/javascript, */*; q=0.01',
  8169. Origin: window.location.origin,
  8170. referer: window.location.href
  8171. }
  8172. });
  8173. if (result === 'Success') {
  8174. if (data?.status === 200) {
  8175. if (data.response?.success) {
  8176. currentoption.addClass('buttonentered').text('Success - Giveaway joined');
  8177. $('#giveawaysjoined').slideDown();
  8178. $('#giveawaysrecommend').slideDown();
  8179. logStatus.success(`Success${data.response?.text ? `:${data.response?.text}` : ''}`);
  8180. return true;
  8181. }
  8182. logStatus.error(`Error${data.response?.text ? `:${data.response?.text}` : ''}`);
  8183. return false;
  8184. }
  8185. if (await this.#join2()) {
  8186. logStatus.success('Success');
  8187. return true;
  8188. }
  8189. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  8190. return false;
  8191. }
  8192. logStatus.error(`${result}:${statusText}(${status})`);
  8193. return false;
  8194. } else if (/success/gim.test($('a.buttonenter.buttongiveaway').text())) {
  8195. return true;
  8196. }
  8197. scripts_echoLog({}).warning(i18n('needJoinGiveaway'));
  8198. return false;
  8199. } catch (error) {
  8200. throwError(error, 'Indiedb.join');
  8201. return false;
  8202. }
  8203. }
  8204. async #join2() {
  8205. try {
  8206. return await new Promise(resolve => {
  8207. const targetNode = document.getElementById('giveawaysjoined');
  8208. const config = {
  8209. attributes: true
  8210. };
  8211. const observer = new MutationObserver(() => {
  8212. if ($('#giveawaysjoined').is(':visible')) {
  8213. resolve(true);
  8214. observer.disconnect();
  8215. }
  8216. });
  8217. observer.observe(targetNode, config);
  8218. $('a.buttonenter.buttongiveaway')[0]?.click();
  8219. setTimeout(() => {
  8220. resolve(false);
  8221. observer.disconnect();
  8222. }, 3e4);
  8223. });
  8224. } catch (error) {
  8225. throwError(error, 'Indiedb.join2');
  8226. return false;
  8227. }
  8228. }
  8229. async #do() {
  8230. try {
  8231. const id = $('script').map((index, script) => {
  8232. if (/\$\(document\)/gim.test(script.innerHTML)) {
  8233. return [ script.innerHTML.match(/"\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0], script.innerHTML.match(/"\/newsletter\/ajax\/subscribeprofile\/optin\/[\d]+"/gim)?.[0]?.match(/[\d]+/)?.[0] ];
  8234. }
  8235. return null;
  8236. });
  8237. if (id.length === 2) {
  8238. const pro = [];
  8239. const tasks = $('#giveawaysjoined a[class*=promo]');
  8240. for (const task of tasks) {
  8241. const promo = $(task);
  8242. if (!promo.hasClass('buttonentered')) {
  8243. const status = scripts_echoLog({
  8244. text: `${i18n('doing')}:${promo.parents('p').text()}...`
  8245. });
  8246. if (/facebookpromo|twitterpromo|visitpromo/gim.test(task.className)) {
  8247. let text = '';
  8248. if (promo.hasClass('facebookpromo')) {
  8249. text = 'facebookpromo';
  8250. } else if (promo.hasClass('twitterpromo')) {
  8251. text = 'twitterpromo';
  8252. } else {
  8253. text = 'visitpromo';
  8254. }
  8255. pro.push(new Promise(resolve => {
  8256. $.ajax({
  8257. type: 'POST',
  8258. url: urlPath(`/giveaways/ajax/${text}/${id[0]}`),
  8259. timeout: 6e4,
  8260. dataType: 'json',
  8261. data: {
  8262. ajax: 't'
  8263. },
  8264. error(response, error, exception) {
  8265. if (window.DEBUG) {
  8266. console.log('%cAuto-Task[Debug]:', 'color:red', {
  8267. response: response,
  8268. error: error,
  8269. exception: exception
  8270. });
  8271. }
  8272. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  8273. resolve(true);
  8274. },
  8275. success(response) {
  8276. if (response.success) {
  8277. status.success(`Success:${response.text}`);
  8278. promo.addClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  8279. resolve(true);
  8280. } else {
  8281. status.error(`Error:${response.text}`);
  8282. resolve(true);
  8283. }
  8284. }
  8285. });
  8286. }));
  8287. } else if (promo.hasClass('emailoptinpromo')) {
  8288. pro.push(new Promise(resolve => {
  8289. $.ajax({
  8290. type: 'POST',
  8291. url: urlPath(`/newsletter/ajax/subscribeprofile/optin/${id[1]}`),
  8292. timeout: 6e4,
  8293. dataType: 'json',
  8294. data: {
  8295. ajax: 't',
  8296. emailsystoggle: 4
  8297. },
  8298. error(response, error, exception) {
  8299. if (window.DEBUG) {
  8300. console.log('%cAuto-Task[Debug]:', 'color:red', {
  8301. response: response,
  8302. error: error,
  8303. exception: exception
  8304. });
  8305. }
  8306. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  8307. resolve(true);
  8308. },
  8309. success(response) {
  8310. if (response.success) {
  8311. status.success(`Success:${response.text}`);
  8312. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  8313. resolve(true);
  8314. } else {
  8315. status.error(`Error:${response.text}`);
  8316. resolve(true);
  8317. }
  8318. }
  8319. });
  8320. }));
  8321. } else if (promo.hasClass('watchingpromo')) {
  8322. pro.push(new Promise(resolve => {
  8323. const data = getUrlQuery(promo.attr('href'));
  8324. data.ajax = 't';
  8325. $.ajax({
  8326. type: 'POST',
  8327. url: urlPath(promo.attr('href')?.split(/[?#]/)[0]),
  8328. timeout: 6e4,
  8329. dataType: 'json',
  8330. data: data,
  8331. error(response, error, exception) {
  8332. if (window.DEBUG) {
  8333. console.log('%cAuto-Task[Debug]:', 'color:red', {
  8334. response: response,
  8335. error: error,
  8336. exception: exception
  8337. });
  8338. }
  8339. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  8340. resolve(true);
  8341. },
  8342. success(response) {
  8343. if (response.success) {
  8344. status.success(`Success:${response.text}`);
  8345. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  8346. resolve(true);
  8347. } else {
  8348. status.error(`Error:${response.text}`);
  8349. resolve(true);
  8350. }
  8351. }
  8352. });
  8353. }));
  8354. } else if (!/the-challenge-of-adblock/gim.test(promo.attr('href'))) {
  8355. pro.push(new Promise(resolve => {
  8356. $.ajax({
  8357. type: 'POST',
  8358. url: urlPath(promo.attr('href')),
  8359. timeout: 6e4,
  8360. dataType: 'json',
  8361. data: {
  8362. ajax: 't'
  8363. },
  8364. error(response, error, exception) {
  8365. if (window.DEBUG) {
  8366. console.log('%cAuto-Task[Debug]:', 'color:red', {
  8367. response: response,
  8368. error: error,
  8369. exception: exception
  8370. });
  8371. }
  8372. status.error('Error:An error has occurred performing the action requested. Please try again shortly.');
  8373. resolve(true);
  8374. },
  8375. success(response) {
  8376. if (response.success) {
  8377. status.success(`Success:${response.text}`);
  8378. promo.toggleClass('buttonentered').closest('p').html(promo.closest('p').find('span').html());
  8379. resolve(true);
  8380. } else {
  8381. status.error(`Error:${response.text}`);
  8382. resolve(true);
  8383. }
  8384. }
  8385. });
  8386. }));
  8387. } else {
  8388. status.error(`Error:${i18n('unKnownTaskType')}`);
  8389. }
  8390. }
  8391. }
  8392. await Promise.all(pro);
  8393. scripts_echoLog({}).success(i18n('allTasksComplete'));
  8394. return true;
  8395. }
  8396. scripts_echoLog({}).error(i18n('getFailed', 'TaskId'));
  8397. return false;
  8398. } catch (error) {
  8399. throwError(error, 'Indiedb.classifyTask');
  8400. return false;
  8401. }
  8402. }
  8403. #checkLogin() {
  8404. try {
  8405. if (!globalOptions.other.checkLogin) {
  8406. return true;
  8407. }
  8408. if ($('a.buttonenter:contains(Register to join)').length > 0) {
  8409. window.open('/members/login', '_self');
  8410. }
  8411. return true;
  8412. } catch (error) {
  8413. throwError(error, 'Indiedb.checkLogin');
  8414. return false;
  8415. }
  8416. }
  8417. async #checkLeftKey() {
  8418. try {
  8419. if (!globalOptions.other.checkLeftKey) {
  8420. return true;
  8421. }
  8422. if ($('a.buttonenter:contains("next time"), a.buttonenter:contains("Giveaway is closed")').length > 0) {
  8423. await external_Swal_default().fire({
  8424. icon: 'warning',
  8425. title: i18n('notice'),
  8426. text: i18n('giveawayEnded'),
  8427. confirmButtonText: i18n('confirm'),
  8428. cancelButtonText: i18n('cancel'),
  8429. showCancelButton: true
  8430. }).then(({
  8431. value
  8432. }) => {
  8433. if (value) {
  8434. window.close();
  8435. }
  8436. });
  8437. }
  8438. return true;
  8439. } catch (error) {
  8440. throwError(error, 'Indiedb.checkLeftKey');
  8441. return false;
  8442. }
  8443. }
  8444. }
  8445. const website_Indiedb = Indiedb;
  8446. const Keyhub_defaultTasksTemplate = {
  8447. steam: {
  8448. groupLinks: [],
  8449. officialGroupLinks: [],
  8450. wishlistLinks: [],
  8451. curatorLinks: []
  8452. },
  8453. discord: {
  8454. serverLinks: []
  8455. },
  8456. extra: {
  8457. videoTasks: []
  8458. },
  8459. links: []
  8460. };
  8461. const Keyhub_defaultTasks = JSON.stringify(Keyhub_defaultTasksTemplate);
  8462. class Keyhub extends website_Website {
  8463. name = 'Keyhub';
  8464. socialTasks = JSON.parse(Keyhub_defaultTasks);
  8465. undoneTasks = JSON.parse(Keyhub_defaultTasks);
  8466. buttons = [ 'doTask', 'undoTask' ];
  8467. static test() {
  8468. return window.location.host === 'key-hub.eu';
  8469. }
  8470. async after() {
  8471. try {
  8472. if (!this.#checkLogin()) {
  8473. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8474. }
  8475. if (!await this.#checkLeftKey()) {
  8476. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8477. }
  8478. $('.NSFW').hide();
  8479. } catch (error) {
  8480. throwError(error, 'Keyhub.after');
  8481. }
  8482. }
  8483. init() {
  8484. try {
  8485. const logStatus = scripts_echoLog({
  8486. text: i18n('initing')
  8487. });
  8488. if ($('a[href*="/connect/steam"]').length > 0) {
  8489. window.open('/connect/steam', '_self');
  8490. logStatus.warning(i18n('needLogin'));
  8491. return false;
  8492. }
  8493. if (!this.#getGiveawayId()) {
  8494. return false;
  8495. }
  8496. $('#VPNoverlay').hide();
  8497. $('#mainArticleSection').show();
  8498. this.initialized = true;
  8499. logStatus.success();
  8500. return true;
  8501. } catch (error) {
  8502. throwError(error, 'Keyhub.init');
  8503. return false;
  8504. }
  8505. }
  8506. async classifyTask(action) {
  8507. try {
  8508. const logStatus = scripts_echoLog({
  8509. text: i18n('getTasksInfo')
  8510. });
  8511. if (action === 'undo') {
  8512. this.socialTasks = GM_getValue(`khTasks-${this.giveawayId}`)?.tasks || JSON.parse(Keyhub_defaultTasks);
  8513. }
  8514. const tasks = $('.task:not(".googleads")').filter((index, element) => action === 'do' ? $(element).find('i.fa-check-circle:visible').length === 0 : true).find('a');
  8515. for (const task of tasks) {
  8516. let link = $(task).attr('href');
  8517. const taskDes = $(task).text().trim();
  8518. if (!link) {
  8519. continue;
  8520. }
  8521. if (/\/away\?data=/.test(link) || /steamcommunity\.com\/gid\//.test(link)) {
  8522. link = await getRedirectLink(link) || link;
  8523. }
  8524. if (/https?:\/\/key-hub\.eu\/connect\/discord/.test(link)) {
  8525. GM_openInTab(link, {
  8526. active: true
  8527. });
  8528. } else if (/steamcommunity\.com\/groups\//.test(link)) {
  8529. if (action === 'undo') {
  8530. this.socialTasks.steam.groupLinks.push(link);
  8531. }
  8532. if (action === 'do') {
  8533. this.undoneTasks.steam.groupLinks.push(link);
  8534. }
  8535. } else if (/steamcommunity\.com\/games\/[\d]+/.test(link)) {
  8536. if (action === 'undo') {
  8537. this.socialTasks.steam.officialGroupLinks.push(link);
  8538. }
  8539. if (action === 'do') {
  8540. this.undoneTasks.steam.officialGroupLinks.push(link);
  8541. }
  8542. } else if (/store\.steampowered\.com\/app\//.test(link) && /wishlist/gim.test(taskDes)) {
  8543. if (action === 'undo') {
  8544. this.socialTasks.steam.wishlistLinks.push(link);
  8545. }
  8546. if (action === 'do') {
  8547. this.undoneTasks.steam.wishlistLinks.push(link);
  8548. }
  8549. } else if (/store\.steampowered\.com\/curator\//.test(link)) {
  8550. if (action === 'undo') {
  8551. this.socialTasks.steam.curatorLinks.push(link);
  8552. }
  8553. if (action === 'do') {
  8554. this.undoneTasks.steam.curatorLinks.push(link);
  8555. }
  8556. } else if (/^https?:\/\/discord\.com\/invite\//.test(link)) {
  8557. if (action === 'undo') {
  8558. this.socialTasks.discord.serverLinks.push(link);
  8559. }
  8560. if (action === 'do') {
  8561. this.undoneTasks.discord.serverLinks.push(link);
  8562. }
  8563. } else if (/^javascript:videoTask.+/.test(link)) {
  8564. if (action === 'do') {
  8565. const taskData = link.match(/javascript:videoTask\('.+?','(.+?)'/)?.[1];
  8566. if (taskData) {
  8567. this.undoneTasks.extra.videoTasks.push(taskData);
  8568. }
  8569. }
  8570. } 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 {
  8571. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  8572. }
  8573. }
  8574. logStatus.success();
  8575. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8576. this.socialTasks = this.uniqueTasks(this.socialTasks);
  8577. if (window.DEBUG) {
  8578. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8579. }
  8580. GM_setValue(`khTasks-${this.giveawayId}`, {
  8581. tasks: this.socialTasks,
  8582. time: new Date().getTime()
  8583. });
  8584. return true;
  8585. } catch (error) {
  8586. throwError(error, 'Keyhub.classifyTask');
  8587. return false;
  8588. }
  8589. }
  8590. async #doScriptTask(data) {
  8591. try {
  8592. const logStatus = scripts_echoLog({
  8593. text: i18n('doingKeyhubTask')
  8594. });
  8595. const {
  8596. result,
  8597. statusText,
  8598. status,
  8599. data: response
  8600. } = await tools_httpRequest({
  8601. url: `/away?data=${data}`,
  8602. method: 'GET',
  8603. headers: {
  8604. origin: 'https://key-hub.eu',
  8605. referer: 'https://key-hub.eu/'
  8606. }
  8607. });
  8608. if (result === 'Success') {
  8609. if (response?.status === 200) {
  8610. logStatus.success();
  8611. return true;
  8612. }
  8613. logStatus.error(`Error:${response?.statusText}(${response?.status})`);
  8614. return false;
  8615. }
  8616. logStatus.error(`${result}:${statusText}(${status})`);
  8617. return false;
  8618. } catch (error) {
  8619. throwError(error, 'Keyhub.doScriptTask');
  8620. return false;
  8621. }
  8622. }
  8623. async extraDoTask({
  8624. videoTasks
  8625. }) {
  8626. try {
  8627. const pro = [];
  8628. for (const data of videoTasks) {
  8629. pro.push(this.#doScriptTask(data));
  8630. }
  8631. return Promise.all(pro).then(() => true);
  8632. } catch (error) {
  8633. throwError(error, 'Keyhub.extraDoTask');
  8634. return false;
  8635. }
  8636. }
  8637. #getGiveawayId() {
  8638. try {
  8639. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  8640. if (giveawayId) {
  8641. this.giveawayId = giveawayId;
  8642. return true;
  8643. }
  8644. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  8645. return false;
  8646. } catch (error) {
  8647. throwError(error, 'Keyhub.getGiveawayId');
  8648. return false;
  8649. }
  8650. }
  8651. async #checkLeftKey() {
  8652. try {
  8653. if (!globalOptions.other.checkLeftKey) {
  8654. return true;
  8655. }
  8656. const leftKey = $('#keysleft').text().trim();
  8657. if (leftKey === '0') {
  8658. await external_Swal_default().fire({
  8659. icon: 'warning',
  8660. title: i18n('notice'),
  8661. text: i18n('noKeysLeft'),
  8662. confirmButtonText: i18n('confirm'),
  8663. cancelButtonText: i18n('cancel'),
  8664. showCancelButton: true
  8665. }).then(({
  8666. value
  8667. }) => {
  8668. if (value) {
  8669. window.close();
  8670. }
  8671. });
  8672. }
  8673. return true;
  8674. } catch (error) {
  8675. throwError(error, 'Keyhub.checkLeftKey');
  8676. return false;
  8677. }
  8678. }
  8679. #checkLogin() {
  8680. try {
  8681. if (!globalOptions.other.checkLogin) {
  8682. return true;
  8683. }
  8684. if ($('a[href*="/connect/steam"]').length > 0) {
  8685. window.open('/connect/steam', '_self');
  8686. }
  8687. return true;
  8688. } catch (error) {
  8689. throwError(error, 'Keyhub.checkLogin');
  8690. return false;
  8691. }
  8692. }
  8693. }
  8694. const website_Keyhub = Keyhub;
  8695. const Givekey_defaultTasksTemplate = {
  8696. steam: {
  8697. groupLinks: [],
  8698. wishlistLinks: [],
  8699. curatorLinks: [],
  8700. curatorLikeLinks: []
  8701. },
  8702. twitter: {
  8703. userLinks: []
  8704. },
  8705. vk: {
  8706. nameLinks: []
  8707. },
  8708. discord: {
  8709. serverLinks: []
  8710. }
  8711. };
  8712. const Givekey_defaultTasks = JSON.stringify(Givekey_defaultTasksTemplate);
  8713. class Givekey extends website_Website {
  8714. name = 'Givekey';
  8715. tasks = [];
  8716. socialTasks = JSON.parse(Givekey_defaultTasks);
  8717. undoneTasks = JSON.parse(Givekey_defaultTasks);
  8718. userId;
  8719. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8720. static test() {
  8721. return window.location.host === 'givekey.ru';
  8722. }
  8723. async after() {
  8724. try {
  8725. await new Promise(resolve => {
  8726. const checker = setInterval(() => {
  8727. if ($('#navbarDropdown').length > 0) {
  8728. clearInterval(checker);
  8729. resolve(true);
  8730. }
  8731. }, 500);
  8732. });
  8733. if (!await this.#checkLeftKey()) {
  8734. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8735. }
  8736. } catch (error) {
  8737. throwError(error, 'Givekey.after');
  8738. }
  8739. }
  8740. init() {
  8741. try {
  8742. const logStatus = scripts_echoLog({
  8743. text: i18n('initing')
  8744. });
  8745. if ($('a[href*="/auth/steam"]').length > 0) {
  8746. window.open('/auth/steam', '_self');
  8747. logStatus.warning(i18n('needLogin'));
  8748. return false;
  8749. }
  8750. if (!this.#getGiveawayId()) {
  8751. return false;
  8752. }
  8753. const userId = $('meta[name="user-id"]').attr('content');
  8754. if (!userId) {
  8755. logStatus.error(i18n('getFailed', i18n('userId')));
  8756. return false;
  8757. }
  8758. this.userId = userId;
  8759. this.initialized = true;
  8760. logStatus.success();
  8761. return true;
  8762. } catch (error) {
  8763. throwError(error, 'Givekey.init');
  8764. return false;
  8765. }
  8766. }
  8767. async classifyTask(action) {
  8768. try {
  8769. const logStatus = scripts_echoLog({
  8770. text: i18n('getTasksInfo')
  8771. });
  8772. if (action === 'undo') {
  8773. this.socialTasks = GM_getValue(`gkTasks-${this.giveawayId}`)?.tasks || JSON.parse(Givekey_defaultTasks);
  8774. }
  8775. const tasks = $('.card-body:has("button") .row');
  8776. for (const task of tasks) {
  8777. const taskEle = $(task);
  8778. const isSuccess = /Complete/i.test(taskEle.find('button').text().trim());
  8779. if (isSuccess && action !== 'undo') {
  8780. continue;
  8781. }
  8782. const checkButton = taskEle.find('#task_check');
  8783. const taskId = checkButton.attr('data-id');
  8784. if (taskId) {
  8785. this.tasks.push(taskId);
  8786. }
  8787. if (action === 'verify') {
  8788. continue;
  8789. }
  8790. let href = taskEle.find('a').attr('href') || null;
  8791. const text = taskEle.find('a').text().trim();
  8792. const icon = taskEle.find('i');
  8793. if (!href || !text) {
  8794. continue;
  8795. }
  8796. if (/^https?:\/\/givekey\.ru\/giveaway\/[\d]+\/execution_task/.test(href)) {
  8797. href = await getRedirectLink(href);
  8798. }
  8799. if (!href) {
  8800. continue;
  8801. }
  8802. if (/^https?:\/\/vk\.com\//.test(href)) {
  8803. this.socialTasks.vk.nameLinks.push(href);
  8804. if (action === 'do' && !isSuccess) {
  8805. this.undoneTasks.vk.nameLinks.push(href);
  8806. }
  8807. } else if (/^https?:\/\/steamcommunity\.com\/groups/.test(href)) {
  8808. this.socialTasks.steam.groupLinks.push(href);
  8809. if (action === 'do' && !isSuccess) {
  8810. this.undoneTasks.steam.groupLinks.push(href);
  8811. }
  8812. } else if (/^https?:\/\/store\.steampowered\.com\/app\//.test(href)) {
  8813. this.socialTasks.steam.wishlistLinks.push(href);
  8814. if (action === 'do' && !isSuccess) {
  8815. this.undoneTasks.steam.wishlistLinks.push(href);
  8816. }
  8817. } else if (/Subscribe/gi.test(text) && icon.hasClass('fa-steam-square')) {
  8818. if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(href)) {
  8819. this.socialTasks.steam.curatorLinks.push(href);
  8820. if (action === 'do' && !isSuccess) {
  8821. this.undoneTasks.steam.curatorLinks.push(href);
  8822. }
  8823. } else {
  8824. this.socialTasks.steam.curatorLikeLinks.push(href);
  8825. if (action === 'do' && !isSuccess) {
  8826. this.undoneTasks.steam.curatorLikeLinks.push(href);
  8827. }
  8828. }
  8829. } else if (/^https?:\/\/twitter\.com\//.test(href) && /Subscribe/gi.test(text)) {
  8830. this.socialTasks.twitter.userLinks.push(href);
  8831. if (action === 'do' && !isSuccess) {
  8832. this.undoneTasks.twitter.userLinks.push(href);
  8833. }
  8834. } else if (icon.hasClass('fa-discord') || /^https?:\/\/discord\.com\/invite\//.test(href)) {
  8835. this.socialTasks.discord.serverLinks.push(href);
  8836. if (action === 'do' && !isSuccess) {
  8837. this.undoneTasks.discord.serverLinks.push(href);
  8838. }
  8839. } else {
  8840. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${text}(${href})`);
  8841. }
  8842. }
  8843. logStatus.success();
  8844. this.tasks = unique(this.tasks);
  8845. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  8846. this.socialTasks = this.uniqueTasks(this.socialTasks);
  8847. if (window.DEBUG) {
  8848. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  8849. }
  8850. GM_setValue(`gkTasks-${this.giveawayId}`, {
  8851. tasks: this.socialTasks,
  8852. time: new Date().getTime()
  8853. });
  8854. return true;
  8855. } catch (error) {
  8856. throwError(error, 'Givekey.classifyTask');
  8857. return false;
  8858. }
  8859. }
  8860. async verifyTask() {
  8861. try {
  8862. if (!this.initialized && !this.init()) {
  8863. return false;
  8864. }
  8865. if (this.tasks.length === 0 && !await this.classifyTask('verify')) {
  8866. return false;
  8867. }
  8868. scripts_echoLog({}).warning(i18n('giveKeyNoticeBefore'));
  8869. const taskLength = this.tasks.length;
  8870. for (let i = 0; i < taskLength; i++) {
  8871. await this.#verify(this.tasks[i]);
  8872. if (i < taskLength - 1) {
  8873. await delay(15e3);
  8874. }
  8875. }
  8876. scripts_echoLog({}).success(i18n('allTasksComplete'));
  8877. scripts_echoLog({
  8878. html: `<li><font class="warning">${i18n('giveKeyNoticeAfter')}</font></li>`
  8879. });
  8880. return true;
  8881. } catch (error) {
  8882. throwError(error, 'Givekey.verifyTask');
  8883. return false;
  8884. }
  8885. }
  8886. async #verify(task) {
  8887. try {
  8888. const logStatus = scripts_echoLog({
  8889. html: `<li>${i18n('verifyingTask')}${task}...<font></font></li>`
  8890. });
  8891. return await new Promise(resolve => {
  8892. $.ajax({
  8893. url: 'https://givekey.ru/giveaway/task',
  8894. method: 'POST',
  8895. data: `id=${task}&user_id=${this.userId}`,
  8896. dataType: 'json',
  8897. headers: {
  8898. 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  8899. },
  8900. success: data => {
  8901. if (data.btn) {
  8902. $(`button[data-id=${this.userId}]`).html(data.btn);
  8903. }
  8904. if (data.status === 'ok') {
  8905. $(`.task_check_${data.id}`).html(`<button class="btn btn-success mb-2 btn-block" disabled>${data.btn}</button>`);
  8906. logStatus.success();
  8907. resolve(true);
  8908. } else if (data.status === 'end') {
  8909. logStatus.success();
  8910. scripts_echoLog({}).success(data.key);
  8911. resolve(true);
  8912. } else {
  8913. logStatus.error(`Error:${data.msg}`);
  8914. resolve(false);
  8915. }
  8916. },
  8917. error: xhr => {
  8918. logStatus.error(`Error:${xhr.statusText}(${xhr.status})`);
  8919. resolve(false);
  8920. }
  8921. });
  8922. });
  8923. } catch (error) {
  8924. throwError(error, 'Givekey.verify');
  8925. return false;
  8926. }
  8927. }
  8928. #getGiveawayId() {
  8929. try {
  8930. const giveawayId = window.location.href.match(/giveaway\/([\d]+)/)?.[1];
  8931. if (giveawayId) {
  8932. this.giveawayId = giveawayId;
  8933. return true;
  8934. }
  8935. scripts_echoLog({
  8936. text: i18n('getFailed', 'GiveawayId')
  8937. });
  8938. return false;
  8939. } catch (error) {
  8940. throwError(error, 'Givekey.getGiveawayId');
  8941. return false;
  8942. }
  8943. }
  8944. async #checkLeftKey() {
  8945. try {
  8946. if (!globalOptions.other.checkLeftKey) {
  8947. return true;
  8948. }
  8949. if (!$('#keys_count').text()) {
  8950. await external_Swal_default().fire({
  8951. icon: 'warning',
  8952. title: i18n('notice'),
  8953. text: i18n('noKeysLeft'),
  8954. confirmButtonText: i18n('confirm'),
  8955. cancelButtonText: i18n('cancel'),
  8956. showCancelButton: true
  8957. }).then(({
  8958. value
  8959. }) => {
  8960. if (value) {
  8961. window.close();
  8962. }
  8963. });
  8964. }
  8965. return true;
  8966. } catch (error) {
  8967. throwError(error, 'Givekey.checkLeftKey');
  8968. return false;
  8969. }
  8970. }
  8971. }
  8972. const website_Givekey = Givekey;
  8973. class GiveeClub extends GiveawaySu {
  8974. name = 'GiveeClub';
  8975. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  8976. static test() {
  8977. return /^https?:\/\/givee\.club\/.*?\/event\/[\d]+/.test(window.location.href);
  8978. }
  8979. async after() {
  8980. try {
  8981. if (!this.#checkLogin()) {
  8982. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  8983. }
  8984. if (!await this.#checkLeftKey()) {
  8985. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  8986. }
  8987. } catch (error) {
  8988. throwError(error, 'GiveeClub.after');
  8989. }
  8990. }
  8991. init() {
  8992. try {
  8993. const logStatus = scripts_echoLog({
  8994. text: i18n('initing')
  8995. });
  8996. if (!this.#checkLogin()) {
  8997. logStatus.warning(i18n('needLogin'));
  8998. return false;
  8999. }
  9000. if (!this.#getGiveawayId()) {
  9001. return false;
  9002. }
  9003. this.initialized = true;
  9004. logStatus.success();
  9005. return true;
  9006. } catch (error) {
  9007. throwError(error, 'GiveeClub.init');
  9008. return false;
  9009. }
  9010. }
  9011. async classifyTask(action) {
  9012. try {
  9013. const logStatus = scripts_echoLog({
  9014. text: i18n('getTasksInfo')
  9015. });
  9016. if (action === 'undo') {
  9017. this.socialTasks = GM_getValue(`gcTasks-${this.giveawayId}`)?.tasks || Giveawaysu_defaultTasks;
  9018. return true;
  9019. }
  9020. this.undoneTasks = Giveawaysu_defaultTasks;
  9021. const pro = [];
  9022. const tasks = $('.event-actions tr');
  9023. for (const task of tasks) {
  9024. pro.push(new Promise(resolve => {
  9025. const taskDes = $(task).find('.event-action-label a');
  9026. const taskIcon = $(task).find('.event-action-icon i').attr('class') || '';
  9027. const taskName = taskDes.text().trim();
  9028. const taskType = $(task).find('button[data-type]')?.attr('data-type');
  9029. const taskFinished = $(task).find('.event-action-buttons .btn-success')?.length;
  9030. if (taskIcon.includes('ban') || /AdBlock/i.test(taskName) || taskIcon.includes('envelope') || taskFinished) {
  9031. return resolve(true);
  9032. }
  9033. getRedirectLink(taskDes.attr('href'), true).then(taskLink => {
  9034. if (!taskLink) {
  9035. return resolve(false);
  9036. }
  9037. if (taskType === 'steam.group.join' && /^https?:\/\/steamcommunity\.com\/groups/.test(taskLink)) {
  9038. this.undoneTasks.steam.groupLinks.push(taskLink);
  9039. } else if (/like.*announcement/gi.test(taskName)) {
  9040. this.undoneTasks.steam.announcementLinks.push(taskLink);
  9041. } else if (taskType === 'steam.game.wishlist' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  9042. this.undoneTasks.steam.wishlistLinks.push(taskLink);
  9043. } else if (taskType === 'steam.game.wishlist' && taskDes.attr('data-steam-wishlist-appid')) {
  9044. this.undoneTasks.steam.wishlistLinks.push(`https://store.steampowered.com/app/${taskDes.attr('data-steam-wishlist-appid')}`);
  9045. } else if (taskType === 'steam.game.follow' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  9046. this.undoneTasks.steam.followLinks.push(taskLink);
  9047. } else if (/^https?:\/\/store\.steampowered\.com\/curator\//.test(taskLink)) {
  9048. this.undoneTasks.steam.curatorLinks.push(taskLink);
  9049. } else if (taskIcon.includes('steam') && /follow|subscribe/gim.test(taskName)) {
  9050. this.undoneTasks.steam.curatorLikeLinks.push(taskLink);
  9051. } else if (/subscribe.*steam.*forum/gim.test(taskName)) {
  9052. this.undoneTasks.steam.forumLinks.push(taskLink);
  9053. } else if (taskType === 'steam.game.playtime' && /^https?:\/\/store\.steampowered\.com\/app\//.test(taskLink)) {
  9054. const time = taskDes.text().match(/(\d+)(?:\.\d+)?/gim)?.[0] || '0';
  9055. this.undoneTasks.steam.playTimeLinks.push(`${time}-${taskLink}`);
  9056. } else if (taskIcon.includes('discord')) {
  9057. this.undoneTasks.discord.serverLinks.push(taskLink);
  9058. } else if (taskIcon.includes('instagram')) {
  9059. this.undoneTasks.instagram.userLinks.push(taskLink);
  9060. } else if (taskIcon.includes('twitch')) {
  9061. this.undoneTasks.twitch.channelLinks.push(taskLink);
  9062. } else if (taskIcon.includes('reddit')) {
  9063. this.undoneTasks.reddit.redditLinks.push(taskLink);
  9064. } else if (/watch.*art/gim.test(taskName)) {
  9065. this.undoneTasks.steam.workshopVoteLinks.push(taskLink);
  9066. } else if (/subscribe.*youtube.*channel/gim.test(taskName)) {
  9067. this.undoneTasks.youtube.channelLinks.push(taskLink);
  9068. } else if (/(watch|like).*youtube.*video/gim.test(taskName) || (taskIcon.includes('youtube') || taskIcon.includes('thumbs-up')) && /(watch|like).*video/gim.test(taskName)) {
  9069. this.undoneTasks.youtube.likeLinks.push(taskLink);
  9070. } else if (taskIcon.includes('vk') || /join.*vk.*group/gim.test(taskName)) {
  9071. this.undoneTasks.vk.nameLinks.push(taskLink);
  9072. } else if (taskIcon.includes('twitter')) {
  9073. if (/https?:\/\/(twitter|x)\.com\/[^/]+\/?$/gim.test(taskLink)) {
  9074. this.undoneTasks.twitter.userLinks.push(taskLink);
  9075. } else if (/https?:\/\/(twitter|x)\.com\/[^/]+?\/status\/[\d]+/gim.test(taskLink)) {
  9076. this.undoneTasks.twitter.retweetLinks.push(taskLink);
  9077. }
  9078. } else {
  9079. if (/(on twitter)|(Follow.*on.*Facebook)/gim.test(taskName)) {} else {
  9080. if (/follow.*button/gim.test(taskName)) {
  9081. this.undoneTasks.steam.followLinks.push(taskLink);
  9082. }
  9083. }
  9084. }
  9085. resolve(true);
  9086. }).catch(error => {
  9087. throwError(error, 'GiveeClub.classifyTask->getRedirectLink');
  9088. return false;
  9089. });
  9090. }));
  9091. }
  9092. await Promise.all(pro);
  9093. logStatus.success();
  9094. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9095. this.socialTasks = this.undoneTasks;
  9096. if (window.DEBUG) {
  9097. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9098. }
  9099. GM_setValue(`gcTasks-${this.giveawayId}`, {
  9100. tasks: this.socialTasks,
  9101. time: new Date().getTime()
  9102. });
  9103. return true;
  9104. } catch (error) {
  9105. throwError(error, 'GiveeClub.classifyTask');
  9106. return false;
  9107. }
  9108. }
  9109. async verifyTask() {
  9110. try {
  9111. const logStatus = scripts_echoLog({
  9112. text: i18n('giveeClubVerifyNotice')
  9113. });
  9114. const taskButtons = $('.event-actions tr button').has('i.glyphicon-refresh').not('[data-type="user.adblock"]');
  9115. for (const button of taskButtons) {
  9116. button.click();
  9117. if ($(button).attr('data-type') !== 'steam.game.wishlist') {
  9118. await delay(1e3);
  9119. }
  9120. }
  9121. logStatus.warning(i18n('giveeClubVerifyFinished'));
  9122. return true;
  9123. } catch (error) {
  9124. throwError(error, 'Givekey.verifyTask');
  9125. return false;
  9126. }
  9127. }
  9128. #checkLogin() {
  9129. try {
  9130. if (!globalOptions.other.checkLogin) {
  9131. return true;
  9132. }
  9133. if ($('a[href*="/account/auth"]').length > 0) {
  9134. window.open($('a[href*="/account/auth"]').attr('href'), '_self');
  9135. }
  9136. return true;
  9137. } catch (error) {
  9138. throwError(error, 'GiveeClub.checkLogin');
  9139. return false;
  9140. }
  9141. }
  9142. #getGiveawayId() {
  9143. const giveawayId = window.location.href.match(/\/event\/([\d]+)/)?.[1];
  9144. if (giveawayId) {
  9145. this.giveawayId = giveawayId;
  9146. return true;
  9147. }
  9148. scripts_echoLog({
  9149. text: i18n('getFailed', 'GiveawayId')
  9150. });
  9151. return false;
  9152. }
  9153. async #checkLeftKey() {
  9154. try {
  9155. if (!globalOptions.other.checkLeftKey) {
  9156. return true;
  9157. }
  9158. if ($('.event-ended').length > 0 && $('.event-winner').length === 0) {
  9159. await external_Swal_default().fire({
  9160. icon: 'warning',
  9161. title: i18n('notice'),
  9162. text: i18n('giveawayEnded'),
  9163. confirmButtonText: i18n('confirm'),
  9164. cancelButtonText: i18n('cancel'),
  9165. showCancelButton: true
  9166. }).then(({
  9167. value
  9168. }) => {
  9169. if (value) {
  9170. window.close();
  9171. }
  9172. });
  9173. }
  9174. return true;
  9175. } catch (error) {
  9176. throwError(error, 'Giveawaysu.checkLeftKey');
  9177. return false;
  9178. }
  9179. }
  9180. }
  9181. const website_GiveeClub = GiveeClub;
  9182. const defaultOptions = {
  9183. maxPoint: '99999999'
  9184. };
  9185. class OpiumPulses {
  9186. name = 'OpiumPulses';
  9187. options = {
  9188. ...defaultOptions,
  9189. ...GM_getValue('OpiumPulsesOptions')
  9190. };
  9191. maxPoints = 99999999;
  9192. myPoints = 0;
  9193. buttons = [ 'doFreeTask', 'doPointTask' ];
  9194. static test() {
  9195. return window.location.host === 'www.opiumpulses.com';
  9196. }
  9197. async after() {
  9198. try {
  9199. if (!this.#checkLogin()) {
  9200. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9201. }
  9202. this.maxPoints = parseInt(this.options.maxPoint, 10);
  9203. } catch (error) {
  9204. throwError(error, 'OpiumPulses.after');
  9205. }
  9206. }
  9207. async doFreeTask() {
  9208. try {
  9209. this.#toggleTask('FREE');
  9210. } catch (error) {
  9211. throwError(error, 'OpiumPulses.doFreeTask');
  9212. }
  9213. }
  9214. async doPointTask() {
  9215. try {
  9216. this.myPoints = parseInt($('.page-header__nav-func-user-nav-items.points-items').text().match(/[\d]+/gim)?.[0] || '0', 10);
  9217. this.#toggleTask('points');
  9218. } catch (error) {
  9219. throwError(error, 'OpiumPulses.doPointTask');
  9220. }
  9221. }
  9222. async #toggleTask(type) {
  9223. try {
  9224. const items = $(`.giveaways-page-item:contains('${type}'):not(:contains('ENTERED'))`);
  9225. for (const item of items) {
  9226. const needPoints = parseInt($(item).find('.giveaways-page-item-header-points').text().match(/[\d]+/gim)?.[0] || '999999', 10);
  9227. const name = $(item).find('.giveaways-page-item-footer-name').text().trim();
  9228. if (type === 'points' && needPoints > this.myPoints) {
  9229. scripts_echoLog({}).warning(`${i18n('noPoints')}: ${name}`);
  9230. } else if (type === 'points' && !needPoints) {
  9231. scripts_echoLog({}).warning(`${i18n('getNeedPointsFailed')}: ${name}`);
  9232. } else if (!(type === 'points' && needPoints > this.maxPoints)) {
  9233. const logStatus = scripts_echoLog({
  9234. text: `${i18n('joiningLottery')}<a href="${$(item).find('a.giveaways-page-item-img-btn-more').attr('href')}" target="_blank">${name}</a>...`
  9235. });
  9236. const aElement = $(item).find('a.giveaways-page-item-img-btn-enter:contains(\'enter\')');
  9237. if (aElement?.attr('onclick')?.includes('checkUser')) {
  9238. const giveawayId = aElement.attr('onclick')?.match(/[\d]+/)?.[0];
  9239. if (giveawayId) {
  9240. checkUser(giveawayId);
  9241. }
  9242. }
  9243. if (!aElement.attr('href')) {
  9244. logStatus.error('Error: No "href".');
  9245. continue;
  9246. }
  9247. const {
  9248. result,
  9249. statusText,
  9250. status,
  9251. data
  9252. } = await tools_httpRequest({
  9253. url: aElement.attr('href'),
  9254. method: 'GET'
  9255. });
  9256. if (result === 'Success') {
  9257. const {
  9258. result: result0,
  9259. statusText: statusText0,
  9260. status: status0,
  9261. data: data0
  9262. } = await tools_httpRequest({
  9263. url: data?.finalUrl,
  9264. method: 'GET'
  9265. });
  9266. if (data0?.responseText && /You've entered this giveaway/gim.test(data0.responseText)) {
  9267. logStatus.success();
  9268. const points = data0.responseText.match(/Points:[\s]*?([\d]+)/)?.[1];
  9269. if (type === 'points' && points) {
  9270. this.myPoints = parseInt(points, 10);
  9271. }
  9272. } else if (data0?.responseText && /You're not eligible to enter/gim.test(data0.responseText)) {
  9273. logStatus.error('You\'re not eligible to enter');
  9274. } else {
  9275. logStatus.error(`${result0}:${statusText0}(${status0})`);
  9276. }
  9277. } else {
  9278. logStatus.error(`${result}:${statusText}(${status})`);
  9279. }
  9280. }
  9281. }
  9282. scripts_echoLog({
  9283. text: '-----END-----'
  9284. });
  9285. } catch (error) {
  9286. throwError(error, 'OpiumPulses.toggleTask');
  9287. }
  9288. }
  9289. init() {
  9290. return true;
  9291. }
  9292. classifyTask() {
  9293. return true;
  9294. }
  9295. #checkLogin() {
  9296. try {
  9297. if (!globalOptions.other.checkLogin) {
  9298. return true;
  9299. }
  9300. if ($('a[href*="/site/login"]').length > 1) {
  9301. window.open('/site/login', '_self');
  9302. }
  9303. return true;
  9304. } catch (error) {
  9305. throwError(error, 'OpiumPulses.checkLogin');
  9306. return false;
  9307. }
  9308. }
  9309. }
  9310. const website_OpiumPulses = OpiumPulses;
  9311. const external_dayjs_namespaceObject = dayjs;
  9312. var external_dayjs_default = __webpack_require__.n(external_dayjs_namespaceObject);
  9313. const leftKeyChecker = {
  9314. async classify(link) {
  9315. try {
  9316. if (/^https?:\/\/giveaway\.su\/giveaway\/view\/[\d]+/.test(link)) {
  9317. return await this.giveawaySu(link);
  9318. }
  9319. if (/^https?:\/\/givee\.club\/[\w]+?\/event\/[\d]+/.test(link)) {
  9320. return await this.giveeClub(link);
  9321. }
  9322. if (/^https?:\/\/gleam\.io\/.+?\/.+/.test(link)) {
  9323. return await this.gleam(link);
  9324. }
  9325. if (/^https?:\/\/www\.indiedb\.com\/giveaways\/.+/.test(link)) {
  9326. return await this.indieDb(link);
  9327. }
  9328. if (/^https?:\/\/key-hub\.eu\/giveaway\/[\d]+/.test(link)) {
  9329. return await this.keyhub(link);
  9330. }
  9331. if (/^https?:\/\/opquests\.com\/quests\/[\d]+/.test(link)) {
  9332. return await this.opquests(link);
  9333. }
  9334. if (/^https?:\/\/itch\.io\/s\/[\d]+?\/.*/.test(link)) {
  9335. return await this.itch(link);
  9336. }
  9337. return false;
  9338. } catch (error) {
  9339. throwError(error, 'leftKeyChecker.classify');
  9340. return false;
  9341. }
  9342. },
  9343. async giveawaySu(link) {
  9344. try {
  9345. const {
  9346. result,
  9347. data
  9348. } = await tools_httpRequest({
  9349. url: link,
  9350. method: 'GET'
  9351. });
  9352. if (result === 'Success' && data?.status === 200) {
  9353. if (data.responseText.includes('class="steam-login"')) {
  9354. return false;
  9355. }
  9356. if (data.responseText.includes('class="giveaway-ended"')) {
  9357. return 'Ended';
  9358. }
  9359. return 'Active';
  9360. }
  9361. return false;
  9362. } catch (error) {
  9363. throwError(error, 'leftKeyChecker.giveawaySu');
  9364. return false;
  9365. }
  9366. },
  9367. async giveeClub(link) {
  9368. try {
  9369. const {
  9370. result,
  9371. data
  9372. } = await tools_httpRequest({
  9373. url: link,
  9374. method: 'GET'
  9375. });
  9376. if (result === 'Success' && data?.status === 200) {
  9377. if (data.responseText.includes('class="event-winner"')) {
  9378. return 'Won';
  9379. }
  9380. if (data.responseText.includes('class="event-ended"')) {
  9381. return 'Ended';
  9382. }
  9383. return 'Active';
  9384. }
  9385. return false;
  9386. } catch (error) {
  9387. throwError(error, 'leftKeyChecker.giveeClub');
  9388. return false;
  9389. }
  9390. },
  9391. async gleam(link) {
  9392. try {
  9393. const {
  9394. result,
  9395. data
  9396. } = await tools_httpRequest({
  9397. url: link,
  9398. method: 'GET'
  9399. });
  9400. if (result === 'Success' && data?.status === 200) {
  9401. if (/incentives&quot;:{&quot;[\d]+?&quot;:\[&quot;.+?&quot;\]/.test(data.responseText)) {
  9402. return 'Won';
  9403. }
  9404. const campaignDiv = data.responseText.match(/<div class='popup-blocks-container'[\w\W]+?'>/)?.[0];
  9405. if (!campaignDiv) {
  9406. return false;
  9407. }
  9408. const campaignString = $(campaignDiv).attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  9409. if (!campaignString) {
  9410. return false;
  9411. }
  9412. const {
  9413. campaign
  9414. } = JSON.parse(campaignString);
  9415. if (campaign.banned) {
  9416. return 'Banned';
  9417. }
  9418. if (campaign.finished) {
  9419. return 'Ended';
  9420. }
  9421. if (campaign.paused) {
  9422. return 'Paused';
  9423. }
  9424. if (new Date().getTime() < campaign.starts_at * 1e3) {
  9425. return 'NotStart';
  9426. }
  9427. return 'Active';
  9428. }
  9429. return false;
  9430. } catch (error) {
  9431. throwError(error, 'leftKeyChecker.gleam');
  9432. return false;
  9433. }
  9434. },
  9435. async indieDb(link) {
  9436. try {
  9437. const {
  9438. result,
  9439. data
  9440. } = await tools_httpRequest({
  9441. url: link,
  9442. method: 'GET'
  9443. });
  9444. if (result === 'Success' && data?.status === 200) {
  9445. if (data.responseText.includes('Congrats you WON')) {
  9446. return 'Won';
  9447. }
  9448. if (data.responseText.includes('Giveaway is closed') || data.responseText.includes('next time')) {
  9449. return 'Ended';
  9450. }
  9451. return 'Active';
  9452. }
  9453. return false;
  9454. } catch (error) {
  9455. throwError(error, 'leftKeyChecker.indieDb');
  9456. return false;
  9457. }
  9458. },
  9459. async keyhub(link) {
  9460. try {
  9461. const {
  9462. result,
  9463. data
  9464. } = await tools_httpRequest({
  9465. url: link,
  9466. method: 'GET'
  9467. });
  9468. if (result === 'Success' && data?.status === 200) {
  9469. const keysleft = data.responseText.match(/<span id="keysleft">([\d]+?)<\/span>/)?.[1];
  9470. if (!keysleft) {
  9471. return false;
  9472. }
  9473. if (keysleft === '0') {
  9474. return 'Ended';
  9475. }
  9476. return `Active(${keysleft})`;
  9477. }
  9478. return false;
  9479. } catch (error) {
  9480. throwError(error, 'leftKeyChecker.keyhub');
  9481. return false;
  9482. }
  9483. },
  9484. async opquests(link) {
  9485. try {
  9486. const {
  9487. result,
  9488. data
  9489. } = await tools_httpRequest({
  9490. url: link,
  9491. method: 'GET'
  9492. });
  9493. if (result === 'Success' && data?.status === 200) {
  9494. const keysleft = data.responseText.match(/<div class="">[\s]*?([\d]+?)[\s]*?of/)?.[1];
  9495. if (!keysleft) {
  9496. return false;
  9497. }
  9498. if (keysleft === '0') {
  9499. return 'Ended';
  9500. }
  9501. return `Active(${keysleft})`;
  9502. } else if (data?.status === 404) {
  9503. return 'Ended';
  9504. }
  9505. return false;
  9506. } catch (error) {
  9507. throwError(error, 'leftKeyChecker.opquests');
  9508. return false;
  9509. }
  9510. },
  9511. async itch(link) {
  9512. try {
  9513. const {
  9514. result,
  9515. data
  9516. } = await tools_httpRequest({
  9517. url: link,
  9518. method: 'GET'
  9519. });
  9520. if (result === 'Success' && data?.status === 200) {
  9521. const endDate = data.responseText.match(/{"start_date":"[0-9A-Z-:]+?".*?"end_date":"([0-9A-Z-:]+?)".*?}/)?.[1];
  9522. if (!endDate) {
  9523. return false;
  9524. }
  9525. if (new Date().getTime() > new Date(endDate).getTime()) {
  9526. return 'Ended';
  9527. }
  9528. return `Active(${external_dayjs_default()(endDate).format('YYYY-MM-DD HH:mm:ss')})`;
  9529. }
  9530. return false;
  9531. } catch (error) {
  9532. throwError(error, 'leftKeyChecker.itch');
  9533. return false;
  9534. }
  9535. }
  9536. };
  9537. const website_leftKeyChecker = leftKeyChecker;
  9538. const Keylol_defaultTasksTemplate = {
  9539. steam: {
  9540. groupLinks: [],
  9541. wishlistLinks: [],
  9542. curatorLinks: [],
  9543. curatorLikeLinks: [],
  9544. followLinks: [],
  9545. forumLinks: [],
  9546. announcementLinks: [],
  9547. workshopVoteLinks: [],
  9548. licenseLinks: []
  9549. },
  9550. discord: {
  9551. serverLinks: []
  9552. },
  9553. instagram: {
  9554. userLinks: []
  9555. },
  9556. vk: {
  9557. nameLinks: []
  9558. },
  9559. twitch: {
  9560. channelLinks: []
  9561. },
  9562. reddit: {
  9563. redditLinks: []
  9564. },
  9565. twitter: {
  9566. userLinks: [],
  9567. retweetLinks: []
  9568. },
  9569. youtube: {
  9570. channelLinks: [],
  9571. likeLinks: []
  9572. }
  9573. };
  9574. const Keylol_defaultTasks = JSON.stringify(Keylol_defaultTasksTemplate);
  9575. class Keylol extends website_Website {
  9576. name = 'Keylol';
  9577. socialTasks = JSON.parse(Keylol_defaultTasks);
  9578. undoneTasks = JSON.parse(Keylol_defaultTasks);
  9579. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect' ];
  9580. static test() {
  9581. 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'));
  9582. }
  9583. init() {
  9584. return true;
  9585. }
  9586. after() {
  9587. try {
  9588. const selector = this.name === 'Keylol' ? '#postlist>div[id^="post_"]:first' : 'div.container';
  9589. const mainPost = $(selector);
  9590. const discordLinks = mainPost.find('a[href*="discord.com"]:visible');
  9591. const redditLinks = mainPost.find('a[href*="reddit.com"]:visible');
  9592. const insLinks = mainPost.find('a[href*="instagram.com"]:visible');
  9593. const twitterLinks = mainPost.find('a[href*="twitter.com"]:visible,a[href*="x.com"]:visible');
  9594. const twitchLinks = mainPost.find('a[href*="twitch.tv"]:visible');
  9595. const vkLinks = mainPost.find('a[href*="vk.com"]:visible');
  9596. const steamStoreLinks = mainPost.find('a[href*="store.steampowered.com"]:visible');
  9597. const steamCommunityLinks = mainPost.find('a[href*="steamcommunity.com"]:visible');
  9598. const ytbLinks = mainPost.find('a[href*="youtube.com"]:visible');
  9599. if (discordLinks.length > 0) {
  9600. for (const discordLink of discordLinks) {
  9601. const link = $(discordLink).attr('href');
  9602. if (!(link && /^https?:\/\/discord\.com\/invite\/.+/.test(link))) {
  9603. continue;
  9604. }
  9605. this.#addBtn(discordLink, 'discord', 'serverLinks', link);
  9606. }
  9607. }
  9608. if (redditLinks.length > 0) {
  9609. for (const redditLink of redditLinks) {
  9610. const link = $(redditLink).attr('href');
  9611. if (!(link && /^https?:\/\/www\.reddit\.com\/(r|user)\/.+/.test(link))) {
  9612. continue;
  9613. }
  9614. this.#addBtn(redditLink, 'reddit', 'redditLinks', link);
  9615. }
  9616. }
  9617. if (insLinks.length > 0) {
  9618. for (const insLink of insLinks) {
  9619. const link = $(insLink).attr('href');
  9620. if (!(link && /^https:\/\/www\.instagram\.com\/.+/.test(link))) {
  9621. continue;
  9622. }
  9623. this.#addBtn(insLink, 'instagram', 'userLinks', link);
  9624. }
  9625. }
  9626. if (twitterLinks.length > 0) {
  9627. for (const twitterLink of twitterLinks) {
  9628. const link = $(twitterLink).attr('href');
  9629. if (!(link && /^https:\/\/twitter\.com\/.+/.test(link))) {
  9630. continue;
  9631. }
  9632. if (/https:\/\/twitter\.com\/.*?\/status\/[\d]+/.test(link)) {
  9633. this.#addBtn(twitterLink, 'twitter', 'retweetLinks', link);
  9634. } else {
  9635. this.#addBtn(twitterLink, 'twitter', 'userLinks', link);
  9636. }
  9637. }
  9638. }
  9639. if (twitchLinks.length > 0) {
  9640. for (const twitchLink of twitchLinks) {
  9641. const link = $(twitchLink).attr('href');
  9642. if (!(link && /^https:\/\/(www\.)?twitch\.tv\/.+/.test(link))) {
  9643. continue;
  9644. }
  9645. this.#addBtn(twitchLink, 'twitch', 'channelLinks', link);
  9646. }
  9647. }
  9648. if (vkLinks.length > 0) {
  9649. for (const vkLink of vkLinks) {
  9650. const link = $(vkLink).attr('href');
  9651. if (!(link && /^https:\/\/vk\.com\/.+/.test(link))) {
  9652. continue;
  9653. }
  9654. this.#addBtn(vkLink, 'vk', 'nameLinks', link);
  9655. }
  9656. }
  9657. if (steamStoreLinks.length > 0) {
  9658. for (const steamStoreLink of steamStoreLinks) {
  9659. const link = $(steamStoreLink).attr('href');
  9660. if (!link) {
  9661. continue;
  9662. }
  9663. if (/curator\/[\d]+/.test(link)) {
  9664. this.#addBtn(steamStoreLink, 'steam', 'curatorLinks', link);
  9665. } else if (/(publisher|developer|franchise)\/.+/.test(link)) {
  9666. this.#addBtn(steamStoreLink, 'steam', 'curatorLikeLinks', link);
  9667. } else if (/news(hub)?\/app\/[\d]+\/view\/[\d]+/.test(link)) {
  9668. this.#addBtn(steamStoreLink, 'steam', 'announcementLinks', link);
  9669. } else if (/app\/[\d]+/.test(link)) {
  9670. this.#addBtn(steamStoreLink, 'steam', 'followLinks', link);
  9671. this.#addBtn(steamStoreLink, 'steam', 'wishlistLinks', link);
  9672. }
  9673. }
  9674. }
  9675. if (steamCommunityLinks.length > 0) {
  9676. for (const steamCommunityLink of steamCommunityLinks) {
  9677. const link = $(steamCommunityLink).attr('href');
  9678. if (!link) {
  9679. continue;
  9680. }
  9681. if (/groups\/.+/.test(link)) {
  9682. this.#addBtn(steamCommunityLink, 'steam', 'groupLinks', link);
  9683. } else if (/announcements\/detail\/[\d]+/.test(link)) {
  9684. this.#addBtn(steamCommunityLink, 'steam', 'announcementLinks', link);
  9685. }
  9686. }
  9687. }
  9688. if (ytbLinks.length > 0) {
  9689. for (const ytbLink of ytbLinks) {
  9690. const link = $(ytbLink).attr('href');
  9691. if (!link) {
  9692. continue;
  9693. }
  9694. this.#addBtn(ytbLink, 'youtube', 'channelLinks', link);
  9695. this.#addBtn(ytbLink, 'youtube', 'likeLinks', link);
  9696. }
  9697. }
  9698. 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');
  9699. if (giveawayLinks.length > 0) {
  9700. for (const giveawayLink of giveawayLinks) {
  9701. const link = $(giveawayLink).attr('href');
  9702. if (!link) {
  9703. continue;
  9704. }
  9705. website_leftKeyChecker.classify(link).then(status => {
  9706. if (!status) {
  9707. return;
  9708. }
  9709. if (/^Active/.test(status)) {
  9710. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status active" title="${i18n('Active')}">${status}</font>`);
  9711. return;
  9712. }
  9713. $(`a[href="${link}"]`).after(`<font class="auto-task-giveaway-status not-active" title="${i18n(status)}">${status}</font>`);
  9714. }).catch(error => {
  9715. throwError(error, 'keylol.after -> leftKeyChecker');
  9716. });
  9717. }
  9718. }
  9719. if (this.name === 'Keylol') {
  9720. const asfLinks = mainPost.find('a[href^="#asf"]:visible');
  9721. if (asfLinks.length > 0) {
  9722. for (const asfLink of asfLinks) {
  9723. const link = $(asfLink).attr('href');
  9724. if (!link) {
  9725. continue;
  9726. }
  9727. this.#addBtn($(`a[href="${link}"]`).after('<span style="color: #ccc; margin: 0 -5px 0 5px"> | </span>').next()[0], 'steam', 'licenseLinks', `appid-${link.replace('#asf', '')}`);
  9728. }
  9729. }
  9730. const subLinks = mainPost.find('a[href*="steamdb.info/sub/"]:visible');
  9731. if (subLinks.length > 0) {
  9732. for (const subLink of subLinks) {
  9733. const link = $(subLink).attr('href');
  9734. if (!link) {
  9735. continue;
  9736. }
  9737. const subid = link.match(/^https:\/\/steamdb\.info\/sub\/([\d]+)/)?.[1];
  9738. if (!subid) {
  9739. continue;
  9740. }
  9741. this.#addBtn(subLink, 'steam', 'licenseLinks', `subid-${subid}`);
  9742. }
  9743. }
  9744. const asfLinks2 = mainPost.find('.blockcode:contains("addlicense"):visible');
  9745. if (asfLinks2.length > 0) {
  9746. for (const asfLink of asfLinks2) {
  9747. const appid = [ ...asfLink.innerText.matchAll(/a(pp)?\/([\d]+)/g) ].map(matched => matched?.[2]).filter(id => id) || [];
  9748. if (appid.length > 0) {
  9749. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `appid-${appid.join(',')}`);
  9750. }
  9751. const subid = asfLink.innerText.match(/[\d]+/g)?.filter(matched => !appid.includes(matched));
  9752. if (!subid || subid.length === 0) {
  9753. continue;
  9754. }
  9755. this.#addBtn($(asfLink).children('em')[0], 'steam', 'licenseLinks', `subid-${subid.join(',')}`);
  9756. }
  9757. }
  9758. }
  9759. if ($('#threadindex').length > 0) {
  9760. const [ targetNode ] = $('#postlist').children('div[id^="post_"]');
  9761. const config = {
  9762. childList: true
  9763. };
  9764. const observer = new MutationObserver(() => {
  9765. observer.disconnect();
  9766. this.after();
  9767. });
  9768. observer.observe(targetNode, config);
  9769. }
  9770. } catch (error) {
  9771. throwError(error, 'keylol.after');
  9772. }
  9773. }
  9774. classifyTask(action) {
  9775. try {
  9776. this.socialTasks = JSON.parse(Keylol_defaultTasks);
  9777. this.undoneTasks = JSON.parse(Keylol_defaultTasks);
  9778. const selectedBtns = $('.auto-task-keylol[selected="selected"]:visible');
  9779. for (const btn of selectedBtns) {
  9780. const button = $(btn);
  9781. const social = button.attr('data-social');
  9782. const type = button.attr('data-type');
  9783. const link = button.attr('data-link');
  9784. if (!(social && type && link)) {
  9785. continue;
  9786. }
  9787. if (action === 'do') {
  9788. this.undoneTasks[social][type].push(link);
  9789. }
  9790. if (action === 'undo') {
  9791. this.socialTasks[social][type].push(link);
  9792. }
  9793. }
  9794. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9795. this.socialTasks = this.uniqueTasks(this.socialTasks);
  9796. if (window.DEBUG) {
  9797. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9798. }
  9799. return true;
  9800. } catch (error) {
  9801. throwError(error, 'Keylol.classifyTask');
  9802. return false;
  9803. }
  9804. }
  9805. selectAll() {
  9806. try {
  9807. $('.auto-task-keylol:visible').attr('selected', 'selected');
  9808. } catch (error) {
  9809. throwError(error, 'Keylol.selectAll');
  9810. }
  9811. }
  9812. selectNone() {
  9813. try {
  9814. $('.auto-task-keylol:visible').removeAttr('selected');
  9815. } catch (error) {
  9816. throwError(error, 'Keylol.selectNone');
  9817. }
  9818. }
  9819. invertSelect() {
  9820. try {
  9821. $('.auto-task-keylol:visible').each((index, element) => {
  9822. element.getAttribute('selected') ? element.removeAttribute('selected') : element.setAttribute('selected', 'selected');
  9823. });
  9824. } catch (error) {
  9825. throwError(error, 'Keylol.invertSelect');
  9826. }
  9827. }
  9828. #addBtn(before, social, linkType, link) {
  9829. try {
  9830. $(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>`);
  9831. } catch (error) {
  9832. throwError(error, 'keylol.addBtn');
  9833. }
  9834. }
  9835. }
  9836. const website_Keylol = Keylol;
  9837. const Opquests_defaultTasks = {
  9838. steam: {
  9839. groupLinks: [],
  9840. wishlistLinks: [],
  9841. followLinks: [],
  9842. curatorLikeLinks: []
  9843. },
  9844. twitter: {
  9845. userLinks: [],
  9846. retweetLinks: []
  9847. }
  9848. };
  9849. class Opquests extends website_Website {
  9850. name = 'Opquests';
  9851. undoneTasks = {
  9852. ...Opquests_defaultTasks
  9853. };
  9854. buttons = [ 'doTask', 'verifyTask', 'getKey' ];
  9855. static test() {
  9856. return window.location.host === 'opquests.com';
  9857. }
  9858. async after() {
  9859. try {
  9860. if (!this.#checkLogin()) {
  9861. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  9862. }
  9863. const opquestsVerifyTasks = GM_getValue('opquestsVerifyTasks') || [];
  9864. if (opquestsVerifyTasks.length > 0) {
  9865. const taskId = opquestsVerifyTasks.pop();
  9866. GM_setValue('opquestsVerifyTasks', opquestsVerifyTasks);
  9867. const [ verifyBtn ] = $(`#task_id[value="${taskId}"]`).parent().find('button[type="button"]').has('i.fa-check');
  9868. if (verifyBtn) {
  9869. verifyBtn.click();
  9870. return;
  9871. }
  9872. this.after();
  9873. return;
  9874. }
  9875. if (GM_getValue('opquestsVerifyTasks')) {
  9876. GM_deleteValue('opquestsVerifyTasks');
  9877. }
  9878. } catch (error) {
  9879. throwError(error, 'Opquests.after');
  9880. }
  9881. }
  9882. init() {
  9883. try {
  9884. const logStatus = scripts_echoLog({
  9885. text: i18n('initing')
  9886. });
  9887. if ($('a[href*="/auth/redirect"]').length > 0) {
  9888. window.open('/auth/redirect', '_self');
  9889. logStatus.warning(i18n('needLogin'));
  9890. return false;
  9891. }
  9892. if (!this.#getGiveawayId()) {
  9893. return false;
  9894. }
  9895. this.initialized = true;
  9896. logStatus.success();
  9897. return true;
  9898. } catch (error) {
  9899. throwError(error, 'Opquests.init');
  9900. return false;
  9901. }
  9902. }
  9903. async classifyTask(action) {
  9904. try {
  9905. if (action === 'undo') {
  9906. scripts_echoLog({
  9907. text: i18n('cannotUndo')
  9908. });
  9909. return false;
  9910. }
  9911. const logStatus = scripts_echoLog({
  9912. text: i18n('getTasksInfo')
  9913. });
  9914. const tasks = $('.w-full:contains("Validate") .items-center');
  9915. for (const task of tasks) {
  9916. const link = $(task).find('a:contains("Open")').attr('href');
  9917. const taskDes = $(task).find('div').eq(1).text().trim();
  9918. if (!link) {
  9919. continue;
  9920. }
  9921. if (/steamcommunity\.com\/groups\//.test(link)) {
  9922. this.undoneTasks.steam.groupLinks.push(link);
  9923. } else if (/store\.steampowered\.com\/app\//.test(link)) {
  9924. if (/wishlist/gim.test(taskDes)) {
  9925. this.undoneTasks.steam.wishlistLinks.push(link);
  9926. } else if (/follow/gim.test(taskDes)) {
  9927. this.undoneTasks.steam.followLinks.push(link);
  9928. }
  9929. } else if (/store\.steampowered\.com\/(publisher|developer|curator)\//.test(link) && /follow/gim.test(taskDes)) {
  9930. this.undoneTasks.steam.curatorLikeLinks.push(link);
  9931. } else if (link.includes('//x.com/') && /follow/gim.test(taskDes)) {
  9932. this.undoneTasks.twitter.userLinks.push(link);
  9933. } else if (link.includes('//x.com/') && link.includes('status') && /Repost/gim.test(taskDes)) {
  9934. this.undoneTasks.twitter.retweetLinks.push(link);
  9935. } else if (/clash\.gg/.test(link)) {
  9936. scripts_echoLog({}).warning(`${i18n('unSupporttedTaskType')}: ${taskDes}(${link})`);
  9937. } else {
  9938. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskDes}(${link})`);
  9939. }
  9940. }
  9941. logStatus.success();
  9942. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  9943. if (window.DEBUG) {
  9944. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  9945. }
  9946. return true;
  9947. } catch (error) {
  9948. throwError(error, 'Opquests.classifyTask');
  9949. return false;
  9950. }
  9951. }
  9952. async verifyTask() {
  9953. try {
  9954. if (!this.initialized) {
  9955. this.init();
  9956. }
  9957. const tasks = $.makeArray($('.items-center').has('input[name="task_id"]')).map(ele => $(ele).find('input[name="task_id"]').val());
  9958. GM_setValue('opquestsVerifyTasks', tasks);
  9959. await this.#confirm();
  9960. this.after();
  9961. return true;
  9962. } catch (error) {
  9963. throwError(error, 'Opquests.verifyTask');
  9964. return false;
  9965. }
  9966. }
  9967. async #confirm() {
  9968. try {
  9969. const logStatus = scripts_echoLog({
  9970. html: `<li>${i18n('confirmingTask')}...<font></font></li>`
  9971. });
  9972. const {
  9973. result,
  9974. statusText,
  9975. status,
  9976. data
  9977. } = await tools_httpRequest({
  9978. url: `https://opquests.com/quests/${this.giveawayId}?confirm=1`,
  9979. method: 'GET',
  9980. nochche: true,
  9981. headers: {
  9982. origin: 'https://opquests.com',
  9983. referer: `https://opquests.com/warning?id=${this.giveawayId}`
  9984. }
  9985. });
  9986. if (result === 'Success') {
  9987. if (data?.status === 200) {
  9988. logStatus.success();
  9989. return true;
  9990. }
  9991. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  9992. return false;
  9993. }
  9994. logStatus.error(`${result}:${statusText}(${status})`);
  9995. return false;
  9996. } catch (error) {
  9997. throwError(error, 'Opquests.confirm');
  9998. return false;
  9999. }
  10000. }
  10001. async getKey(isButton) {
  10002. try {
  10003. const logStatus = scripts_echoLog({
  10004. text: i18n('gettingKey')
  10005. });
  10006. const {
  10007. result,
  10008. statusText,
  10009. status,
  10010. data
  10011. } = await tools_httpRequest({
  10012. url: 'https://opquests.com/keys',
  10013. method: 'GET'
  10014. });
  10015. if (result === 'Success') {
  10016. if (data?.responseText) {
  10017. const key = $(data?.responseText).find(`div.items-center:contains("${$('h1.font-bold').text().trim().replace(' Quest', '')}")`).find('div.font-bold').next().text();
  10018. if (!key) {
  10019. logStatus.error('Error: Key was not found');
  10020. if (isButton) {
  10021. window.open('https://opquests.com/keys', '_self');
  10022. }
  10023. return false;
  10024. }
  10025. logStatus.success();
  10026. scripts_echoLog({}).success(key);
  10027. return true;
  10028. }
  10029. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10030. return false;
  10031. }
  10032. logStatus.error(`${result}:${statusText}(${status})`);
  10033. return false;
  10034. } catch (error) {
  10035. throwError(error, 'Opquests.getGiveawayId');
  10036. return false;
  10037. }
  10038. }
  10039. #getGiveawayId() {
  10040. try {
  10041. const giveawayId = window.location.href.match(/quests\/([\d]+)/)?.[1];
  10042. if (giveawayId) {
  10043. this.giveawayId = giveawayId;
  10044. return true;
  10045. }
  10046. scripts_echoLog({}).error(i18n('getFailed', 'GiveawayId'));
  10047. return false;
  10048. } catch (error) {
  10049. throwError(error, 'Opquests.getGiveawayId');
  10050. return false;
  10051. }
  10052. }
  10053. #checkLogin() {
  10054. try {
  10055. if (!globalOptions.other.checkLogin) {
  10056. return true;
  10057. }
  10058. if ($('a[href*="/auth/redirect"]').length > 0) {
  10059. window.open('/auth/redirect', '_self');
  10060. }
  10061. return true;
  10062. } catch (error) {
  10063. throwError(error, 'Opquests.checkLogin');
  10064. return false;
  10065. }
  10066. }
  10067. }
  10068. const website_Opquests = Opquests;
  10069. const Gleam_defaultTasksTemplate = {
  10070. steam: {
  10071. groupLinks: [],
  10072. wishlistLinks: [],
  10073. followLinks: [],
  10074. curatorLinks: [],
  10075. curatorLikeLinks: []
  10076. },
  10077. twitter: {
  10078. userLinks: [],
  10079. retweetLinks: []
  10080. },
  10081. twitch: {
  10082. channelLinks: []
  10083. },
  10084. discord: {
  10085. serverLinks: []
  10086. },
  10087. youtube: {
  10088. channelLinks: []
  10089. },
  10090. extra: {
  10091. gleam: []
  10092. }
  10093. };
  10094. const Gleam_defaultTasks = JSON.stringify(Gleam_defaultTasksTemplate);
  10095. class Gleam extends website_Website {
  10096. name = 'Gleam';
  10097. undoneTasks = JSON.parse(Gleam_defaultTasks);
  10098. socialTasks = JSON.parse(Gleam_defaultTasks);
  10099. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  10100. static test() {
  10101. return window.location.host === 'gleam.io';
  10102. }
  10103. before() {
  10104. try {
  10105. unsafeWindow.confirm = () => {};
  10106. unsafeWindow.alert = () => {};
  10107. unsafeWindow.prompt = () => {};
  10108. } catch (error) {
  10109. throwError(error, 'Gleam.before');
  10110. }
  10111. }
  10112. async after() {
  10113. try {
  10114. if (window.location.search.includes('8b07d23f4bfa65f9')) {
  10115. const checkComplete = setInterval(() => {
  10116. if ($('.entry-content .entry-method i.fa-check').length > 0) {
  10117. clearInterval(checkComplete);
  10118. window.close();
  10119. }
  10120. });
  10121. for (const task of $('.entry-content .entry-method')) {
  10122. const taskInfo = $(task).find('.user-links');
  10123. const expandInfo = $(task).find('.expandable');
  10124. const aElements = expandInfo.find('a.btn,a:contains(Continue),button:contains(Continue)');
  10125. if (aElements.length > 0) {
  10126. for (const element of aElements) {
  10127. const $element = $(element);
  10128. const href = $element.attr('href');
  10129. $element.removeAttr('href')[0].click();
  10130. $element.attr('href', href);
  10131. await delay(1e3);
  10132. }
  10133. }
  10134. taskInfo[0].click();
  10135. await delay(1e3);
  10136. }
  10137. scripts_echoLog({}).warning(i18n('gleamTaskNotice'));
  10138. } else if (!await this.#checkLeftKey()) {
  10139. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  10140. }
  10141. } catch (error) {
  10142. throwError(error, 'Gleam.after');
  10143. }
  10144. }
  10145. init() {
  10146. try {
  10147. const logStatus = scripts_echoLog({
  10148. text: i18n('initing')
  10149. });
  10150. if (!this.#getGiveawayId()) {
  10151. return false;
  10152. }
  10153. this.initialized = true;
  10154. logStatus.success();
  10155. return true;
  10156. } catch (error) {
  10157. throwError(error, 'Gleam.init');
  10158. return false;
  10159. }
  10160. }
  10161. async classifyTask(action) {
  10162. try {
  10163. const logStatus = scripts_echoLog({
  10164. text: i18n('getTasksInfo')
  10165. });
  10166. if (action === 'undo') {
  10167. this.socialTasks = GM_getValue(`gleamTasks-${this.giveawayId}`)?.tasks || JSON.parse(Gleam_defaultTasks);
  10168. }
  10169. const tasks = $('.entry-content .entry-method');
  10170. for (const task of tasks) {
  10171. const $task = $(task);
  10172. if (action === 'do' && $task.find('i.fa-question').length === 0) {
  10173. continue;
  10174. }
  10175. const socialIcon = $task.find('.icon-wrapper i');
  10176. const taskInfo = $task.find('.user-links');
  10177. const taskText = taskInfo.text().trim();
  10178. const expandInfo = $task.find('.expandable');
  10179. const aElements = expandInfo.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. if (socialIcon.hasClass('fa-twitter') || socialIcon.hasClass('fa-x-twitter')) {
  10189. const link = $task.find('a[href^="https://twitter.com/"],a[href^="https://x.com/"]').attr('href');
  10190. if (!link) {
  10191. continue;
  10192. }
  10193. if (/follow/gi.test(taskText)) {
  10194. if (action === 'undo') {
  10195. this.socialTasks.twitter.userLinks.push(link);
  10196. }
  10197. if (action === 'do') {
  10198. this.undoneTasks.twitter.userLinks.push(link);
  10199. }
  10200. } else if (/retweet/gim.test(taskText)) {
  10201. if (action === 'undo') {
  10202. this.socialTasks.twitter.retweetLinks.push(link);
  10203. }
  10204. if (action === 'do') {
  10205. this.undoneTasks.twitter.retweetLinks.push(link);
  10206. }
  10207. }
  10208. } else if (socialIcon.hasClass('fa-twitch')) {
  10209. if (/follow/gim.test(taskText)) {
  10210. const link = $task.find('a[href^="https://twitch.tv/"]').attr('href');
  10211. if (!link) {
  10212. continue;
  10213. }
  10214. if (action === 'undo') {
  10215. this.socialTasks.twitch.channelLinks.push(link);
  10216. }
  10217. if (action === 'do') {
  10218. this.undoneTasks.twitch.channelLinks.push(link);
  10219. }
  10220. }
  10221. } else if (socialIcon.hasClass('fa-discord')) {
  10222. if (/join/gim.test(taskText)) {
  10223. let link = $task.find('a[href^="https://discord.com/invite/"]').attr('href');
  10224. if (!link) {
  10225. const ggLink = $task.find('a[href^="https://discord.gg/"]').attr('href')?.match(/discord\.gg\/([^/]+)/)?.[1];
  10226. if (!ggLink) {
  10227. continue;
  10228. }
  10229. link = `https://discord.com/invite/${ggLink}`;
  10230. }
  10231. if (action === 'undo') {
  10232. this.socialTasks.discord.serverLinks.push(link);
  10233. }
  10234. if (action === 'do') {
  10235. this.undoneTasks.discord.serverLinks.push(link);
  10236. }
  10237. }
  10238. } else if (socialIcon.hasClass('fa-external-link-square-alt')) {
  10239. continue;
  10240. } else if (socialIcon.hasClass('fa-youtube')) {
  10241. if (/subscribe/gim.test(taskText)) {
  10242. const link = $task.find('a[href^="https://www.youtube.com/channel/"]').attr('href');
  10243. if (!link) {
  10244. continue;
  10245. }
  10246. if (action === 'undo') {
  10247. this.socialTasks.youtube.channelLinks.push(link);
  10248. }
  10249. if (action === 'do') {
  10250. this.undoneTasks.youtube.channelLinks.push(link);
  10251. }
  10252. }
  10253. } else if (socialIcon.attr('class')?.includes('steam')) {
  10254. if (/join.*group/gi.test(taskText)) {
  10255. const link = $task.find('a[href^="https://steamcommunity.com/groups/"]').attr('href');
  10256. if (!link) {
  10257. continue;
  10258. }
  10259. if (action === 'undo') {
  10260. this.socialTasks.steam.groupLinks.push(link);
  10261. }
  10262. if (action === 'do') {
  10263. this.undoneTasks.steam.groupLinks.push(link);
  10264. }
  10265. } else if (/follow.*curator/gi.test(taskText)) {
  10266. const link = $task.find('a[href^="https://store.steampowered.com/curator/"]').attr('href');
  10267. if (!link) {
  10268. continue;
  10269. }
  10270. if (action === 'undo') {
  10271. this.socialTasks.steam.curatorLinks.push(link);
  10272. }
  10273. if (action === 'do') {
  10274. this.undoneTasks.steam.curatorLinks.push(link);
  10275. }
  10276. }
  10277. } else if (socialIcon.hasClass('fa-bullhorn') && /Complete|Increase/gi.test(taskText)) {
  10278. if (action !== 'do') {
  10279. continue;
  10280. }
  10281. const gleamLink = await this.#getGleamLink(taskText);
  10282. if (!gleamLink) {
  10283. continue;
  10284. }
  10285. this.undoneTasks.extra.gleam.push(gleamLink);
  10286. } 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 {
  10287. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${taskText}`);
  10288. }
  10289. }
  10290. logStatus.success();
  10291. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  10292. this.socialTasks = this.uniqueTasks(this.socialTasks);
  10293. if (window.DEBUG) {
  10294. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  10295. }
  10296. GM_setValue(`gleamTasks-${this.giveawayId}`, {
  10297. tasks: this.socialTasks,
  10298. time: new Date().getTime()
  10299. });
  10300. return true;
  10301. } catch (error) {
  10302. throwError(error, 'Gleam.classifyTask');
  10303. return false;
  10304. }
  10305. }
  10306. async extraDoTask({
  10307. gleam
  10308. }) {
  10309. try {
  10310. const pro = [];
  10311. for (const link of gleam) {
  10312. pro.push(this.#doGleamTask(link));
  10313. }
  10314. return Promise.all(pro).then(() => true);
  10315. } catch (error) {
  10316. throwError(error, 'Gleam.extraDoTask');
  10317. return false;
  10318. }
  10319. }
  10320. async verifyTask() {
  10321. try {
  10322. scripts_echoLog({
  10323. text: `${i18n('verifyingTask')}...`
  10324. });
  10325. const tasks = $('.entry-content .entry-method');
  10326. unsafeWindow._OxA = '_OxA';
  10327. for (const task of tasks) {
  10328. if ($('[campaign-key="campaign.key"]').length > 0) {
  10329. return scripts_echoLog({
  10330. text: i18n('campaign')
  10331. });
  10332. }
  10333. const $task = $(task);
  10334. if ($task.find('i.fa-question').length === 0) {
  10335. continue;
  10336. }
  10337. const taskInfo = $task.find('.user-links');
  10338. taskInfo[0].click();
  10339. const aElements = $task.find('.expandable').find('a.btn');
  10340. if (aElements.length > 0) {
  10341. for (const element of aElements) {
  10342. const $element = $(element);
  10343. const href = $element.attr('href');
  10344. $element.removeAttr('href')[0].click();
  10345. $element.attr('href', href);
  10346. }
  10347. }
  10348. unsafeWindow.$hookTimer?.setSpeed(1e3);
  10349. const visitBtn = $task.find('.expandable').find('span:contains(more seconds),button:contains(more seconds)').filter(':visible');
  10350. if (visitBtn.length > 0 && unsafeWindow.$hookTimer) {
  10351. const newTab = GM_openInTab('', {
  10352. active: true
  10353. });
  10354. await delay(1e3);
  10355. newTab?.close();
  10356. window.focus();
  10357. }
  10358. await delay(3e3);
  10359. unsafeWindow.$hookTimer?.setSpeed(1);
  10360. const expandInfo = $task.find('.expandable');
  10361. const [ input ] = expandInfo.find('input');
  10362. if (input) {
  10363. const evt = new Event('input', {
  10364. bubbles: true,
  10365. cancelable: true,
  10366. composed: true
  10367. });
  10368. const valuelimit = [ ...expandInfo.text().matchAll(/"(.+?)"/g) ].at(-1)?.[1];
  10369. input.value = valuelimit || 'vloot';
  10370. input.dispatchEvent(evt);
  10371. await delay(1e3);
  10372. }
  10373. await this.#checkSync();
  10374. const continueBtn = $task.find('.expandable').find('span:contains(Continue),button:contains(Continue)');
  10375. for (const button of continueBtn) {
  10376. button.click();
  10377. await delay(500);
  10378. await this.#checkSync();
  10379. }
  10380. }
  10381. scripts_echoLog({
  10382. text: i18n('verifiedGleamTasks')
  10383. });
  10384. } catch (error) {
  10385. throwError(error, 'Gleam.verifyTask');
  10386. return false;
  10387. }
  10388. }
  10389. async #checkSync() {
  10390. try {
  10391. return await new Promise(resolve => {
  10392. const checker = setInterval(() => {
  10393. if ($('.entry-content .entry-method i.fa-sync').length === 0) {
  10394. clearInterval(checker);
  10395. resolve(true);
  10396. }
  10397. }, 500);
  10398. });
  10399. } catch (error) {
  10400. throwError(error, 'Gleam.checkSync');
  10401. return false;
  10402. }
  10403. }
  10404. async #doGleamTask(link) {
  10405. try {
  10406. const logStatus = scripts_echoLog({
  10407. text: i18n('doingGleamTask')
  10408. });
  10409. return await new Promise(resolve => {
  10410. GM_openInTab(`${link}?8b07d23f4bfa65f9`, {
  10411. active: true,
  10412. insert: true,
  10413. setParent: true
  10414. }).onclose = () => {
  10415. logStatus.success();
  10416. resolve(true);
  10417. };
  10418. });
  10419. } catch (error) {
  10420. throwError(error, 'Gleam.doGleamTask');
  10421. return false;
  10422. }
  10423. }
  10424. #getGiveawayId() {
  10425. try {
  10426. const giveawayId = window.location.pathname;
  10427. if (giveawayId) {
  10428. this.giveawayId = giveawayId;
  10429. return true;
  10430. }
  10431. scripts_echoLog({
  10432. text: i18n('getFailed', 'GiveawayId')
  10433. });
  10434. return false;
  10435. } catch (error) {
  10436. throwError(error, 'Gleam.getGiveawayId');
  10437. return false;
  10438. }
  10439. }
  10440. async #getGleamLink(title) {
  10441. try {
  10442. const logStatus = scripts_echoLog({
  10443. text: i18n('gettingGleamLink')
  10444. });
  10445. const {
  10446. result,
  10447. statusText,
  10448. status,
  10449. data
  10450. } = await tools_httpRequest({
  10451. url: 'https://www.vloot.io/api/v1/giveaways',
  10452. method: 'GET',
  10453. responseType: 'json'
  10454. });
  10455. if (result === 'Success') {
  10456. if (data?.status === 200 && data?.response?.Success === true && data?.response?.Data) {
  10457. const {
  10458. link
  10459. } = data.response.Data.find(giveaway => title.replace(/[\s]/g, '').toLowerCase().includes(giveaway.title.replace(/[\s]/g, '').toLowerCase())) || {};
  10460. if (link) {
  10461. logStatus.success();
  10462. return link;
  10463. }
  10464. logStatus.error(`Error:${i18n('getLinkFailed')}`);
  10465. return false;
  10466. }
  10467. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10468. return false;
  10469. }
  10470. logStatus.error(`${result}:${statusText}(${status})`);
  10471. return false;
  10472. } catch (error) {
  10473. throwError(error, 'Gleam.getGleamLink');
  10474. return false;
  10475. }
  10476. }
  10477. async #checkLeftKey() {
  10478. try {
  10479. if (!globalOptions.other.checkLeftKey) {
  10480. return true;
  10481. }
  10482. const campaignString = $('div.popup-blocks-container').attr('ng-init')?.match(/initCampaign\(([\w\W]+?)\)$/)?.[1];
  10483. if (!campaignString) {
  10484. return false;
  10485. }
  10486. const {
  10487. campaign,
  10488. incentive
  10489. } = JSON.parse(campaignString);
  10490. const controllerString = $('div.campaign.reward').attr('ng-init')?.match(/initContestant\(([\w\W]+?)\);/)?.[1];
  10491. let ownedKey = false;
  10492. if (controllerString) {
  10493. if (JSON.parse(controllerString).contestant?.claims?.incentives?.[incentive.id]?.length) {
  10494. ownedKey = true;
  10495. }
  10496. }
  10497. if (campaign.banned || campaign.finished && !ownedKey || campaign.paused || new Date().getTime() < campaign.starts_at * 1e3) {
  10498. await external_Swal_default().fire({
  10499. icon: 'warning',
  10500. title: i18n('notice'),
  10501. text: i18n('giveawayNotWork'),
  10502. confirmButtonText: i18n('confirm'),
  10503. cancelButtonText: i18n('cancel'),
  10504. showCancelButton: true
  10505. }).then(({
  10506. value
  10507. }) => {
  10508. if (value) {
  10509. window.close();
  10510. }
  10511. });
  10512. }
  10513. return true;
  10514. } catch (error) {
  10515. throwError(error, 'Gleam.checkLeftKey');
  10516. return false;
  10517. }
  10518. }
  10519. }
  10520. const website_Gleam = Gleam;
  10521. const SweepWidget_defaultOptions = {
  10522. username: '',
  10523. email: ''
  10524. };
  10525. class SweepWidget extends website_Website {
  10526. name = 'SweepWidget';
  10527. options = {
  10528. ...SweepWidget_defaultOptions,
  10529. ...GM_getValue('SweepWidgetOptions')
  10530. };
  10531. buttons = [ 'doTask' ];
  10532. static test() {
  10533. return /^https?:\/\/sweepwidget\.com\/view\/[\d]+/.test(window.location.href);
  10534. }
  10535. async after() {
  10536. try {
  10537. if (!this.#checkLogin()) {
  10538. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  10539. }
  10540. } catch (error) {
  10541. throwError(error, 'SweepWidget.after');
  10542. }
  10543. }
  10544. init() {
  10545. try {
  10546. const logStatus = scripts_echoLog({
  10547. text: i18n('initing')
  10548. });
  10549. if (!this.#checkLogin()) {
  10550. logStatus.warning(i18n('needLogin'));
  10551. return false;
  10552. }
  10553. if (!this.#getGiveawayId()) {
  10554. return false;
  10555. }
  10556. this.initialized = true;
  10557. logStatus.success();
  10558. return true;
  10559. } catch (error) {
  10560. throwError(error, 'SweepWidget.init');
  10561. return false;
  10562. }
  10563. }
  10564. classifyTask() {
  10565. return true;
  10566. }
  10567. async doTask() {
  10568. try {
  10569. if ($('#unlock_rewards_main_wrapper').length === 0) {
  10570. if ($('input[name="sw__login_name"]:visible').length > 0) {
  10571. $('input[name="sw__login_name"]').val(this.options.username);
  10572. }
  10573. if ($('input[name="sw__login_email"]:visible').length > 0) {
  10574. $('input[name="sw__login_email"]').val(this.options.email);
  10575. }
  10576. if ($('#sw_login_button:visible').length > 0) {
  10577. $('#sw_login_button')[0].click();
  10578. }
  10579. if (!await this.#checkEnter()) {
  10580. return false;
  10581. }
  10582. }
  10583. const logStatus = scripts_echoLog({
  10584. text: i18n('SweepWidgetNotice')
  10585. });
  10586. const tasks = $('#sw_inner_entry_methods_l2_wrapper>div.sw_entry');
  10587. for (const task of tasks) {
  10588. const $task = $(task);
  10589. if ($task.find('i.fa-check:visible').length > 0) {
  10590. continue;
  10591. }
  10592. const title = $task.find('.sw_text_inner');
  10593. title[0].click();
  10594. const aElement = $task.find('a.sw_link');
  10595. const link = aElement.attr('href');
  10596. aElement.attr('href', '#a').attr('target', '_self');
  10597. aElement[0]?.click();
  10598. await delay(300);
  10599. aElement.attr('href', link).attr('target', '_blank');
  10600. $task.find('input[type="text"]').val('test');
  10601. const verifyBtn = $task.find('input.sw_verify');
  10602. if (verifyBtn.prop('disabled') === true) {
  10603. title[0].click();
  10604. await delay(300);
  10605. title[0].click();
  10606. await delay(300);
  10607. }
  10608. $task.find('input.sw_verify').removeAttr('disabled')[0]?.click();
  10609. await this.#checkFinish($task);
  10610. await delay(parseInt(`${Math.random() * (3e3 - 1e3 + 1) + 1e3}`, 10));
  10611. }
  10612. logStatus.success();
  10613. return true;
  10614. } catch (error) {
  10615. throwError(error, 'SweepWidget.doTask');
  10616. return false;
  10617. }
  10618. }
  10619. #checkLogin() {
  10620. try {
  10621. if ($('#twitter_login_button').length > 0) {
  10622. $('#twitter_login_button')[0].click();
  10623. }
  10624. return true;
  10625. } catch (error) {
  10626. throwError(error, 'SweepWidget.checkLogin');
  10627. return false;
  10628. }
  10629. }
  10630. #getGiveawayId() {
  10631. try {
  10632. const giveawayId = window.location.href.match(/\/view\/([\d]+)/)?.[1];
  10633. if (giveawayId) {
  10634. this.giveawayId = giveawayId;
  10635. return true;
  10636. }
  10637. scripts_echoLog({
  10638. text: i18n('getFailed', 'GiveawayId')
  10639. });
  10640. return false;
  10641. } catch (error) {
  10642. throwError(error, 'SweepWidget.getGiveawayId');
  10643. return false;
  10644. }
  10645. }
  10646. async #checkEnter() {
  10647. try {
  10648. return new Promise(resolve => {
  10649. const checker = setInterval(() => {
  10650. if ($('#unlock_rewards_main_wrapper').length > 0) {
  10651. clearInterval(checker);
  10652. resolve(true);
  10653. }
  10654. }, 500);
  10655. });
  10656. } catch (error) {
  10657. throwError(error, 'SweepWidget.checkEnter');
  10658. return false;
  10659. }
  10660. }
  10661. async #checkFinish($task) {
  10662. try {
  10663. return new Promise(resolve => {
  10664. const checker = setInterval(() => {
  10665. if ($task.find('i.fa-check:visible').length > 0 || $task.find('.sw_entry_input:visible').length === 0) {
  10666. clearInterval(checker);
  10667. resolve(true);
  10668. }
  10669. }, 500);
  10670. });
  10671. } catch (error) {
  10672. throwError(error, 'SweepWidget.checkFinish');
  10673. return false;
  10674. }
  10675. }
  10676. }
  10677. const website_SweepWidget = SweepWidget;
  10678. const defaultWhiteList = {
  10679. discord: {
  10680. servers: []
  10681. },
  10682. instagram: {
  10683. users: []
  10684. },
  10685. twitch: {
  10686. channels: []
  10687. },
  10688. twitter: {
  10689. users: [],
  10690. retweets: [],
  10691. likes: []
  10692. },
  10693. vk: {
  10694. names: []
  10695. },
  10696. youtube: {
  10697. channels: [],
  10698. likes: []
  10699. },
  10700. reddit: {
  10701. reddits: []
  10702. },
  10703. steam: {
  10704. groups: [],
  10705. officialGroups: [],
  10706. wishlists: [],
  10707. follows: [],
  10708. forums: [],
  10709. workshops: [],
  10710. curators: [],
  10711. workshopVotes: [],
  10712. curatorLikes: [],
  10713. announcements: [],
  10714. licenses: [],
  10715. playtests: [],
  10716. playTime: []
  10717. }
  10718. };
  10719. const link2id = async function(type) {
  10720. try {
  10721. const link = $('#socialLink').val();
  10722. let id = '';
  10723. switch (type) {
  10724. case 'discord.servers':
  10725. id = link.match(/invite\/(.+)/)?.[1] || '';
  10726. break;
  10727.  
  10728. case 'instagram.users':
  10729. id = link.match(/https:\/\/www\.instagram\.com\/(.+)?\//)?.[1] || '';
  10730. break;
  10731.  
  10732. case 'twitch.channels':
  10733. id = link.match(/https:\/\/(www\.)?twitch\.tv\/(.+)/)?.[2] || '';
  10734. break;
  10735.  
  10736. case 'twitter.users':
  10737. id = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || '';
  10738. break;
  10739.  
  10740. case 'twitter.retweets':
  10741. id = link.match(/https:\/\/twitter\.com\/.*?\/status\/([\d]+)/)?.[1] || '';
  10742. break;
  10743.  
  10744. case 'vk.names':
  10745. id = link.match(/https:\/\/vk\.com\/([^/]+)/)?.[1] || '';
  10746. break;
  10747.  
  10748. case 'youtube.channels':
  10749. id = (await getInfo(link, 'channel'))?.params?.channelId || '';
  10750. break;
  10751.  
  10752. case 'youtube.likes':
  10753. id = (await getInfo(link, 'likeVideo'))?.params?.videoId || '';
  10754. break;
  10755.  
  10756. case 'reddit.reddits':
  10757. id = link.match(/https?:\/\/www\.reddit\.com\/user\/([^/]*)/)?.[1] || link.match(/https?:\/\/www\.reddit\.com\/r\/([^/]*)/)?.[1] || '';
  10758. break;
  10759.  
  10760. case 'steam.groups':
  10761. id = link.match(/groups\/(.+)\/?/)?.[1] || '';
  10762. break;
  10763.  
  10764. case 'steam.wishlists':
  10765. case 'steam.follows':
  10766. case 'steam.forums':
  10767. case 'steam.playtests':
  10768. case 'steam.playTime':
  10769. id = link.match(/app\/([\d]+)/)?.[1] || '';
  10770. break;
  10771.  
  10772. case 'steam.workshops':
  10773. id = link.match(/\?id=([\d]+)/)?.[1] || '';
  10774. break;
  10775.  
  10776. case 'steam.curators':
  10777. {
  10778. if (link.includes('curator')) {
  10779. id = link.match(/curator\/([\d]+)/)?.[1] || '';
  10780. } else {
  10781. const param = link.match(/https?:\/\/store\.steampowered\.com\/(.*?)\/([^/?]+)/)?.slice(1, 3);
  10782. if (!param || param.length !== 2) {
  10783. break;
  10784. }
  10785. const steam = new social_Steam();
  10786. if (await steam.init()) {
  10787. id = await steam.getCuratorId(param[0], param[1]) || '';
  10788. }
  10789. }
  10790. }
  10791. break;
  10792. }
  10793. return id;
  10794. } catch (error) {
  10795. throwError(error, 'link2id');
  10796. return i18n('getFailed', 'id');
  10797. }
  10798. };
  10799. const disabledType = {
  10800. steam: [ 'workshopVotes', 'curatorLikes', 'announcements' ],
  10801. twitter: [ 'likes' ]
  10802. };
  10803. const assignWhiteList = whiteList => {
  10804. try {
  10805. const newWhiteList = {};
  10806. for (const [ key, value ] of Object.entries(defaultWhiteList)) {
  10807. newWhiteList[key] = {
  10808. ...value,
  10809. ...whiteList[key]
  10810. };
  10811. }
  10812. return newWhiteList;
  10813. } catch (error) {
  10814. throwError(error, 'assignWhiteList');
  10815. return defaultWhiteList;
  10816. }
  10817. };
  10818. const whiteListOptions = function(showType) {
  10819. try {
  10820. const whiteList = assignWhiteList(GM_getValue('whiteList') || {});
  10821. let whiteListOptionsForm = `<form id="whiteListForm" class="auto-task-form">
  10822. <table class="auto-task-table"><thead><tr><td>${i18n('website')}</td><td>${i18n('type')}</td><td>${i18n('edit')}</td></tr></thead><tbody>`;
  10823. for (const [ social, types ] of Object.entries(whiteList)) {
  10824. 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('');
  10825. }
  10826. whiteListOptionsForm += '</tbody></table></form>';
  10827. if (showType === 'swal') {
  10828. external_Swal_default().fire({
  10829. title: i18n('whiteListOptions'),
  10830. html: whiteListOptionsForm,
  10831. showConfirmButton: false,
  10832. showCloseButton: true
  10833. });
  10834. } else {
  10835. $('body').append(`<h2>${i18n('whiteList')}</h2>${whiteListOptionsForm}`);
  10836. }
  10837. $('.editWhiteList').on('click', function() {
  10838. const value = $(this).attr('data-value');
  10839. if (!value) {
  10840. return;
  10841. }
  10842. const [ social, type ] = value.split('.');
  10843. if (!whiteList?.[social]?.[type]) {
  10844. scripts_echoLog({}).warning(i18n('whiteListNotFound', value));
  10845. return;
  10846. }
  10847. external_Swal_default().fire({
  10848. title: i18n('changeWhiteListOption', value),
  10849. input: 'textarea',
  10850. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  10851. <button id="link2id" data-type="${value}" class="swal2-confirm swal2-styled">获取id</button>
  10852. <p style="margin-bottom:0 !important;">在下方填写白名单,每行一个</p>`,
  10853. inputValue: whiteList[social][type].join('\n'),
  10854. showConfirmButton: true,
  10855. confirmButtonText: i18n('save'),
  10856. showCancelButton: true,
  10857. cancelButtonText: i18n('close'),
  10858. showDenyButton: true,
  10859. denyButtonText: i18n('return')
  10860. }).then(({
  10861. isDenied,
  10862. isConfirmed,
  10863. value
  10864. }) => {
  10865. if (isDenied) {
  10866. if (showType === 'swal') {
  10867. whiteListOptions(showType);
  10868. }
  10869. return;
  10870. } else if (isConfirmed) {
  10871. whiteList[social][type] = value.split('\n');
  10872. GM_setValue('whiteList', whiteList);
  10873. external_Swal_default().fire({
  10874. title: i18n('changeWhiteListSuccess'),
  10875. icon: 'success'
  10876. });
  10877. }
  10878. });
  10879. $('#link2id').on('click', async function() {
  10880. const type = $(this).attr('data-type');
  10881. $('#socialLink').val(await link2id(type));
  10882. });
  10883. });
  10884. } catch (error) {
  10885. throwError(error, 'whiteListOptions');
  10886. }
  10887. };
  10888. const whiteList = whiteListOptions;
  10889. const setGistData = async (token, gistId, fileName, content) => {
  10890. try {
  10891. const logStatus = scripts_echoLog({
  10892. text: i18n('settingData')
  10893. });
  10894. const contentData = JSON.stringify({
  10895. files: {
  10896. [fileName]: {
  10897. content: JSON.stringify(content)
  10898. }
  10899. }
  10900. });
  10901. const {
  10902. result,
  10903. statusText,
  10904. status,
  10905. data
  10906. } = await tools_httpRequest({
  10907. url: `https://api.github.com/gists/${gistId}`,
  10908. headers: {
  10909. Accept: 'application/vnd.github.v3+json',
  10910. Authorization: `token ${token}`
  10911. },
  10912. data: contentData,
  10913. responseType: 'json',
  10914. method: 'POST',
  10915. timeout: 3e4
  10916. });
  10917. if (result === 'Success') {
  10918. if (data?.status === 200 && data.response.files?.[fileName]?.content === JSON.stringify(content)) {
  10919. logStatus.success();
  10920. return true;
  10921. }
  10922. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10923. return false;
  10924. }
  10925. logStatus.error(`${result}:${statusText}(${status})`);
  10926. return false;
  10927. } catch (error) {
  10928. throwError(error, 'setGistData');
  10929. return false;
  10930. }
  10931. };
  10932. const getGistData = async (token, gistId, fileName, test = false) => {
  10933. try {
  10934. const logStatus = scripts_echoLog({
  10935. text: i18n('gettingData')
  10936. });
  10937. const {
  10938. result,
  10939. statusText,
  10940. status,
  10941. data
  10942. } = await tools_httpRequest({
  10943. url: `https://api.github.com/gists/${gistId}`,
  10944. headers: {
  10945. Accept: 'application/vnd.github.v3+json',
  10946. Authorization: `token ${token}`
  10947. },
  10948. responseType: 'json',
  10949. method: 'GET',
  10950. timeout: 3e4
  10951. });
  10952. if (result === 'Success') {
  10953. if (data?.status === 200) {
  10954. const content = data.response?.files?.[fileName]?.content;
  10955. let formatedContent;
  10956. if (!content) {
  10957. logStatus.error(`Error:${i18n('noRemoteData')}`);
  10958. return false;
  10959. }
  10960. if (test) {
  10961. logStatus.success();
  10962. return true;
  10963. }
  10964. try {
  10965. formatedContent = JSON.parse(content);
  10966. } catch (error) {
  10967. logStatus.error(`Error:${i18n('errorRemoteDataFormat')}`);
  10968. return false;
  10969. }
  10970. logStatus.success();
  10971. return formatedContent;
  10972. }
  10973. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  10974. return false;
  10975. }
  10976. logStatus.error(`${result}:${statusText}(${status})`);
  10977. return false;
  10978. } catch (error) {
  10979. throwError(error, 'getGistData');
  10980. return false;
  10981. }
  10982. };
  10983. const syncOptions = () => {
  10984. try {
  10985. const {
  10986. TOKEN,
  10987. GIST_ID,
  10988. FILE_NAME,
  10989. SYNC_HISTORY
  10990. } = GM_getValue('gistOptions') || {
  10991. TOKEN: '',
  10992. GIST_ID: '',
  10993. FILE_NAME: '',
  10994. SYNC_HISTORY: true
  10995. };
  10996. external_Swal_default().fire({
  10997. title: i18n('gistOptions'),
  10998. 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;">
  10999. ${i18n('upload2gist')}</button>` + `<button id="download-data" type="button" class="swal2-confirm swal2-styled" style="display: inline-block;">
  11000. ${i18n('downloadFromGist')}</button></p>`,
  11001. focusConfirm: false,
  11002. showLoaderOnConfirm: true,
  11003. 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>`,
  11004. preConfirm: async () => {
  11005. const token = $('#github-token').val();
  11006. const gistId = $('#gist-id').val();
  11007. const fileName = $('#file-name').val();
  11008. const syncHistory = $('#sync-history').prop('checked');
  11009. GM_setValue('gistOptions', {
  11010. TOKEN: token,
  11011. GIST_ID: gistId,
  11012. FILE_NAME: fileName,
  11013. SYNC_HISTORY: syncHistory
  11014. });
  11015. return await getGistData(token, gistId, fileName, true);
  11016. },
  11017. allowOutsideClick: () => !external_Swal_default().isLoading(),
  11018. confirmButtonText: i18n('saveAndTest'),
  11019. showCancelButton: true,
  11020. cancelButtonText: i18n('close')
  11021. }).then(({
  11022. value
  11023. }) => {
  11024. if (value) {
  11025. external_Swal_default().fire({
  11026. icon: 'success',
  11027. title: i18n('testSuccess')
  11028. }).then(syncOptions);
  11029. } else if (value !== undefined) {
  11030. external_Swal_default().fire({
  11031. icon: 'error',
  11032. title: i18n('testFailed')
  11033. }).then(syncOptions);
  11034. }
  11035. });
  11036. $('#upload-data').on('click', async () => {
  11037. const {
  11038. TOKEN,
  11039. GIST_ID,
  11040. FILE_NAME
  11041. } = GM_getValue('gistOptions') || {};
  11042. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  11043. return external_Swal_default().fire({
  11044. icon: 'error',
  11045. title: i18n('saveAndTestNotice')
  11046. }).then(syncOptions);
  11047. }
  11048. external_Swal_default().fire({
  11049. icon: 'info',
  11050. title: i18n('processingData')
  11051. });
  11052. const data = {};
  11053. const names = GM_listValues();
  11054. const SYNC_HISTORY = $('#sync-history').prop('checked');
  11055. for (const name of names) {
  11056. if (name === 'gistOptions' || /^[\w]+?Auth$/.test(name)) {
  11057. continue;
  11058. }
  11059. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  11060. continue;
  11061. }
  11062. data[name] = GM_getValue(name);
  11063. }
  11064. external_Swal_default().update({
  11065. icon: 'info',
  11066. title: i18n('updatingData')
  11067. });
  11068. if (await setGistData(TOKEN, GIST_ID, FILE_NAME, data)) {
  11069. external_Swal_default().fire({
  11070. icon: 'success',
  11071. title: i18n('syncDataSuccess')
  11072. });
  11073. } else {
  11074. external_Swal_default().fire({
  11075. icon: 'error',
  11076. title: i18n('syncDataFailed')
  11077. });
  11078. }
  11079. });
  11080. $('#download-data').on('click', async () => {
  11081. const {
  11082. TOKEN,
  11083. GIST_ID,
  11084. FILE_NAME
  11085. } = GM_getValue('gistOptions') || {};
  11086. if (!(TOKEN && GIST_ID && FILE_NAME)) {
  11087. return external_Swal_default().fire({
  11088. icon: 'error',
  11089. title: i18n('saveAndTestNotice')
  11090. }).then(syncOptions);
  11091. }
  11092. external_Swal_default().fire({
  11093. icon: 'info',
  11094. title: i18n('downloadingData')
  11095. });
  11096. const data = await getGistData(TOKEN, GIST_ID, FILE_NAME);
  11097. if (!data) {
  11098. return external_Swal_default().fire({
  11099. icon: 'error',
  11100. title: i18n('checkedNoData')
  11101. }).then(syncOptions);
  11102. }
  11103. external_Swal_default().update({
  11104. icon: 'info',
  11105. title: i18n('savingData')
  11106. });
  11107. const SYNC_HISTORY = $('#sync-history').prop('checked');
  11108. for (const [ name, value ] of Object.entries(data)) {
  11109. if (!SYNC_HISTORY && /^[\w]+?Tasks-/.test(name)) {
  11110. continue;
  11111. }
  11112. GM_setValue(name, value);
  11113. }
  11114. external_Swal_default().fire({
  11115. icon: 'success',
  11116. title: i18n('syncDataSuccess')
  11117. });
  11118. });
  11119. } catch (error) {
  11120. throwError(error, 'syncOptions');
  11121. }
  11122. };
  11123. const dataSync = syncOptions;
  11124. class Setting {
  11125. name = 'Setting';
  11126. buttons = [ 'saveGlobalOptions', 'syncData', 'tasksHistory' ];
  11127. syncData = dataSync;
  11128. tasksHistory() {
  11129. GM_openInTab('https://auto-task-v4.hclonely.com/history.html', {
  11130. active: true
  11131. });
  11132. }
  11133. static test() {
  11134. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/setting.html';
  11135. }
  11136. before() {
  11137. try {
  11138. $('body').html('').addClass('auto-task-options');
  11139. } catch (error) {
  11140. throwError(error, 'Setting.before');
  11141. }
  11142. }
  11143. after() {
  11144. try {
  11145. this.#environment();
  11146. changeGlobalOptions('page');
  11147. whiteList('page');
  11148. $('input[name="other.twitterVerifyId"]').after(`<button id="getTwitterUserId" type="button">${i18n('getTwitterUserId')}</button>`);
  11149. $('#getTwitterUserId').on('click', () => {
  11150. this.#getId('twitterUser');
  11151. });
  11152. $('input[name="other.youtubeVerifyChannel"]').after(`<button id="getYoutubeChannelId" type="button">${i18n('getYoutubeChannelId')}</button>`);
  11153. $('#getYoutubeChannelId').on('click', () => {
  11154. this.#getId('youtubeChannel');
  11155. });
  11156. $('input[name^="position"]').on('input', function() {
  11157. const type = $(this).attr('name').replace('position.', '');
  11158. const xLabel = 'rightleft';
  11159. const yLabel = 'topbottpm';
  11160. switch (type) {
  11161. case 'buttonSideX':
  11162. case 'buttonSideY':
  11163. case 'buttonDistance':
  11164. {
  11165. const distance = $('input[name="position.buttonDistance"]').val();
  11166. const sideX = $('input[name="position.buttonSideX"]').val();
  11167. const sideY = $('input[name="position.buttonSideY"]').val();
  11168. if (![ 'right', 'left' ].includes(sideX)) {
  11169. break;
  11170. }
  11171. if (![ 'top', 'bottom' ].includes(sideY)) {
  11172. break;
  11173. }
  11174. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  11175. break;
  11176. }
  11177. const distanceArr = distance.split(',');
  11178. $('#auto-task-buttons').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  11179. break;
  11180. }
  11181.  
  11182. case 'showButtonSideX':
  11183. case 'showButtonSideY':
  11184. case 'showButtonDistance':
  11185. {
  11186. const distance = $('input[name="position.showButtonDistance"]').val();
  11187. const sideX = $('input[name="position.showButtonSideX"]').val();
  11188. const sideY = $('input[name="position.showButtonSideY"]').val();
  11189. if (![ 'right', 'left' ].includes(sideX)) {
  11190. break;
  11191. }
  11192. if (![ 'top', 'bottom' ].includes(sideY)) {
  11193. break;
  11194. }
  11195. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  11196. break;
  11197. }
  11198. const distanceArr = distance.split(',');
  11199. $('div.show-button-div').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  11200. break;
  11201. }
  11202.  
  11203. case 'logSideX':
  11204. case 'logSideY':
  11205. case 'logDistance':
  11206. {
  11207. const distance = $('input[name="position.logDistance"]').val();
  11208. const sideX = $('input[name="position.logSideX"]').val();
  11209. const sideY = $('input[name="position.logSideY"]').val();
  11210. if (![ 'right', 'left' ].includes(sideX)) {
  11211. break;
  11212. }
  11213. if (![ 'top', 'bottom' ].includes(sideY)) {
  11214. break;
  11215. }
  11216. if (!/^[\d]+?,[\d]+$/.test(distance)) {
  11217. break;
  11218. }
  11219. const distanceArr = distance.split(',');
  11220. $('#auto-task-info').css(sideX, `${distanceArr[0]}px`).css(sideY, `${distanceArr[1]}px`).css(xLabel.replace(sideX, ''), '').css(yLabel.replace(sideY, ''), '');
  11221. break;
  11222. }
  11223.  
  11224. default:
  11225. break;
  11226. }
  11227. });
  11228. $('input[name^="hotKey"]').attr('readonly', 'readonly').off('keydown').on('keydown', function(event) {
  11229. let functionKey = '';
  11230. if (event.altKey) {
  11231. functionKey += 'alt + ';
  11232. } else if (event.ctrlKey) {
  11233. functionKey += 'ctrl + ';
  11234. } else if (event.shiftKey) {
  11235. functionKey += 'shift + ';
  11236. }
  11237. $(this).val(functionKey + (event.key.length === 1 ? event.key.toLowerCase() : ''));
  11238. });
  11239. } catch (error) {
  11240. throwError(error, 'Setting.after');
  11241. }
  11242. }
  11243. saveGlobalOptions() {
  11244. try {
  11245. saveData();
  11246. } catch (error) {
  11247. throwError(error, 'Setting.saveGlobalOptions');
  11248. }
  11249. }
  11250. #getId(social) {
  11251. try {
  11252. external_Swal_default().fire({
  11253. title: i18n('getId', i18n(social)),
  11254. html: `<input id="socialLink" class="swal2-input" placeholder="在此处输入链接获取id">
  11255. <button id="link2id" data-type="${social}" class="swal2-confirm swal2-styled">获取id</button>`,
  11256. showCancelButton: true,
  11257. cancelButtonText: i18n('close'),
  11258. showConfirmButton: false
  11259. });
  11260. $('#link2id').on('click', async function() {
  11261. const link = $('#socialLink').val();
  11262. if (!link) {
  11263. return;
  11264. }
  11265. const type = $(this).attr('data-type');
  11266. if (type === 'twitterUser') {
  11267. const name = link.match(/https:\/\/twitter\.com\/(.+)/)?.[1] || link;
  11268. $('#socialLink').val(await new social_Twitter().userName2id(name) || '');
  11269. } else if (type === 'youtubeChannel') {
  11270. const name = /^https:\/\/(www\.)?google\.com.*?\/url\?.*?url=https:\/\/www.youtube.com\/.*/.test(link) ? link.match(/url=(https:\/\/www\.youtube\.com\/.*)/)?.[1] : link;
  11271. $('#socialLink').val((await getInfo(name, 'channel'))?.params?.channelId || '');
  11272. }
  11273. });
  11274. } catch (error) {
  11275. throwError(error, 'Setting.getId');
  11276. }
  11277. }
  11278. #environment() {
  11279. try {
  11280. const userAgent = (0, javascript_utils_umd_min.ua)();
  11281. const environmentForm = `<form id="environmentForm" class="auto-task-form">
  11282. <table class="auto-task-table"><thead><tr><td>${i18n('type')}</td><td>${i18n('name')}</td><td>${i18n('version')}</td></tr></thead><tbody>
  11283. <tr><td>${i18n('os')}</td><td>${userAgent.os}</td><td>${userAgent.osVersion}</td></tr>
  11284. <tr><td>${i18n('browser')}</td><td>${userAgent.browserZH}</td><td>${userAgent.browserVersion}</td></tr>
  11285. <tr><td>${i18n('scriptManager')}</td><td>${GM_info.scriptHandler}</td><td>${GM_info.version}</td></tr>
  11286. <tr><td>${i18n('script')}</td><td>${GM_info.script.name}</td><td>${GM_info.script.version}</td></tr>
  11287. </tbody></table></form>`;
  11288. $('body').append(`<h2>${i18n('environment')}</h2>${environmentForm}`);
  11289. } catch (error) {
  11290. throwError(error, 'Setting.environment');
  11291. }
  11292. }
  11293. }
  11294. const website_Setting = Setting;
  11295. class History extends website_Keylol {
  11296. name = 'History';
  11297. buttons = [ 'doTask', 'undoTask', 'selectAll', 'selectNone', 'invertSelect', 'clearHistory' ];
  11298. static test() {
  11299. return window.location.host === 'auto-task-v4.hclonely.com' && window.location.pathname === '/history.html';
  11300. }
  11301. before() {
  11302. try {
  11303. $('body').html('<div class="container"></div>').addClass('auto-task-history');
  11304. const data = GM_listValues() || [];
  11305. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  11306. for (const item of tasksHistory) {
  11307. this.#addItem(item);
  11308. }
  11309. } catch (error) {
  11310. throwError(error, 'History.before');
  11311. }
  11312. }
  11313. clearHistory() {
  11314. try {
  11315. const data = GM_listValues() || [];
  11316. const tasksHistory = data.map(value => /^[\w]+?Tasks-/.test(value) ? value : null).filter(value => value);
  11317. for (const item of tasksHistory) {
  11318. GM_deleteValue(item);
  11319. }
  11320. external_Swal_default().fire({
  11321. title: i18n('clearHistoryFinished'),
  11322. icon: 'success'
  11323. });
  11324. } catch (error) {
  11325. throwError(error, 'History.clearHistory');
  11326. }
  11327. }
  11328. #addItem(item) {
  11329. try {
  11330. const tasksData = GM_getValue(item);
  11331. if (!tasksData?.tasks) {
  11332. return;
  11333. }
  11334. let html = '';
  11335. let title = '';
  11336. let link = '';
  11337. const [ website, id ] = item.split('-');
  11338. switch (website) {
  11339. case 'fawTasks':
  11340. title = `Freeanywhere[${id}]`;
  11341. link = `https://freeanywhere.net/#/giveaway/${id}`;
  11342. break;
  11343.  
  11344. case 'gasTasks':
  11345. title = `Giveawaysu[${id}]`;
  11346. link = `https://giveaway.su/giveaway/view/${id}`;
  11347. break;
  11348.  
  11349. case 'gcTasks':
  11350. title = `GiveeClub[${id}]`;
  11351. link = `https://givee.club/event/${id}`;
  11352. break;
  11353.  
  11354. case 'gkTasks':
  11355. title = `Givekey[${id}]`;
  11356. link = `https://givekey.ru/giveaway/${id}`;
  11357. break;
  11358.  
  11359. case 'gleamTasks':
  11360. title = `Gleam[${id}]`;
  11361. link = `https://gleam.io${id}`;
  11362. break;
  11363.  
  11364. case 'khTasks':
  11365. title = `keyhub[${id}]`;
  11366. link = `https://key-hub.eu/giveaway/${id}`;
  11367. break;
  11368.  
  11369. case 'prysTasks':
  11370. title = `Prys[${id}]`;
  11371. link = `https://prys.revadike.com/giveaway/?id=${id}`;
  11372. break;
  11373.  
  11374. default:
  11375. return;
  11376. }
  11377. for (const [ social, types ] of Object.entries(tasksData.tasks)) {
  11378. for (const [ type, tasks ] of Object.entries(types)) {
  11379. for (const task of tasks) {
  11380. 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>`;
  11381. }
  11382. }
  11383. }
  11384. $('.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>`);
  11385. $('span.delete-task').on('click', function() {
  11386. const itemName = $(this).attr('data-name');
  11387. if (itemName) {
  11388. GM_deleteValue(itemName);
  11389. $(`div.card[data-name="${itemName}"]`).remove();
  11390. external_Swal_default().fire({
  11391. title: i18n('clearTaskFinished'),
  11392. text: itemName,
  11393. icon: 'success'
  11394. });
  11395. } else {
  11396. external_Swal_default().fire({
  11397. title: i18n('clearTaskFailed'),
  11398. icon: 'error'
  11399. });
  11400. }
  11401. });
  11402. } catch (error) {
  11403. throwError(error, 'History.addItem');
  11404. }
  11405. }
  11406. }
  11407. const website_History = History;
  11408. const GiveawayHopper_defaultTasksTemplate = {
  11409. steam: {
  11410. groupLinks: [],
  11411. wishlistLinks: [],
  11412. followLinks: [],
  11413. curatorLinks: [],
  11414. curatorLikeLinks: []
  11415. },
  11416. twitter: {
  11417. userLinks: [],
  11418. retweetLinks: []
  11419. },
  11420. twitch: {
  11421. channelLinks: []
  11422. },
  11423. discord: {
  11424. serverLinks: []
  11425. },
  11426. youtube: {
  11427. channelLinks: []
  11428. },
  11429. extra: {
  11430. giveawayHopper: []
  11431. }
  11432. };
  11433. const GiveawayHopper_defaultTasks = JSON.stringify(GiveawayHopper_defaultTasksTemplate);
  11434. class GiveawayHopper extends website_Website {
  11435. name = 'GiveawayHopper';
  11436. undoneTasks = JSON.parse(GiveawayHopper_defaultTasks);
  11437. socialTasks = JSON.parse(GiveawayHopper_defaultTasks);
  11438. tasks = [];
  11439. buttons = [ 'doTask', 'undoTask', 'verifyTask' ];
  11440. static test() {
  11441. return window.location.host === 'giveawayhopper.com';
  11442. }
  11443. async after() {
  11444. try {
  11445. if (!this.#checkLogin()) {
  11446. scripts_echoLog({}).warning(i18n('checkLoginFailed'));
  11447. }
  11448. this.#getGiveawayId();
  11449. } catch (error) {
  11450. throwError(error, 'GiveawayHopper.after');
  11451. }
  11452. }
  11453. async init() {
  11454. try {
  11455. const logStatus = scripts_echoLog({
  11456. text: i18n('initing')
  11457. });
  11458. if (!await this.#checkLeftKey()) {
  11459. scripts_echoLog({}).warning(i18n('checkLeftKeyFailed'));
  11460. }
  11461. this.initialized = true;
  11462. logStatus.success();
  11463. return true;
  11464. } catch (error) {
  11465. throwError(error, 'GiveawayHopper.init');
  11466. return false;
  11467. }
  11468. }
  11469. async classifyTask(action) {
  11470. try {
  11471. if (!this.giveawayId) {
  11472. await this.#getGiveawayId();
  11473. }
  11474. const logStatus = scripts_echoLog({
  11475. text: i18n('getTasksInfo')
  11476. });
  11477. if (action === 'undo') {
  11478. this.socialTasks = GM_getValue(`giveawayHopperTasks-${this.giveawayId}`)?.tasks || JSON.parse(GiveawayHopper_defaultTasks);
  11479. }
  11480. const {
  11481. result,
  11482. statusText,
  11483. status,
  11484. data
  11485. } = await tools_httpRequest({
  11486. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/with-auth`,
  11487. method: 'GET',
  11488. responseType: 'json',
  11489. fetch: true,
  11490. headers: {
  11491. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  11492. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  11493. }
  11494. });
  11495. if (result === 'Success') {
  11496. if (data?.status === 200 && data?.response?.tasks) {
  11497. this.tasks = data.response.tasks;
  11498. for (const task of data.response.tasks) {
  11499. if (task.isDone) {
  11500. continue;
  11501. }
  11502. await tools_httpRequest({
  11503. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/visited`,
  11504. method: 'GET',
  11505. responseType: 'json',
  11506. fetch: true,
  11507. headers: {
  11508. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  11509. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  11510. }
  11511. });
  11512. if (task.category === 'Steam' && task.type === 'JoinGroup') {
  11513. const steamGroupLink = await getRedirectLink(`https://steamcommunity.com/gid/${task.group_id}`);
  11514. if (!steamGroupLink) {
  11515. continue;
  11516. }
  11517. if (action === 'undo') {
  11518. this.socialTasks.steam.groupLinks.push(steamGroupLink);
  11519. }
  11520. if (action === 'do') {
  11521. this.undoneTasks.steam.groupLinks.push(steamGroupLink);
  11522. }
  11523. continue;
  11524. }
  11525. if (task.category === 'Discord' && task.type === 'JoinServer') {
  11526. if (action === 'undo') {
  11527. this.socialTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  11528. }
  11529. if (action === 'do') {
  11530. this.undoneTasks.discord.serverLinks.push(`https://discord.gg/${task.invite_code}`);
  11531. }
  11532. continue;
  11533. }
  11534. if ([ 'TikTok', 'YouTube', 'General' ].includes(task.category)) {
  11535. continue;
  11536. }
  11537. scripts_echoLog({}).warning(`${i18n('unKnownTaskType')}: ${task.category}-${task.type}`);
  11538. }
  11539. logStatus.success();
  11540. this.undoneTasks = this.uniqueTasks(this.undoneTasks);
  11541. this.socialTasks = this.uniqueTasks(this.socialTasks);
  11542. if (window.DEBUG) {
  11543. console.log('%cAuto-Task[Debug]:', 'color:blue', JSON.stringify(this));
  11544. }
  11545. GM_setValue(`giveawayHopperTasks-${this.giveawayId}`, {
  11546. tasks: this.socialTasks,
  11547. time: new Date().getTime()
  11548. });
  11549. return true;
  11550. }
  11551. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  11552. return false;
  11553. }
  11554. logStatus.error(`${result}:${statusText}(${status})`);
  11555. return false;
  11556. } catch (error) {
  11557. throwError(error, 'GiveawayHopper.classifyTask');
  11558. return false;
  11559. }
  11560. }
  11561. async verifyTask() {
  11562. try {
  11563. for (const task of this.tasks) {
  11564. if (task.isDone) {
  11565. continue;
  11566. }
  11567. const logStatus = scripts_echoLog({
  11568. text: `${i18n('verifyingTask')}[${task.displayName?.replace(':target', task.targetName) || task.name}]...`
  11569. });
  11570. if (!task.link) {
  11571. if (task.category === 'YouTube' && task.type === 'FollowAccount') {
  11572. task.link = `https://www.youtube.com/@${task.targetName}`;
  11573. } else if (task.category === 'TikTok' && task.type === 'FollowAccount') {
  11574. task.link = `https://www.tiktok.com/@${task.targetName}`;
  11575. } else if (task.category === 'Steam' && task.type === 'JoinGroup') {
  11576. task.link = '';
  11577. } else if (task.category === 'Discord' && task.type === 'JoinServer') {
  11578. task.link = '';
  11579. }
  11580. }
  11581. if (task.link) {
  11582. await tools_httpRequest({
  11583. 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}`,
  11584. method: 'GET',
  11585. fetch: true,
  11586. headers: {
  11587. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  11588. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1])
  11589. }
  11590. });
  11591. }
  11592. await delay(1e3);
  11593. const postData = {
  11594. taskcategory: task.category,
  11595. taskname: task.type
  11596. };
  11597. if ([ 'YouTube', 'TikTok' ].includes(task.category)) {
  11598. postData.username = '1';
  11599. }
  11600. const {
  11601. result,
  11602. statusText,
  11603. status,
  11604. data
  11605. } = await tools_httpRequest({
  11606. url: `https://giveawayhopper.com/api/v1/campaigns/${this.giveawayId}/tasks/${task.id}/complete`,
  11607. method: 'POST',
  11608. fetch: true,
  11609. headers: {
  11610. authorization: `Bearer ${window.sessionStorage.gw_auth}`,
  11611. 'x-xsrf-token': decodeURIComponent(document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1]),
  11612. 'content-type': 'application/json'
  11613. },
  11614. dataType: 'json',
  11615. data: JSON.stringify(postData)
  11616. });
  11617. if (result === 'Success') {
  11618. if (data?.status === 200 && data?.response?.completed) {
  11619. logStatus.success();
  11620. continue;
  11621. }
  11622. logStatus.error(`Error:${data?.statusText}(${data?.status})`);
  11623. continue;
  11624. }
  11625. logStatus.error(`${result}:${statusText}(${status})`);
  11626. continue;
  11627. }
  11628. } catch (error) {
  11629. throwError(error, 'GiveawayHopper.verifyTask');
  11630. return false;
  11631. }
  11632. }
  11633. #getGiveawayId() {
  11634. try {
  11635. const giveawayId = window.location.pathname.split('/').at(-1);
  11636. if (giveawayId) {
  11637. this.giveawayId = giveawayId;
  11638. return true;
  11639. }
  11640. scripts_echoLog({
  11641. text: i18n('getFailed', 'GiveawayId')
  11642. });
  11643. return false;
  11644. } catch (error) {
  11645. throwError(error, 'GiveawayHopper.getGiveawayId');
  11646. return false;
  11647. }
  11648. }
  11649. #checkLogin() {
  11650. try {
  11651. if (!globalOptions.other.checkLogin) {
  11652. return true;
  11653. }
  11654. if ($('div.widget-connections-edit:contains("Log in")').length > 0) {
  11655. $('div.widget-connections-edit:contains("Log in") a')[0].click();
  11656. }
  11657. return true;
  11658. } catch (error) {
  11659. throwError(error, 'GiveawayHopper.checkLogin');
  11660. return false;
  11661. }
  11662. }
  11663. async #checkLeftKey() {
  11664. try {
  11665. if (!globalOptions.other.checkLeftKey) {
  11666. return true;
  11667. }
  11668. if ($('p.widget-single-prize span').length > 0 && parseInt($('p.widget-single-prize span').text()?.match(/\d+/)?.[0] || '0', 10) > 0) {
  11669. return true;
  11670. }
  11671. await external_Swal_default().fire({
  11672. icon: 'warning',
  11673. title: i18n('notice'),
  11674. text: i18n('noKeysLeft'),
  11675. confirmButtonText: i18n('confirm'),
  11676. cancelButtonText: i18n('cancel'),
  11677. showCancelButton: true
  11678. }).then(({
  11679. value
  11680. }) => {
  11681. if (value) {
  11682. window.close();
  11683. }
  11684. });
  11685. return true;
  11686. } catch (error) {
  11687. throwError(error, 'GiveawayHopper.checkLeftKey');
  11688. return false;
  11689. }
  11690. }
  11691. }
  11692. const website_GiveawayHopper = GiveawayHopper;
  11693. 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 ];
  11694. const websiteOptions = function(website, options) {
  11695. try {
  11696. let websiteOptionsForm = `<form id="websiteOptionsForm" class="auto-task-form">
  11697. <table class="auto-task-table"><thead><tr><td>${i18n('option')}</td><td>${i18n('value')}</td></tr></thead><tbody>`;
  11698. for (const [ option, value ] of Object.entries(options)) {
  11699. websiteOptionsForm += `<tr><td>${option}</td><td><input class="editOption" type="text" name="${option}" value="${value}"/></td></tr>`;
  11700. }
  11701. websiteOptionsForm += '</tbody></table></form>';
  11702. external_Swal_default().fire({
  11703. title: i18n('websiteOptions'),
  11704. html: websiteOptionsForm,
  11705. showConfirmButton: true,
  11706. confirmButtonText: i18n('save'),
  11707. showCancelButton: true,
  11708. cancelButtonText: i18n('close')
  11709. }).then(({
  11710. isConfirmed
  11711. }) => {
  11712. if (isConfirmed) {
  11713. $('#websiteOptionsForm').serializeArray().map(value => {
  11714. options[value.name] = value.value;
  11715. return value;
  11716. });
  11717. GM_setValue(`${website}Options`, options);
  11718. external_Swal_default().fire({
  11719. title: i18n('changeWebsiteOptionsSuccess'),
  11720. icon: 'success'
  11721. });
  11722. }
  11723. });
  11724. } catch (error) {
  11725. throwError(error, 'websiteOptions');
  11726. }
  11727. };
  11728. const options = websiteOptions;
  11729. const external_keyboardJS_namespaceObject = keyboardJS;
  11730. var external_keyboardJS_default = __webpack_require__.n(external_keyboardJS_namespaceObject);
  11731. const checkUpdate = async (updateLink, auto) => {
  11732. try {
  11733. const checkUrl = `${updateLink}package.json?time=${new Date().getTime()}`;
  11734. const {
  11735. result,
  11736. statusText,
  11737. status,
  11738. data
  11739. } = await tools_httpRequest({
  11740. url: checkUrl,
  11741. responseType: 'json',
  11742. method: 'GET',
  11743. timeout: 3e4
  11744. });
  11745. if (result === 'Success') {
  11746. if (data?.response?.version) {
  11747. return data.response;
  11748. }
  11749. if (!auto) {
  11750. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${data?.statusText}(${data?.status})]`);
  11751. }
  11752. return false;
  11753. }
  11754. if (!auto) {
  11755. scripts_echoLog({}).error(`${i18n('checkUpdateFailed')}[${result}:${statusText}(${status})]`);
  11756. }
  11757. return false;
  11758. } catch (error) {
  11759. throwError(error, 'checkUpdate');
  11760. return false;
  11761. }
  11762. };
  11763. const hasNewVersion = (currentVersion, remoteVersion) => {
  11764. try {
  11765. const [ currentRealVersion ] = currentVersion.split('-');
  11766. const [ remoteRealVersion, isPreview ] = remoteVersion.split('-');
  11767. if (isPreview && !globalOptions.other.receivePreview) {
  11768. return false;
  11769. }
  11770. const [ currentVersion1, currentVersion2, currentVersion3 ] = currentRealVersion.split('.').map(value => parseInt(value, 10));
  11771. const [ remoteVersion1, remoteVersion2, remoteVersion3 ] = remoteRealVersion.split('.').map(value => parseInt(value, 10));
  11772. if (remoteVersion1 > currentVersion1) {
  11773. return true;
  11774. }
  11775. if (remoteVersion1 < currentVersion1) {
  11776. return false;
  11777. }
  11778. if (remoteVersion2 > currentVersion2) {
  11779. return true;
  11780. }
  11781. if (remoteVersion2 < currentVersion2) {
  11782. return false;
  11783. }
  11784. if (remoteVersion3 > currentVersion3) {
  11785. return true;
  11786. }
  11787. return false;
  11788. } catch (error) {
  11789. throwError(error, 'compareVersion');
  11790. return false;
  11791. }
  11792. };
  11793. const updateChecker = async () => {
  11794. try {
  11795. const currentVersion = GM_info.script.version;
  11796. const updateSource = globalOptions.other.autoUpdateSource.toLowerCase();
  11797. const updateLinks = {
  11798. github: 'https://github.com/HCLonely/auto-task-new/raw/main/',
  11799. jsdelivr: 'https://cdn.jsdelivr.net/gh/HCLonely/auto-task-v4@main/',
  11800. standby: 'https://auto-task-v4.hclonely.com/'
  11801. };
  11802. let version;
  11803. let updateLink = '';
  11804. let packageData;
  11805. if ([ 'github', 'jsdelivr', 'standby' ].includes(updateSource)) {
  11806. updateLink = updateLinks[updateSource];
  11807. packageData = await checkUpdate(updateLink, false);
  11808. } else {
  11809. updateLink = updateLinks.github;
  11810. packageData = await checkUpdate(updateLink, true);
  11811. if (!packageData) {
  11812. updateLink = updateLinks.jsdelivr;
  11813. packageData = await checkUpdate(updateLink, true);
  11814. if (!packageData) {
  11815. updateLink = updateLinks.standby;
  11816. packageData = await checkUpdate(updateLink, true);
  11817. }
  11818. }
  11819. }
  11820. if (packageData) {
  11821. version = packageData.version || currentVersion;
  11822. } else {
  11823. version = currentVersion;
  11824. scripts_echoLog({}).error(i18n('checkUpdateFailed'));
  11825. }
  11826. if (packageData && hasNewVersion(currentVersion, version)) {
  11827. scripts_echoLog({
  11828. html: `<li><font>${i18n('newVersionNotice', version, `${updateLink}dist/${GM_info.script.name}.user.js`)}</font></li>`
  11829. });
  11830. scripts_echoLog({
  11831. html: `<li>${i18n('updateText', version)}</li><ol class="update-text">${packageData.change?.map(change => `<li>${change}</li>`).join('')}<li>${i18n('updateHistory')}</li></ol>`
  11832. });
  11833. }
  11834. } catch (error) {
  11835. throwError(error, 'updateChecker');
  11836. }
  11837. };
  11838. const scripts_updateChecker = updateChecker;
  11839. window.STYLE = GM_addStyle(auto_task.A + GM_getResourceText('style'));
  11840. window.DEBUG = !!globalOptions.other?.debug;
  11841. window.TRACE = !!globalOptions.other?.debug && typeof console.trace === 'function';
  11842. const loadScript = async () => {
  11843. if (window.name === 'ATv4_twitchAuth' && window.location.hostname === 'www.twitch.tv') {
  11844. const authToken = external_Cookies_default().get('auth-token');
  11845. const isLogin = !!external_Cookies_default().get('login');
  11846. if (isLogin) {
  11847. GM_setValue('twitchAuth', {
  11848. authToken: authToken,
  11849. clientVersion: __twilightBuildID,
  11850. clientId: commonOptions?.headers?.['Client-ID'],
  11851. deviceId: commonOptions?.headers?.['Device-ID'],
  11852. clientSessionId: window.localStorage.local_storage_app_session_id.replace(/"/g, '')
  11853. });
  11854. window.close();
  11855. external_Swal_default().fire('', i18n('closePageNotice'));
  11856. } else {
  11857. external_Swal_default().fire('', i18n('needLogin'));
  11858. }
  11859. return;
  11860. }
  11861. if (window.name === 'ATv4_redditAuth' && window.location.hostname === 'www.reddit.com') {
  11862. const betaButton = $('#redesign-beta-optin-btn');
  11863. if (betaButton.length > 0) {
  11864. return betaButton[0].click();
  11865. }
  11866. window.close();
  11867. external_Swal_default().fire('', i18n('closePageNotice'));
  11868. return;
  11869. }
  11870. let website;
  11871. for (const Website of Websites) {
  11872. if (Website.test()) {
  11873. website = new Website();
  11874. break;
  11875. }
  11876. }
  11877. if (!website) {
  11878. console.log('%c%s', 'color:#ff0000', 'Auto-Task[Warning]: 脚本停止加载,当前网站不支持!');
  11879. return;
  11880. }
  11881. if (website?.before) {
  11882. await website?.before();
  11883. }
  11884. $('body').append(`
  11885. <div id="auto-task-info"
  11886. style="display:${globalOptions.other.defaultShowLog ? 'block' : 'none'};
  11887. ${globalOptions.position.logSideX}:${globalOptions.position.logDistance.split(',')[0]}px;
  11888. ${globalOptions.position.logSideY}:${globalOptions.position.logDistance.split(',')[1]}px;">
  11889. </div>
  11890. <div id="auto-task-buttons"
  11891. style="display:${globalOptions.other.defaultShowButton ? 'block' : 'none'};
  11892. ${globalOptions.position.buttonSideX}:${globalOptions.position.buttonDistance.split(',')[0]}px;
  11893. ${globalOptions.position.buttonSideY}:${globalOptions.position.buttonDistance.split(',')[1]}px;">
  11894. </div>
  11895. <div class="show-button-div"
  11896. style="display:${globalOptions.other.defaultShowButton ? 'none' : 'block'};
  11897. ${globalOptions.position.showButtonSideX}:${globalOptions.position.showButtonDistance.split(',')[0]}px;
  11898. ${globalOptions.position.showButtonSideY}:${globalOptions.position.showButtonDistance.split(',')[1]}px;">
  11899. <a class="auto-task-website-btn"
  11900. href="javascript:void(0);"
  11901. target="_self"
  11902. title="${i18n('showButton')}"> </a>
  11903. </div>
  11904. `);
  11905. $('div.show-button-div').on('click', () => {
  11906. $('#auto-task-buttons').show();
  11907. $('div.show-button-div').hide();
  11908. });
  11909. const toggleLog = () => {
  11910. const $this = $('#toggle-log');
  11911. const status = $this.attr('data-status');
  11912. if (status === 'show') {
  11913. $('#auto-task-info').hide();
  11914. $this.attr('data-status', 'hide').text(i18n('showLog'));
  11915. } else {
  11916. $('#auto-task-info').show();
  11917. $this.attr('data-status', 'show').text(i18n('hideLog'));
  11918. }
  11919. };
  11920. external_keyboardJS_default().bind(globalOptions.hotKey.doTaskKey, () => {
  11921. if (website.doTask) {
  11922. website.doTask();
  11923. }
  11924. });
  11925. external_keyboardJS_default().bind(globalOptions.hotKey.undoTaskKey, () => {
  11926. if (website.undoTask) {
  11927. website.undoTask();
  11928. }
  11929. });
  11930. external_keyboardJS_default().bind(globalOptions.hotKey.toggleLogKey, toggleLog);
  11931. if (website?.after) {
  11932. await website?.after();
  11933. }
  11934. if (website?.buttons && $('#auto-task-buttons').children().length === 0) {
  11935. $('#auto-task-buttons').addClass(`${website.name}-buttons`);
  11936. for (const button of website.buttons) {
  11937. if (website[button]) {
  11938. const btnElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">${i18n(button)}</a></p>`);
  11939. btnElement.find('a.auto-task-website-btn').on('click', () => {
  11940. website[button]();
  11941. });
  11942. $('#auto-task-buttons').append(btnElement);
  11943. }
  11944. }
  11945. }
  11946. const hideButtonElement = $(`<p><a class="auto-task-website-btn ${website.name}-button" href="javascript:void(0);" target="_self">
  11947. ${i18n('hideButton')}</a></p>`);
  11948. hideButtonElement.find('a.auto-task-website-btn').on('click', () => {
  11949. $('#auto-task-buttons').hide();
  11950. $('div.show-button-div').show();
  11951. });
  11952. 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'}">
  11953. ${globalOptions.other.defaultShowLog ? i18n('hideLog') : i18n('showLog')}</a></p>`);
  11954. toggleLogElement.find('a.auto-task-website-btn').on('click', toggleLog);
  11955. $('#auto-task-buttons').append(hideButtonElement).append(toggleLogElement);
  11956. if (website?.options) {
  11957. GM_registerMenuCommand(i18n('changeWebsiteOptions'), () => {
  11958. options(website.name, website.options);
  11959. });
  11960. }
  11961. if (website.name !== 'Setting') {
  11962. GM_registerMenuCommand(i18n('changeGlobalOptions'), () => {
  11963. changeGlobalOptions('swal');
  11964. });
  11965. GM_registerMenuCommand(i18n('settingPage'), () => {
  11966. GM_openInTab('https://auto-task-v4.hclonely.com/setting.html', {
  11967. active: true
  11968. });
  11969. });
  11970. }
  11971. console.log('%c%s', 'color:#1bbe1a', 'Auto-Task[Load]: 脚本加载完成');
  11972. const stopPlayTime = GM_getValue('stopPlayTime', 0) || 0;
  11973. const stopPlayTimeMinutes = Math.floor((Date.now() - stopPlayTime) / 6e4);
  11974. if (stopPlayTime > 0 && stopPlayTime < Date.now()) {
  11975. external_Swal_default().fire({
  11976. title: i18n('stopPlayTimeTitle'),
  11977. text: i18n('stopPlayTimeText', stopPlayTimeMinutes.toString()),
  11978. icon: 'warning',
  11979. confirmButtonText: i18n('confirm')
  11980. }).then(async () => {
  11981. const steamASF = new social_SteamASF();
  11982. if (await steamASF.init()) {
  11983. if (await steamASF.stopPlayGames()) {
  11984. GM_setValue('stopPlayTime', 0);
  11985. }
  11986. }
  11987. });
  11988. }
  11989. const [ v1, v2 ] = GM_info.version?.split('.') || [];
  11990. if (!(parseInt(v1, 10) >= 5 && parseInt(v2, 10) >= 2)) {
  11991. scripts_echoLog({}).error(i18n('versionNotMatched'));
  11992. }
  11993. if (!GM_getValue('notice')) {
  11994. external_Swal_default().fire({
  11995. title: i18n('swalNotice'),
  11996. icon: 'warning'
  11997. }).then(() => {
  11998. GM_openInTab(i18n('noticeLink'), {
  11999. active: true
  12000. });
  12001. GM_setValue('notice', new Date().getTime());
  12002. });
  12003. scripts_echoLog({
  12004. html: `<li><font class="warning">${i18n('echoNotice', i18n('noticeLink'))}</font></li>`
  12005. }).font?.find('a').on('click', () => {
  12006. GM_setValue('notice', new Date().getTime());
  12007. });
  12008. }
  12009. scripts_updateChecker();
  12010. };
  12011. if (window.location.hostname === 'discord.com') {
  12012. const LocalStorage = window.localStorage;
  12013. if (window.name === 'ATv4_discordAuth') {
  12014. window.localStorage.removeItem = () => true;
  12015. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  12016. if (discordAuth && discordAuth.length > 0) {
  12017. GM_setValue('discordAuth', {
  12018. auth: discordAuth
  12019. });
  12020. window.close();
  12021. external_Swal_default().fire('', i18n('closePageNotice'));
  12022. } else {
  12023. external_Swal_default().fire({
  12024. text: i18n('getDiscordAuthFailed'),
  12025. icon: 'error'
  12026. });
  12027. }
  12028. } else {
  12029. const discordAuth = LocalStorage?.getItem('token')?.replace(/^"|"$/g, '');
  12030. if (discordAuth && discordAuth.length > 0) {
  12031. GM_setValue('discordAuth', {
  12032. auth: discordAuth
  12033. });
  12034. }
  12035. }
  12036. } else if (window.location.hostname === 'opquests.com') {
  12037. loadScript();
  12038. } else if ((window.name === 'ATv4_updateStoreAuth' || GM_getValue('ATv4_updateStoreAuth')) && window.location.host === 'store.steampowered.com') {
  12039. $(() => {
  12040. if ($('[data-miniprofile]').length === 0) {
  12041. return;
  12042. }
  12043. const storeSessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  12044. if (storeSessionID) {
  12045. GM_deleteValue('ATv4_updateStoreAuth');
  12046. GM_setValue('steamStoreAuth', {
  12047. storeSessionID: storeSessionID
  12048. });
  12049. window.close();
  12050. external_Swal_default().fire('', i18n('closePageNotice'));
  12051. } else {
  12052. external_Swal_default().fire({
  12053. title: 'Error: Get "sessionID" failed',
  12054. icon: 'error'
  12055. });
  12056. }
  12057. });
  12058. } else if ((window.name === 'ATv4_updateCommunityAuth' || GM_getValue('ATv4_updateCommunityAuth')) && window.location.host === 'steamcommunity.com') {
  12059. $(() => {
  12060. const steam64Id = document.body.innerHTML.match(/g_steamID = "(.+?)";/)?.[1];
  12061. const communitySessionID = document.body.innerHTML.match(/g_sessionID = "(.+?)";/)?.[1];
  12062. if (steam64Id && communitySessionID) {
  12063. GM_deleteValue('ATv4_updateCommunityAuth');
  12064. GM_setValue('steamCommunityAuth', {
  12065. steam64Id: steam64Id,
  12066. communitySessionID: communitySessionID
  12067. });
  12068. window.close();
  12069. external_Swal_default().fire('', i18n('closePageNotice'));
  12070. } else {
  12071. setTimeout(() => {
  12072. external_Swal_default().fire({
  12073. title: 'Error: Get "sessionID" failed',
  12074. icon: 'error'
  12075. });
  12076. }, 3e3);
  12077. }
  12078. });
  12079. } else {
  12080. if (window.location.hostname === 'key-hub.eu') {
  12081. unsafeWindow.keyhubtracker = 1;
  12082. unsafeWindow.gaData = {};
  12083. }
  12084. $(loadScript);
  12085. }
  12086. }();
  12087. })();