-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.tsx
More file actions
356 lines (302 loc) · 13 KB
/
Copy pathindex.tsx
File metadata and controls
356 lines (302 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import { ApplicationCommandInputType, sendBotMessage } from "@api/Commands";
import definePlugin from "@utils/types";
import { findStore, findByProps } from "@webpack";
import { FluxDispatcher, RunningGameStore, Toasts, showToast } from "@webpack/common";
const supportedTasks = ["WATCH_VIDEO", "PLAY_ON_DESKTOP", "STREAM_ON_DESKTOP", "PLAY_ACTIVITY", "WATCH_VIDEO_ON_MOBILE"];
let isRunning = false;
function sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Stores are fetched lazily
let QuestsStore: any;
let ApplicationStreamingStore: any;
let AuthStore: any;
function loadStores() {
if (QuestsStore && ApplicationStreamingStore && AuthStore) return true;
try {
QuestsStore = findByProps("getQuest", "quests") || findByProps("getQuest") || findStore("QuestsStore");
ApplicationStreamingStore = findByProps("getStreamerActiveStreamMetadata") || findStore("ApplicationStreamingStore");
AuthStore = findByProps("getToken");
return !!(QuestsStore && ApplicationStreamingStore && AuthStore);
} catch (e) {
console.error("[QuestHelper] Error loading stores:", e);
return false;
}
}
async function apiCall(method: string, endpoint: string, body?: any) {
const token = AuthStore.getToken();
const url = `https://discord.com/api/v9${endpoint}`;
const options: RequestInit = {
method: method,
headers: {
"Authorization": token,
"Content-Type": "application/json",
},
};
if (body) {
options.body = JSON.stringify(body);
}
const res = await fetch(url, options);
if (!res.ok) {
throw new Error(`API Error ${res.status}: ${res.statusText}`);
}
// safe parsing
const text = await res.text();
try {
return JSON.parse(text);
} catch {
return text;
}
}
async function completeVideoQuest(quest: any, taskName: string, secondsNeeded: number, secondsDone: number) {
const maxFuture = 10, speed = 7, interval = 1;
const enrolledAt = new Date(quest.userStatus.enrolledAt).getTime();
console.log(`[QuestHelper] Video progress: ${secondsDone}/${secondsNeeded}`);
while (secondsDone < secondsNeeded) {
if (!isRunning) return;
const maxAllowed = Math.floor((Date.now() - enrolledAt) / 1000) + maxFuture;
const diff = maxAllowed - secondsDone;
const timestamp = secondsDone + speed;
if (diff >= speed) {
try {
const res = await apiCall("POST", `/quests/${quest.id}/video-progress`, {
timestamp: Math.min(secondsNeeded, timestamp + Math.random())
});
if (res && res.completed_at != null) {
console.log(`[QuestHelper] Video quest completed via API Response.`);
return;
}
} catch (e) {
console.error("[QuestHelper] API Error", e);
}
secondsDone = Math.min(secondsNeeded, timestamp);
console.log(`[QuestHelper] Video progress updated: ${secondsDone}/${secondsNeeded}`);
}
await sleep(interval * 1000);
}
try {
if (isRunning) {
await apiCall("POST", `/quests/${quest.id}/video-progress`, { timestamp: secondsNeeded });
}
} catch (e) { }
}
async function completePlayDesktopQuest(quest: any, applicationId: string, applicationName: string, secondsNeeded: number) {
return new Promise<void>(async (resolve) => {
let appData;
try {
const res = await apiCall("GET", `/applications/public?application_ids=${applicationId}`);
if (Array.isArray(res) && res.length > 0) {
appData = res[0];
}
} catch (e) {
console.error("[QuestHelper] Failed to fetch app data", e);
}
if (!appData) {
console.log(`[QuestHelper] Could not retrieve metadata for ${applicationName}. Using fallback.`);
appData = { name: applicationName, executables: [{ os: "win32", name: "game.exe" }] };
}
const exeName = appData.executables.find((x: any) => x.os === "win32")?.name.replace(">", "") || "game.exe";
const pid = Math.floor(Math.random() * 30000) + 1000;
console.log(`[QuestHelper] Mocking game: ${appData.name} (PID: ${pid})`);
const fakeGame = {
cmdLine: `C:\\Program Files\\${appData.name}\\${exeName}`,
exeName,
exePath: `c:/program files/${appData.name.toLowerCase()}/${exeName}`,
hidden: false,
isLauncher: false,
id: applicationId,
name: appData.name,
pid: pid,
pidPath: [pid],
processName: appData.name,
start: Date.now(),
};
const realGetRunningGames = RunningGameStore.getRunningGames;
const realGetGameForPID = RunningGameStore.getGameForPID;
const realGames = RunningGameStore.getRunningGames();
const fakeGames = [fakeGame];
// @ts-ignore
RunningGameStore.getRunningGames = () => fakeGames;
// @ts-ignore
RunningGameStore.getGameForPID = (pid) => fakeGames.find(x => x.pid === pid);
FluxDispatcher.dispatch({ type: "RUNNING_GAMES_CHANGE", removed: realGames, added: [fakeGame], games: fakeGames });
const cleanup = () => {
// @ts-ignore
RunningGameStore.getRunningGames = realGetRunningGames;
// @ts-ignore
RunningGameStore.getGameForPID = realGetGameForPID;
FluxDispatcher.dispatch({ type: "RUNNING_GAMES_CHANGE", removed: [fakeGame], added: [], games: [] });
FluxDispatcher.unsubscribe("QUESTS_SEND_HEARTBEAT_SUCCESS", onHeartbeat);
console.log(`[QuestHelper] Stopped mocking ${applicationName}`);
};
const onHeartbeat = (data: any) => {
if (!isRunning) {
cleanup();
resolve();
return;
}
const userStatus = data.userStatus;
let progress = 0;
if (quest.config.configVersion === 1) {
progress = userStatus?.streamProgressSeconds ?? 0;
} else {
progress = Math.floor(userStatus?.progress?.PLAY_ON_DESKTOP?.value ?? 0);
}
console.log(`[QuestHelper] Heartbeat: ${progress}/${secondsNeeded}s`);
if (progress >= secondsNeeded) {
cleanup();
resolve();
}
};
FluxDispatcher.subscribe("QUESTS_SEND_HEARTBEAT_SUCCESS", onHeartbeat);
console.log(`[QuestHelper] Listening for heartbeats...`);
});
}
async function completeStreamDesktopQuest(quest: any, applicationId: string, secondsNeeded: number) {
return new Promise<void>((resolve) => {
const pid = Math.floor(Math.random() * 30000) + 1000;
let realFunc = ApplicationStreamingStore.getStreamerActiveStreamMetadata;
ApplicationStreamingStore.getStreamerActiveStreamMetadata = () => ({
id: applicationId,
pid,
sourceName: null
});
const cleanup = () => {
ApplicationStreamingStore.getStreamerActiveStreamMetadata = realFunc;
FluxDispatcher.unsubscribe("QUESTS_SEND_HEARTBEAT_SUCCESS", onHeartbeat);
};
const onHeartbeat = (data: any) => {
if (!isRunning) {
cleanup();
resolve();
return;
}
const userStatus = data.userStatus;
let progress = 0;
if (quest.config.configVersion === 1) {
progress = userStatus?.streamProgressSeconds ?? 0;
} else {
progress = Math.floor(userStatus?.progress?.STREAM_ON_DESKTOP?.value ?? 0);
}
if (progress >= secondsNeeded) {
cleanup();
resolve();
}
};
FluxDispatcher.subscribe("QUESTS_SEND_HEARTBEAT_SUCCESS", onHeartbeat);
});
}
async function runQuests(ctx: any) {
if (isRunning) {
showToast("QuestHelper is already running.", Toasts.Type.MESSAGE);
return;
}
isRunning = true;
if (!loadStores()) {
const missing = [];
if (!QuestsStore) missing.push("QuestsStore");
if (!ApplicationStreamingStore) missing.push("ApplicationStreamingStore");
if (!AuthStore) missing.push("AuthStore");
console.error("[QuestHelper] Failed to load stores:", missing);
showToast(`QuestHelper Error: Missing stores: ${missing.join(", ")}`, Toasts.Type.FAILURE);
isRunning = false;
return;
}
if (!QuestsStore.quests) {
console.error("[QuestHelper] QuestsStore found but .quests property is missing!", QuestsStore);
showToast("QuestHelper Error: Invalid QuestsStore", Toasts.Type.FAILURE);
isRunning = false;
return;
}
const quests = [...QuestsStore.quests.values()].filter((x: any) =>
x.userStatus?.enrolledAt &&
!x.userStatus?.completedAt &&
new Date(x.config.expiresAt).getTime() > Date.now() &&
supportedTasks.find(y => Object.keys((x.config.taskConfig ?? x.config.taskConfigV2).tasks).includes(y))
);
if (quests.length === 0) {
showToast("No eligible uncompleted quests found.", Toasts.Type.MESSAGE);
isRunning = false;
return;
}
sendBotMessage(ctx.channel.id, { content: `Found ${quests.length} quest(s). Execution started...` });
showToast(`Starting ${quests.length} quest(s)...`, Toasts.Type.MESSAGE);
for (const quest of quests) {
if (!isRunning) break;
const applicationId = quest.config.application.id;
const applicationName = quest.config.application.name;
const taskConfig = quest.config.taskConfig ?? quest.config.taskConfigV2;
const taskName = supportedTasks.find(x => taskConfig.tasks[x] != null) as string;
const secondsNeeded = taskConfig.tasks[taskName].target;
let secondsDone = quest.userStatus?.progress?.[taskName]?.value ?? 0;
console.log(`[QuestHelper] Starting ${quest.config.messages.questName} (${taskName})`);
// Show updated toast message for starting quest
showToast(`Starting Quest: ${quest.config.messages.questName}`, Toasts.Type.MESSAGE);
try {
if (taskName === "WATCH_VIDEO" || taskName === "WATCH_VIDEO_ON_MOBILE") {
await completeVideoQuest(quest, taskName, secondsNeeded, secondsDone);
} else if (taskName === "PLAY_ON_DESKTOP") {
await completePlayDesktopQuest(quest, applicationId, applicationName, secondsNeeded);
} else if (taskName === "STREAM_ON_DESKTOP") {
await completeStreamDesktopQuest(quest, applicationId, secondsNeeded);
} else {
console.log(`Skipping quest ${quest.config.messages.questName} - Type ${taskName} not fully implemented in plugin yet.`);
}
} catch (err) {
console.error(err);
showToast(`Quest Failed: ${quest.config.messages.questName}`, Toasts.Type.FAILURE);
}
await sleep(2000);
}
if (isRunning) {
showToast("All quests finished!", Toasts.Type.SUCCESS);
sendBotMessage(ctx.channel.id, { content: "All quests finished!" });
} else {
showToast("Quest execution stopped.", Toasts.Type.MESSAGE);
}
isRunning = false;
}
export default definePlugin({
name: "DiscordQuestHelper",
description: "Automates Discord quests sequentially",
authors: [{ name: "@DMR3-CODE", id: 0n }],
commands: [
{
name: "quests",
description: "Manage Discord Quests",
inputType: ApplicationCommandInputType.BUILT_IN,
options: [
{
name: "start",
description: "Start auto-completing quests",
type: 1, // SUB_COMMAND
options: []
},
{
name: "stop",
description: "Stop Quest Helper",
type: 1, // SUB_COMMAND
options: []
}
],
execute: async (args, ctx) => {
if (args[0].name === "start") {
runQuests(ctx).catch(err => {
console.error("[QuestHelper] Fatal", err);
showToast("Fatal error in QuestHelper", Toasts.Type.FAILURE);
isRunning = false;
});
return { content: "Quest Helper started..." };
} else if (args[0].name === "stop") {
if (isRunning) {
isRunning = false;
return { content: "Stopping Quest Helper..." };
} else {
return { content: "Quest Helper is not running." };
}
}
return { content: "Invalid subcommand" };
}
}
]
});