-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathmega.ts
More file actions
292 lines (253 loc) · 7.85 KB
/
Copy pathmega.ts
File metadata and controls
292 lines (253 loc) · 7.85 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
import { Mutex } from "async-mutex";
import * as Mega from "megajs";
import { Config, MegaAccount, UploadMode, UploadQuery } from "./types";
import database from "./database";
import { Readable } from "stream";
function streamToBuffer(stream: NodeJS.ReadableStream): Promise<Buffer> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
stream.on("data", (chunk) => chunks.push(chunk));
stream.on("end", () => resolve(Buffer.concat(chunks)));
stream.on("error", (err) => {
console.error("Error stream:", err);
reject(err);
});
});
}
async function fullUpload(uploadStream: any): Promise<any> {
return new Promise((resolve, reject) => {
// Timeout for lag uploads
const timeout = setTimeout(
() => {
reject(new Error("Upload timeout after 5 mins"));
},
5 * 60 * 1000,
);
uploadStream.on("complete", (file: any) => {
clearTimeout(timeout);
file.link((err: any, url: string) => {
if (err) {
console.error("Error linking file:", err);
return reject(err);
}
resolve({ name: file.name, size: file.size, mime: file.mime, url });
});
});
uploadStream.on("error", (err: any) => {
clearTimeout(timeout);
console.error("Could not upload media:", err);
reject(err);
});
});
}
class MegaClient {
private accounts: MegaAccount[] = [];
private currentAccountIndex = 0;
private config: Config;
private accountMutexes: Map<string, Mutex> = new Map();
constructor(config: Config) {
this.config = config;
}
async initialize() {
if (this.config.FILENAMES || this.config.autoDelete?.enable) {
await database.initialize(this.config.DATABASE_URL);
}
const creds = this.config.mega.accounts;
if (!creds) throw new Error("No MEGA accounts found");
for (const entry of creds.split(";")) {
const [email, password] = entry.split(":");
if (email && password) {
try {
const storage = new (Mega as any).Storage({ email, password });
await storage.ready;
this.accounts.push({
email,
password,
storage,
});
this.accountMutexes.set(email, new Mutex());
console.log(`Logged into: ${email}`);
} catch (err) {
console.error(`Login failed: ${email}`, err);
}
}
}
if (!this.accounts.length) throw new Error("No valid MEGA accounts");
}
private selectAccount(mode: UploadMode, query?: UploadQuery): MegaAccount {
if (mode === "dual" && query?.email) {
const account = this.accounts.find((a) => a.email === query.email);
if (!account) throw new Error(`No account for ${query.email}`);
return account;
}
const account = this.accounts[this.currentAccountIndex];
this.currentAccountIndex =
(this.currentAccountIndex + 1) % this.accounts.length;
return account;
}
getAccountByEmail(email: string): MegaAccount | null {
return this.accounts.find((acc) => acc.email === email) || null;
}
getZeroAcc(): MegaAccount {
if (!this.accounts.length) throw new Error("No accounts available");
return this.accounts[0];
}
async uploadFile(
filename: string,
input: NodeJS.ReadableStream,
mode: UploadMode = "single",
query?: UploadQuery,
) {
const account = this.selectAccount(mode, query);
if (!account || !account.storage) {
throw new Error(
"Storage not available for this account - payment required or banned",
);
}
const mutex = this.accountMutexes.get(account.email);
if (!mutex) throw new Error("Account mutex not found");
const release = await mutex.acquire();
try {
const buffer = await streamToBuffer(input);
const size = buffer.length;
if (size === 0) {
throw new Error("File is empty");
}
const uploadStream = account.storage.upload({
name: filename,
size: size,
allowUploadBuffering: true,
});
Readable.from(buffer).pipe(uploadStream);
const result = await fullUpload(uploadStream);
return result;
} catch (error) {
throw new Error(
"Upload failed: " +
(error instanceof Error ? error.message : "Unknown error"),
);
} finally {
release();
}
}
async uploadBuffer(
filename: string,
buffer: Buffer,
mode: UploadMode = "single",
query?: UploadQuery,
) {
if (!buffer || buffer.length === 0) {
throw new Error("Buffer is empty or null");
}
return this.uploadFile(filename, Readable.from(buffer), mode, query);
}
async getFile(filePath: string) {
const primary = this.getZeroAcc();
const fileName = filePath.split("/").pop() || filePath;
const file = Object.values(primary.storage.files).find(
(f: any) => f.name === fileName,
);
if (!file) throw new Error("File not found");
return file;
}
async scheduleDelete(name: string, mins: number) {
const deleteTime = Date.now() + mins * 60_000;
await database.save({ fileName: name, deleteTime });
}
async processExpired() {
const now = Date.now();
const expired = await database.findExpired(now);
for (const record of expired) {
let fileDeleted = false;
for (const account of this.accounts) {
try {
const files = account.storage.root.children;
const file = files.find((x: any) => x.name === record.fileName);
if (file) {
await file.delete();
console.log(`Deleted: ${record.fileName} from ${account.email}`);
fileDeleted = true;
break;
}
} catch (error) {
console.error(
`Failed to delete ${record.fileName} from ${account.email}:`,
error,
);
}
}
if (!fileDeleted) {
console.warn(`Could not find file ${record.fileName} in any account`);
}
await database.delete(record.fileName);
}
if (expired.length) {
console.log(`Cleaned up ${expired.length} expired files`);
}
}
async cleanup() {
try {
if (this.config.autoDelete?.enable) {
await this.processExpired();
}
await database.disconnect();
console.log("Cleanup completed");
} catch (error) {
console.error("Cleanup failed:", error);
}
}
getAccountCount(): number {
return this.accounts.length;
}
getAccountEmails(): string[] {
return this.accounts.map((acc) => acc.email);
}
public getAccounts(): MegaAccount[] {
return this.accounts;
}
public async deleteFileByName(fileName: string): Promise<boolean> {
for (const account of this.accounts) {
try {
await account.storage.reload();
const file = account.storage.find(fileName);
if (file && !file.directory) {
await file.delete(true);
return true;
}
} catch (error) {
console.error(
`Failed to delete ${fileName} from ${account.email}:`,
error,
);
}
}
return false;
}
public async getFileNameFromUrl(url: string): Promise<string> {
const file = Mega.File.fromURL(url);
await file.loadAttributes();
return file.name || "unknown";
}
async getStorageInfo(): Promise<any[]> {
const info = [];
for (const account of this.accounts) {
try {
const accountInfo = await account.storage.getAccountInfo();
info.push({
email: account.email,
used: accountInfo.used || 0,
total: accountInfo.total || 0,
available: (accountInfo.total || 0) - (accountInfo.used || 0),
});
} catch (error) {
console.error(`Failed to get acc info for ${account.email}:`, error);
info.push({
email: account.email,
error: "Failed to get acc info",
});
}
}
return info;
}
}
export default MegaClient;