-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnative.ts
More file actions
329 lines (280 loc) · 13.8 KB
/
native.ts
File metadata and controls
329 lines (280 loc) · 13.8 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
/*
* Vencord, a Discord client mod
* Copyright (c) 2024 Vendicated and contributors
* SPDX-License-Identifier: GPL-3.0-or-later
*/
import { exec } from "child_process";
import { unzip } from "fflate";
import { constants } from "fs";
import { access, mkdir, readdir, readFile, rm, unlink, writeFile } from "fs/promises";
import os from "os";
import { dirname, join } from "path";
import { PluginInfo } from "./types";
const pluginsDir = join(__dirname, "../src/userplugins");
const userDirectory = join(os.homedir(), "Vencord");
async function ensureDirectoryExists(dir: string) {
try {
await mkdir(dir, { recursive: true });
console.log("Directory created:", dir);
} catch (error) {
console.error("Error creating directory:", error);
throw new Error(`Failed to create directory ${dir}: ${error}`);
}
}
async function getInstalledPlugins(): Promise<string[]> {
try {
const files = await readdir(pluginsDir);
console.log("Installed plugins:", files);
return files;
} catch (error) {
console.error("Error retrieving installed plugins:", error);
throw new Error("Failed to retrieve installed plugins.");
}
}
const runShellCommand = (command, cwd) => {
return new Promise((resolve, reject) => {
exec(command, { cwd }, (error, stdout, stderr) => {
if (error) {
console.error(`Error executing command: ${error}`);
return reject(stderr);
}
console.log(stdout);
resolve(stdout);
});
});
};
async function installPlugin(_: any, plugin: PluginInfo): Promise<void> {
if (!plugin.downloadUrl) {
throw new Error(`Download URL is undefined for plugin ${plugin.name}`);
}
const filePath = join(pluginsDir, (plugin.filename || "default") + ".zip");
try {
const response = await fetch(plugin.downloadUrl);
if (!response.ok) throw new Error(`Failed to fetch ${plugin.downloadUrl}: ${response.statusText}`);
const zipData = new Uint8Array(await response.arrayBuffer());
await writeFile(filePath, zipData);
const zipBuffer = await readFile(filePath);
await extract(zipBuffer, pluginsDir, plugin);
console.log(`Plugin ${plugin.name} extracted successfully.`);
await runShellCommand("pnpm build", userDirectory);
console.log(`Build completed successfully in ${userDirectory}.`);
await runShellCommand("pnpm inject", userDirectory);
console.log(`Injection completed successfully in ${userDirectory}.`);
} catch (error) {
console.error(`Error installing ${plugin.name} plugin:`, error);
}
}
async function extract(data: Buffer, pluginsDir: string, plugin: PluginInfo): Promise<void> {
await ensureDirectoryExists(pluginsDir);
const zipFilePath = join(pluginsDir, (plugin.filename || "default") + ".zip");
const baseDir = plugin.filename && !plugin.filename.includes(".") ? join(pluginsDir, plugin.filename) : pluginsDir;
return new Promise<void>((resolve, reject) => {
// Convert Buffer to Uint8Array using Uint8Array.from()
const uint8Array = Uint8Array.from(data);
unzip(uint8Array, async (err, files) => {
if (err) return void reject(err);
try {
if (plugin.downloadFiles) {
// Get the actual root directory from the ZIP
const firstLevelDirs = new Set<string>();
Object.keys(files).forEach(filePath => {
const parts = filePath.split("/");
if (parts.length > 1) {
firstLevelDirs.add(parts[0]);
}
});
const rootDirName = firstLevelDirs.size === 1 ? Array.from(firstLevelDirs)[0] : "";
// Check if this is a multi-file plugin with a common prefix
const paths = plugin.downloadFiles.map(f => f.split("/"));
const commonPrefix: string[] = [];
if (paths.length > 0 && paths[0].length > 1) {
// Only look for common prefix if at least one path has multiple segments
const firstPath = paths[0];
for (let i = 0; i < firstPath.length - 1; i++) {
const segment = firstPath[i];
if (paths.every(path => path[i] === segment)) {
commonPrefix.push(segment);
} else {
break;
}
}
}
const commonPrefixStr = commonPrefix.join("/");
// Find matching files in the ZIP
const filesToMove = Object.keys(files).filter(filePath => {
if (commonPrefixStr) {
// Multi-file case with common prefix
const zipPath = `${rootDirName}/${commonPrefixStr}`;
return plugin.downloadFiles!.some(pattern => {
const targetPath = pattern.substring(commonPrefixStr.length + 1);
return filePath.startsWith(`${zipPath}/${targetPath}`);
});
} else {
// Multi-file or single file case without prefix
return plugin.downloadFiles!.some(pattern => {
// Check if the file matches exactly or is inside a requested directory
const inRequestedDir = plugin.downloadFiles!.some(dir => {
// If dir doesn't have an extension, treat it as a directory
if (!dir.includes(".")) {
return filePath === `${rootDirName}/${dir}` ||
filePath.startsWith(`${rootDirName}/${dir}/`);
}
return false;
});
// Check for exact file matches
const exactMatch = filePath === pattern ||
filePath === `${rootDirName}/${pattern}` ||
filePath.endsWith(`/${pattern}`);
return exactMatch || inRequestedDir;
});
}
});
// Create plugin directory if needed
if (plugin.filename && !plugin.filename.includes(".")) {
await mkdir(baseDir, { recursive: true });
}
// Move files while maintaining the desired structure
await Promise.all(
filesToMove.map(async filePath => {
let relativePath;
if (commonPrefixStr) {
// Multi-file case: remove root dir and common prefix
relativePath = filePath
.replace(`${rootDirName}/`, "")
.replace(`${commonPrefixStr}/`, "");
} else {
// For files in directories or root files
relativePath = filePath.replace(`${rootDirName}/`, "");
}
const destPath = join(baseDir, relativePath);
await mkdir(dirname(destPath), { recursive: true });
// Proper directory detection
// A directory in ZIP files typically ends with "/" and has no content
const isDirectory = filePath.endsWith("/") || files[filePath].length === 0;
if (isDirectory && !destPath.endsWith("/")) {
// This is a directory entry, ensure it exists
await mkdir(destPath, { recursive: true });
} else if (!isDirectory) {
// This is a file, write its content
await writeFile(destPath, files[filePath]);
}
})
);
// Cleanup: remove the root directory if it exists
if (rootDirName) {
const rootPath = join(pluginsDir, rootDirName);
await rm(rootPath, { recursive: true, force: true });
}
} else {
// Default behavior for when no specific files are requested
// Sort files so directories come before their contents
const sortedFiles = Object.keys(files).sort();
await Promise.all(
sortedFiles.map(async filePath => {
const fullPath = join(baseDir, filePath);
await mkdir(dirname(fullPath), { recursive: true });
// Proper directory detection
const isDirectory = filePath.endsWith("/") || files[filePath].length === 0;
if (isDirectory && !fullPath.endsWith("/")) {
// This is a directory entry, ensure it exists
await mkdir(fullPath, { recursive: true });
} else if (!isDirectory) {
// This is a file, write its content
await writeFile(fullPath, files[filePath]);
}
})
);
}
// Delete the original ZIP file
await rm(zipFilePath, { force: true });
resolve();
} catch (err) {
console.error(`Error moving or renaming files: ${err}`);
reject(err);
}
});
});
}
async function moveFilesToRoot(srcDir: string, destDir: string) {
const entries = await readdir(srcDir, { withFileTypes: true });
for (const entry of entries) {
const srcPath = join(srcDir, entry.name);
const destPath = join(destDir, entry.name);
if (entry.isDirectory()) {
await moveFilesToRoot(srcPath, destPath);
await rm(srcPath, { recursive: true });
} else {
await mkdir(dirname(destPath), { recursive: true });
const fileContent = await readFile(srcPath);
await writeFile(destPath, new Uint8Array(fileContent));
await unlink(srcPath);
}
}
}
async function uninstallPlugin(_, plugin: PluginInfo): Promise<void> {
try {
if (plugin.downloadFiles && plugin.downloadFiles.length > 0) {
const parentDirs = new Set<string>();
for (const originalFileName of plugin.downloadFiles) {
const renamedFileName = plugin.filename || originalFileName;
const fullPath = join(pluginsDir, renamedFileName);
await rm(fullPath, { recursive: true, force: true });
parentDirs.add(dirname(fullPath));
}
for (const dir of parentDirs) {
if ((await readdir(dir)).length === 0) {
await rm(dir, { recursive: true, force: true });
}
}
} else if (plugin.filename) {
const fullPath = join(pluginsDir, plugin.filename);
await rm(fullPath, { recursive: true, force: true });
}
console.log(`Plugin ${plugin.name} has been successfully uninstalled.`);
} catch (error) {
console.error(`Error uninstalling plugin ${plugin.name}:`, error);
throw new Error(`Uninstallation failed for ${plugin.name}: ${error}`);
}
}
async function updatePluginRepo() {
const pluginInfo: PluginInfo = {
name: "Plugins Repo",
filename: "PluginsRepo",
filesearch: "PluginsRepo",
downloadUrl: "https://github.com/ScattrdBlade/PluginsRepo/archive/refs/heads/main.zip",
description: "Updates the Plugin Repo with the latest files.",
tags: ["management"],
dateAdded: new Date().toISOString(),
};
const pluginDir = join(pluginsDir, pluginInfo.filename);
if (await checkExists(pluginDir)) {
await rm(pluginDir, { recursive: true });
console.log("Existing Plugin Repo removed.");
}
try {
const response = await fetch(pluginInfo.downloadUrl);
if (!response.ok) throw new Error(`Failed to fetch ${pluginInfo.downloadUrl}: ${response.statusText}`);
const zipDataArray = new Uint8Array(await response.arrayBuffer());
const zipFilePath = join(pluginsDir, pluginInfo.filename + ".zip");
await writeFile(zipFilePath, zipDataArray);
console.log("Plugin zip file downloaded.");
const zipBuffer = Buffer.from(zipDataArray);
await extract(zipBuffer, pluginsDir, pluginInfo);
console.log("Plugin extracted successfully.");
await runShellCommand("pnpm build", pluginDir);
console.log("Plugin build completed.");
await runShellCommand("pnpm inject", pluginDir);
console.log("Plugin injection completed.");
} catch (error) {
console.error("Error updating Plugin Repo:", error);
}
}
async function checkExists(path: string): Promise<boolean> {
try {
await access(path, constants.F_OK);
return true;
} catch {
return false;
}
}
export { getInstalledPlugins, installPlugin, uninstallPlugin, updatePluginRepo };