-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathmega-provider.ts
More file actions
1369 lines (1212 loc) · 45.5 KB
/
Copy pathmega-provider.ts
File metadata and controls
1369 lines (1212 loc) · 45.5 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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { browser } from '$app/environment';
import type {
SyncProvider,
ProviderCredentials,
ProviderStatus,
CloudFileMetadata,
StorageQuota,
UploadPayload
} from '../../provider-interface';
import { ProviderError } from '../../provider-interface';
import { megaCache } from './mega-cache';
import { cacheManager } from '../../cache-manager';
import { setActiveProviderKey, clearActiveProviderKey } from '../../provider-detection';
import type { FolderOperations, FolderInfo, FolderItem } from '../../folder-deduplicator';
import {
isMfaRequiredError,
isSessionExpiredError,
isAuthRejectionError,
sanitizeSessionBlob,
encodeMegaKey,
type MegaSessionBlob
} from './mega-session';
interface MegaCredentials {
email: string;
password: string;
/** One-time TOTP code for 2FA-enabled accounts. Never persisted. */
secondFactorCode?: string;
}
const STORAGE_KEYS = {
/** Sanitized Storage.toJSON() blob (sid + master key). The only persisted secret. */
SESSION: 'mega_session',
// Legacy keys — read for migration, removed on first successful login.
EMAIL: 'mega_email',
PASSWORD: 'mega_password',
FOLDER_PATH: 'mega_folder_path'
};
const MOKURO_FOLDER = 'mokuro-reader';
const VOLUME_DATA_FILE = 'volume-data.json';
const PROFILES_FILE = 'profiles.json';
function getUploadPayloadSize(payload: UploadPayload): number {
if (payload instanceof Blob) return payload.size;
if (payload instanceof ArrayBuffer) return payload.byteLength;
return payload.byteLength;
}
/**
* Exponential backoff with jitter for retrying MEGA API calls
*/
async function retryWithBackoff<T>(
operation: () => Promise<T>,
maxRetries: number = 8,
baseDelay: number = 500,
operationName: string = 'operation'
): Promise<T> {
let lastError: Error | null = null;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
lastError = error as Error;
// Check if error is retryable (EAGAIN, rate limit, temporary congestion)
const errorMessage = error instanceof Error ? error.message : String(error);
const isRetryable =
errorMessage.includes('EAGAIN') ||
errorMessage.includes('congestion') ||
errorMessage.includes('rate') ||
errorMessage.includes('429');
if (!isRetryable || attempt === maxRetries) {
// Non-retryable error or max retries reached
throw error;
}
// Calculate exponential backoff with jitter
// Formula: delay = baseDelay * 2^attempt + random(0, 1000)
const exponentialDelay = baseDelay * Math.pow(2, attempt);
const jitter = Math.random() * 1000;
const delay = exponentialDelay + jitter;
console.warn(
`${operationName} failed (attempt ${attempt + 1}/${maxRetries + 1}): ${errorMessage}. Retrying in ${Math.round(delay)}ms...`
);
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
throw lastError;
}
/**
* Smart retry wrapper for MEGA operations that may fail due to stale cache
* When two devices sync back and forth, file IDs change but local cache is stale
* This wrapper detects ENOENT errors, refreshes the cache, and retries once
*/
async function retryWithCacheRefresh<T>(
operation: () => Promise<T>,
operationName: string = 'operation',
forceReload?: () => Promise<void>
): Promise<T> {
try {
return await operation();
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
// Check if error is ENOENT (file/object not found)
const isStaleCache =
errorMessage.includes('ENOENT') ||
errorMessage.includes('not found') ||
errorMessage.includes('Object');
if (isStaleCache) {
console.warn(
`${operationName} failed with ENOENT - cache may be stale. Waiting for MEGA to sync and retrying...`
);
// Give MEGA time to propagate server changes to storage.files
// MEGA.js updates storage.files via events, but server changes take time
await new Promise((resolve) => setTimeout(resolve, 2000));
// Force reload of MEGA's storage.files if provided
if (forceReload) {
await forceReload();
}
// Refresh our app's cloud cache from MEGA's now-fresh storage.files
// Skip reinitialize since forceReload already did that
await megaCache.fetch(true);
// Retry the operation once with fresh cache
try {
return await operation();
} catch (retryError) {
console.error(`${operationName} failed again after cache refresh:`, retryError);
throw retryError;
}
}
// Non-stale-cache error, throw immediately
throw error;
}
}
export class MegaProvider implements SyncProvider {
readonly type = 'mega' as const;
readonly name = 'MEGA';
readonly supportsWorkerDownload = true; // Workers download owned nodes via sid + per-file key
readonly uploadConcurrencyLimit = 6;
readonly downloadConcurrencyLimit = 6;
private storage: any = null;
private mokuroFolder: any = null;
private needsReconnect = false;
private reconnectEmail: string | null = null;
private initPromise: Promise<void>;
// Mutexes preventing concurrent uploads from racing to create the same folder.
// Without these, N parallel uploads each find no folder and call mkdir N times.
private mokuroFolderPromise: Promise<any> | null = null;
private seriesFolderPromises = new Map<string, Promise<any>>();
constructor() {
if (browser) {
this.initPromise = this.restorePersistedSession();
} else {
this.initPromise = Promise.resolve();
}
}
/**
* Wait for provider initialization to complete
* Use this to ensure credentials have been restored before checking authentication
*/
async whenReady(): Promise<void> {
await this.initPromise;
}
isAuthenticated(): boolean {
return this.storage !== null;
}
getStatus(): ProviderStatus {
const hasSession = !!(browser && localStorage.getItem(STORAGE_KEYS.SESSION));
const hasLegacy = !!(
browser &&
localStorage.getItem(STORAGE_KEYS.EMAIL) &&
localStorage.getItem(STORAGE_KEYS.PASSWORD)
);
const isConnected = this.isAuthenticated();
return {
isAuthenticated: isConnected,
hasStoredCredentials: hasSession || hasLegacy,
needsAttention: this.needsReconnect,
statusMessage: isConnected
? 'Connected to MEGA'
: this.needsReconnect
? 'MEGA session expired — please reconnect'
: hasSession || hasLegacy
? 'Configured (not connected)'
: 'Not configured'
};
}
/** Drop the stored session and flag the UI to prompt for reconnect (password never stored). */
private markSessionExpired(): void {
// Capture email for reconnect pre-fill before clearing.
if (browser && !this.reconnectEmail) {
const sessionRaw = localStorage.getItem(STORAGE_KEYS.SESSION);
if (sessionRaw) {
try {
this.reconnectEmail = JSON.parse(sessionRaw)?.options?.email ?? null;
} catch {
/* ignore */
}
}
this.reconnectEmail = this.reconnectEmail ?? localStorage.getItem(STORAGE_KEYS.EMAIL);
}
this.storage = null;
this.mokuroFolder = null;
this.needsReconnect = true;
if (browser) {
localStorage.removeItem(STORAGE_KEYS.SESSION);
// Keep active_cloud_provider so the UI still shows MEGA in a needs-attention state.
}
}
/** Email captured for reconnect pre-fill (mirrors WebDAV's getLastUsername). */
getLastUsername(): string | null {
if (this.reconnectEmail) return this.reconnectEmail;
if (!browser) return null;
const sessionRaw = localStorage.getItem(STORAGE_KEYS.SESSION);
if (sessionRaw) {
try {
return JSON.parse(sessionRaw)?.options?.email ?? null;
} catch {
return null;
}
}
return localStorage.getItem(STORAGE_KEYS.EMAIL);
}
async login(credentials?: ProviderCredentials): Promise<void> {
if (!credentials || !credentials.email || !credentials.password) {
throw new ProviderError('Email and password are required', 'mega', 'INVALID_CREDENTIALS');
}
const { email, password, secondFactorCode } = credentials as MegaCredentials;
try {
// Dynamically import megajs to reduce initial bundle size
const { Storage } = await import('megajs');
// Fresh interactive login. The constructor cb fires after the tree loads
// (autoload:true), so the Storage is ready once this promise resolves.
// keepalive:false disables megajs's server-change (sc) long-poll. We never use
// push notifications (we reload explicitly), and that poll's handler crashes on
// delete events ("Cannot read properties of undefined (reading 'parent')").
const storage: any = await new Promise((resolve, reject) => {
const s = new Storage(
{ email, password, secondFactorCode, autoload: true, keepalive: false } as any,
(error: Error | null) => (error ? reject(error) : resolve(s))
);
});
this.storage = storage;
await this.ensureMokuroFolder();
this.persistSession();
this.needsReconnect = false;
this.reconnectEmail = email;
setActiveProviderKey('mega');
console.log('✅ MEGA login successful');
} catch (error) {
this.storage = null;
this.mokuroFolder = null;
if (isMfaRequiredError(error)) {
throw new ProviderError(
'MEGA requires a two-factor authentication code',
'mega',
'MFA_REQUIRED',
false
);
}
throw new ProviderError(
`MEGA login failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
'mega',
'LOGIN_FAILED',
true
);
}
}
/** Persist the current session as a sanitized toJSON() blob; drop legacy keys. */
private persistSession(): void {
if (!browser || !this.storage) return;
const blob: MegaSessionBlob = sanitizeSessionBlob(this.storage.toJSON());
localStorage.setItem(STORAGE_KEYS.SESSION, JSON.stringify(blob));
localStorage.removeItem(STORAGE_KEYS.EMAIL);
localStorage.removeItem(STORAGE_KEYS.PASSWORD);
}
async logout(): Promise<void> {
this.storage = null;
this.mokuroFolder = null;
this.needsReconnect = false;
this.reconnectEmail = null;
if (browser) {
localStorage.removeItem(STORAGE_KEYS.SESSION);
localStorage.removeItem(STORAGE_KEYS.EMAIL);
localStorage.removeItem(STORAGE_KEYS.PASSWORD);
localStorage.removeItem(STORAGE_KEYS.FOLDER_PATH);
}
clearActiveProviderKey();
console.log('MEGA logged out');
}
/** Rebuild an authenticated Storage from a saved session blob (no password, no login round-trip). */
private async restoreSession(blob: MegaSessionBlob): Promise<void> {
const { Storage } = await import('megajs');
// Force keepalive:false so the restored session never starts the crashing sc poll,
// even for blobs persisted before that default changed.
const storage: any = Storage.fromJSON({
...(blob as any),
options: { ...((blob as any).options ?? {}), keepalive: false }
});
// fromJSON does no network and loads no tree; reload populates root + files.
// A dead session throws ESID here.
await storage.reload(true);
this.storage = storage;
this.mokuroFolder = null;
await this.ensureMokuroFolder();
this.needsReconnect = false;
this.reconnectEmail = (blob.options && (blob.options as any).email) || this.reconnectEmail;
setActiveProviderKey('mega');
}
/** Restore on app load: session blob first, then one-time legacy email/password migration. */
async restorePersistedSession(): Promise<void> {
if (!browser) return;
const sessionRaw = localStorage.getItem(STORAGE_KEYS.SESSION);
if (sessionRaw) {
try {
await this.restoreSession(JSON.parse(sessionRaw) as MegaSessionBlob);
console.log('Restored MEGA session from stored token');
} catch (error) {
if (isSessionExpiredError(error) || isAuthRejectionError(error)) {
console.error('Stored MEGA session invalid; reconnect required');
this.markSessionExpired();
} else {
console.warn('Failed to restore MEGA session (temporary error), will retry:', error);
}
}
return;
}
// Legacy migration: log in with stored email/password, which persists a session blob
// and removes the password (see login()/persistSession()).
const email = localStorage.getItem(STORAGE_KEYS.EMAIL);
const password = localStorage.getItem(STORAGE_KEYS.PASSWORD);
if (email && password) {
try {
await this.login({ email, password });
console.log('Migrated MEGA legacy credentials to session token');
} catch (error) {
if (isMfaRequiredError(error)) {
// Account enabled 2FA after the password was stored — cannot migrate silently.
this.reconnectEmail = email;
this.markSessionExpired();
} else if (isAuthRejectionError(error)) {
this.reconnectEmail = email;
this.markSessionExpired();
} else {
console.warn('MEGA migration deferred (temporary error), keeping legacy creds:', error);
}
}
}
}
/**
* Refresh the file-tree cache by rebuilding the session from the stored token.
* No password and no re-login round-trip — fromJSON + reload only.
*/
private async reinitialize(): Promise<void> {
if (!browser) return;
// No live session to refresh — fall back to restoring from the stored token.
if (!this.storage) {
await this.restorePersistedSession();
return;
}
try {
// Refresh the file tree on the EXISTING session, in place.
//
// We must NOT rebuild the storage and close the old one: megajs
// `storage.close()` issues `{a:'sml'}`, which TERMINATES the session sid
// server-side. Every storage (login, restore, reinitialize, upload worker)
// reuses the one persisted sid, so closing any of them invalidates the
// stored token and makes every later request fail with ESID (-15).
await this.storage.reload(true);
this.mokuroFolder = null;
console.log('✅ MEGA cache reinitialized (in-place reload)');
} catch (error) {
if (isSessionExpiredError(error)) {
this.markSessionExpired();
return;
}
// Transient error: keep the existing storage so we don't appear logged out.
console.warn('Continuing with potentially stale MEGA cache:', error);
}
}
private async ensureMokuroFolder(): Promise<any> {
// Fast path: folder already exists in storage cache.
const existing = this.findMokuroFolder();
if (existing) {
this.mokuroFolder = existing;
return existing;
}
// Coalesce concurrent calls so only one mkdir runs.
if (this.mokuroFolderPromise) {
return this.mokuroFolderPromise;
}
this.mokuroFolderPromise = (async () => {
try {
// Re-check after acquiring the mutex; another caller may have created it.
const recheck = this.findMokuroFolder();
if (recheck) {
this.mokuroFolder = recheck;
return recheck;
}
const folder = await this.createFolder(MOKURO_FOLDER);
console.log('Created mokuro-reader folder in MEGA');
this.mokuroFolder = folder;
return folder;
} catch (error) {
console.error('ensureMokuroFolder error:', error);
throw new ProviderError(
`Failed to ensure mokuro folder exists: ${error instanceof Error ? error.message : 'Unknown error'}`,
'mega',
'FOLDER_ERROR'
);
} finally {
this.mokuroFolderPromise = null;
}
})();
return this.mokuroFolderPromise;
}
private findMokuroFolder(): any | null {
const files = Object.values(this.storage.files || {});
return files.find((f: any) => f.name === MOKURO_FOLDER && f.directory) || null;
}
private listFolder(folder: any): Promise<any[]> {
return new Promise((resolve, reject) => {
// Get all files from storage
const files = Object.values(this.storage.files || {});
// Filter files that are children of this folder
const children = files.filter((f: any) => f.parent === folder);
resolve(children);
});
}
private createFolder(name: string): Promise<any> {
return new Promise((resolve, reject) => {
this.storage.mkdir(name, (error: Error | null, folder: any) => {
if (error) {
reject(error);
} else {
resolve(folder);
}
});
});
}
private getNodeById(fileId: string): any | null {
const files = Object.values(this.storage.files || {});
return files.find((f: any) => (f.nodeId === fileId || f.id === fileId) && !f.directory) || null;
}
private async findFolderByPath(folderPath: string, rootFolder: any): Promise<any | null> {
const pathParts = folderPath.split('/').filter(Boolean);
let currentFolder = rootFolder;
for (const folderName of pathParts) {
const children = await this.listFolder(currentFolder);
const nextFolder = children.find((f: any) => f.name === folderName && f.directory);
if (!nextFolder) {
return null;
}
currentFolder = nextFolder;
}
return currentFolder;
}
private buildRenamedCloudFile(
file: CloudFileMetadata,
nextPath: string,
fileId?: string,
modifiedTime?: string
): CloudFileMetadata {
return {
...file,
fileId: fileId || file.fileId,
path: nextPath,
modifiedTime: modifiedTime || new Date().toISOString()
};
}
// VOLUME STORAGE METHODS
async listCloudVolumes(
skipReinitialize = false
): Promise<import('../../provider-interface').CloudFileMetadata[]> {
if (!this.isAuthenticated()) {
throw new ProviderError('Not authenticated', 'mega', 'NOT_AUTHENTICATED', true);
}
try {
// Only reinitialize if needed (cache miss, initial load)
// Skip for post-operation refreshes where storage.files is already fresh
if (!skipReinitialize) {
await this.reinitialize();
}
await this.ensureMokuroFolder();
// Get all files from storage
const files = Object.values(this.storage.files || {});
// Find ALL mokuro-reader folders (there may be multiple from different sessions)
// Note: We don't check parent because MEGA's root folder location varies by account/locale
const mokuroFolders = files.filter((f: any) => f.name === MOKURO_FOLDER && f.directory);
// Filter CBZ and JSON files that are in ANY mokuro-reader folder or its subfolders
const allFiles: import('../../provider-interface').CloudFileMetadata[] = [];
for (const file of files) {
// Skip non-files
if ((file as any).directory) continue;
// Check if file is a CBZ, sidecar, or JSON
const name = (file as any).name || '';
const isCbz = name.toLowerCase().endsWith('.cbz');
const lowerName = name.toLowerCase();
const isSidecar =
lowerName.endsWith('.mokuro') ||
lowerName.endsWith('.mokuro.gz') ||
/\.(webp|jpe?g)$/i.test(lowerName);
const isJson = name === 'volume-data.json' || name === 'profiles.json';
if (!isCbz && !isSidecar && !isJson) continue;
// Check if file is in ANY mokuro-reader folder or subfolder
let parent = (file as any).parent;
let pathParts: string[] = [];
let foundMokuroRoot = false;
let isInTrash = false;
// Walk up the tree to build path and verify it's under a mokuro-reader folder
while (parent) {
// Check if any parent is the Rubbish Bin (trash)
if (parent.name === 'Rubbish Bin') {
isInTrash = true;
break;
}
// Check if this parent is ANY mokuro-reader folder
const isMokuroFolder = mokuroFolders.some((mf: any) => mf === parent);
if (isMokuroFolder) {
foundMokuroRoot = true;
break;
}
if (parent.name) {
pathParts.unshift(parent.name);
}
parent = parent.parent;
}
// Skip files in trash
if (isInTrash) continue;
// If we found mokuro root, this file is under a mokuro-reader folder
if (foundMokuroRoot) {
// For JSON files in the mokuro root, use just the filename as path
// For CBZ files, build full path as "SeriesTitle/VolumeTitle.cbz"
let path: string;
if (isJson && pathParts.length === 0) {
// JSON file directly in mokuro folder
path = name;
} else {
// CBZ file or JSON in subfolder
pathParts.push(name);
path = pathParts.join('/');
}
// Get file metadata
const fileId = (file as any).nodeId || (file as any).id || '';
const modifiedTime = (file as any).timestamp
? new Date((file as any).timestamp * 1000).toISOString()
: new Date().toISOString();
const size = (file as any).size || 0;
allFiles.push({
provider: 'mega',
fileId,
path,
modifiedTime,
size
});
}
}
console.log(`✅ Listed ${allFiles.length} files from MEGA`);
return allFiles;
} catch (error) {
throw new ProviderError(
`Failed to list cloud volumes: ${error instanceof Error ? error.message : 'Unknown error'}`,
'mega',
'LIST_FAILED',
false,
true
);
}
}
async uploadFile(
path: string,
blob: UploadPayload,
description?: string,
onProgress?: (loaded: number, total: number) => void
): Promise<string> {
if (!this.isAuthenticated()) {
throw new ProviderError('Not authenticated', 'mega', 'NOT_AUTHENTICATED', true);
}
const payloadSize = getUploadPayloadSize(blob);
try {
if (onProgress) {
onProgress(0, payloadSize);
}
// Wrap upload in retry logic to handle stale cache
const fileId = await retryWithCacheRefresh(
async () => {
const mokuroFolder = await this.ensureMokuroFolder();
// Parse path: "SeriesTitle/VolumeTitle.cbz"
const pathParts = path.split('/');
const fileName = pathParts.pop() || path;
const seriesFolderName = pathParts.join('/');
// Find or create series folder if path includes subfolder
let targetFolder = mokuroFolder;
if (seriesFolderName) {
targetFolder = await this.ensureSeriesFolder(seriesFolderName, mokuroFolder);
}
let buffer: Uint8Array;
if (blob instanceof Uint8Array) {
buffer = blob;
} else if (blob instanceof ArrayBuffer) {
buffer = new Uint8Array(blob);
} else {
const arrayBuffer = await blob.arrayBuffer();
buffer = new Uint8Array(arrayBuffer);
}
// Check if file already exists
const children = await this.listFolder(targetFolder);
const existingFile = children.find((f: any) => f.name === fileName && !f.directory);
// Delete existing file if found
if (existingFile) {
const existingFileId = existingFile.nodeId || existingFile.id;
await new Promise<void>((resolve, reject) => {
existingFile.delete(true, (error: Error | null) => {
if (error) reject(error);
else {
resolve();
// MEGA.js doesn't remove from storage.files, so we do it manually
// Done after resolve() to let MEGA.js finish its internal cleanup first
delete this.storage.files[existingFileId];
}
});
});
}
// Upload new file
const uploadedFileId = await new Promise<string>((resolve, reject) => {
const uploadStream = targetFolder.upload(
{
name: fileName,
size: buffer.length
},
buffer,
(error: Error | null, file: any) => {
if (error) {
reject(error);
} else {
const fileId = file?.nodeId || file?.id || '';
if (onProgress) {
onProgress(buffer.length, buffer.length);
}
console.log(`✅ Uploaded ${fileName} to MEGA (${fileId})`);
resolve(fileId);
}
}
);
if (onProgress && uploadStream && typeof uploadStream.on === 'function') {
uploadStream.on('progress', (progress: any) => {
const loaded = Number(progress?.bytesUploaded ?? progress?.bytesLoaded ?? 0);
const total = Number(progress?.bytesTotal ?? buffer.length);
onProgress(loaded, total > 0 ? total : buffer.length);
});
}
});
return uploadedFileId;
},
`Upload ${path} to MEGA`,
() => this.reinitialize()
);
// Refresh cache from MEGA's internal storage.files (which auto-updates on upload)
// Skip reinitialize since storage.files is already fresh
await megaCache.fetch(true);
return fileId;
} catch (error) {
throw new ProviderError(
`Failed to upload volume CBZ: ${error instanceof Error ? error.message : 'Unknown error'}`,
'mega',
'UPLOAD_FAILED',
false,
true
);
}
}
async downloadFile(
file: CloudFileMetadata,
onProgress?: (loaded: number, total: number) => void
): Promise<Blob> {
if (!this.isAuthenticated()) {
throw new ProviderError('Not authenticated', 'mega', 'NOT_AUTHENTICATED', true);
}
// Extract file ID from metadata
const fileId = file.fileId;
try {
// Find the file by ID
const files = Object.values(this.storage.files || {});
const megaFile = files.find(
(f: any) => (f.nodeId === fileId || f.id === fileId) && !f.directory
);
if (!megaFile) {
throw new Error('File not found');
}
return new Promise((resolve, reject) => {
const fileObj = megaFile as any;
// Use download with progress callback if provided
if (onProgress) {
// MEGA.js download supports progress via stream options
const stream = fileObj.download({ returnCiphertext: false });
const chunks: Uint8Array[] = [];
let loaded = 0;
const total = fileObj.size || 0;
stream.on('data', (chunk: Uint8Array) => {
chunks.push(chunk);
loaded += chunk.length;
onProgress(loaded, total);
});
stream.on('end', () => {
// Combine all chunks into a single Uint8Array
const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
const combined = new Uint8Array(totalLength);
let offset = 0;
for (const chunk of chunks) {
combined.set(chunk, offset);
offset += chunk.length;
}
const blob = new Blob([combined], { type: 'application/zip' });
console.log(`✅ Downloaded ${fileObj.name} from MEGA`);
resolve(blob);
});
stream.on('error', (error: Error) => {
reject(error);
});
} else {
// Simple download without progress
fileObj.download((error: Error | null, data: Uint8Array) => {
if (error) {
reject(error);
} else {
// Convert to standard Uint8Array to satisfy TypeScript
const standardArray = new Uint8Array(Array.from(data));
const blob = new Blob([standardArray], { type: 'application/zip' });
console.log(`✅ Downloaded ${fileObj.name} from MEGA`);
resolve(blob);
}
});
}
});
} catch (error) {
throw new ProviderError(
`Failed to download file: ${error instanceof Error ? error.message : 'Unknown error'}`,
'mega',
'DOWNLOAD_FAILED',
false,
true
);
}
}
async deleteFile(file: CloudFileMetadata): Promise<void> {
if (!this.isAuthenticated()) {
throw new ProviderError('Not authenticated', 'mega', 'NOT_AUTHENTICATED', true);
}
// Extract file ID from metadata
const fileId = file.fileId;
try {
// Wrap delete in retry logic to handle stale cache
await retryWithCacheRefresh(
async () => {
// Find the file by ID
const files = Object.values(this.storage.files || {});
const megaFile = files.find(
(f: any) => (f.nodeId === fileId || f.id === fileId) && !f.directory
);
if (!megaFile) {
throw new Error('File not found');
}
return new Promise<void>((resolve, reject) => {
(megaFile as any).delete(true, (error: Error | null) => {
if (error) {
reject(error);
} else {
console.log(`✅ Deleted file from MEGA (${fileId})`);
resolve();
delete this.storage.files[fileId];
}
});
});
},
`Delete file ${fileId} from MEGA`,
() => this.reinitialize()
);
// Refresh cache from MEGA's internal storage.files (which auto-updates on delete)
// Skip reinitialize since storage.files is already fresh
await megaCache.fetch(true);
} catch (error) {
throw new ProviderError(
`Failed to delete volume CBZ: ${error instanceof Error ? error.message : 'Unknown error'}`,
'mega',
'DELETE_FAILED',
false,
true
);
}
}
async renameFile(file: CloudFileMetadata, newPath: string): Promise<CloudFileMetadata> {
if (!this.isAuthenticated()) {
throw new ProviderError('Not authenticated', 'mega', 'NOT_AUTHENTICATED', true);
}
const normalizedNewPath = newPath.replace(/^\/+|\/+$/g, '');
if (file.path === normalizedNewPath) {
return file;
}
try {
return await retryWithCacheRefresh(
async () => {
const megaFile = this.getNodeById(file.fileId);
if (!megaFile) {
throw new Error('File not found');
}
const pathParts = normalizedNewPath.split('/');
const newFileName = pathParts.pop() || normalizedNewPath;
const newSeriesPath = pathParts.join('/');
const mokuroFolder = await this.ensureMokuroFolder();
const targetFolder = newSeriesPath
? await this.ensureSeriesFolder(newSeriesPath, mokuroFolder)
: mokuroFolder;
const targetChildren = await this.listFolder(targetFolder);
const existingTarget = targetChildren.find(
(child: any) =>
!child.directory &&
child.name === newFileName &&
child !== megaFile &&
child.nodeId !== megaFile.nodeId &&
child.id !== megaFile.id
);
if (existingTarget) {
throw new ProviderError(
`Target file already exists at '${normalizedNewPath}'`,
'mega',
'TARGET_EXISTS'
);
}
if (megaFile.parent !== targetFolder) {
await megaFile.moveTo(targetFolder);
}
if (megaFile.name !== newFileName) {
await megaFile.rename(newFileName);
}
const nextFileId = megaFile.nodeId || megaFile.id || file.fileId;
return this.buildRenamedCloudFile(file, normalizedNewPath, nextFileId);
},
`Rename file ${file.fileId} in MEGA`,
() => this.reinitialize()
);
} catch (error) {
if (error instanceof ProviderError) {
throw error;
}
throw new ProviderError(
`Failed to rename file: ${error instanceof Error ? error.message : 'Unknown error'}`,
'mega',
'RENAME_FAILED',
false,
true
);
}
}
async renameFolder(oldPath: string, newPath: string): Promise<CloudFileMetadata[]> {
if (!this.isAuthenticated()) {
throw new ProviderError('Not authenticated', 'mega', 'NOT_AUTHENTICATED', true);
}
const normalizedOldPath = oldPath.replace(/^\/+|\/+$/g, '');
const normalizedNewPath = newPath.replace(/^\/+|\/+$/g, '');
if (normalizedOldPath === normalizedNewPath) {
return megaCache.getBySeries(normalizedOldPath);
}
const existingFiles = megaCache.getBySeries(normalizedOldPath);
if (existingFiles.length === 0) {
return [];
}
try {
await retryWithCacheRefresh(
async () => {
const mokuroFolder = await this.ensureMokuroFolder();
const sourceFolder = await this.findFolderByPath(normalizedOldPath, mokuroFolder);
if (!sourceFolder) {
throw new ProviderError(
`Series folder '${normalizedOldPath}' not found`,
'mega',
'FOLDER_NOT_FOUND'
);
}
const existingTargetFolder = await this.findFolderByPath(normalizedNewPath, mokuroFolder);
if (existingTargetFolder && existingTargetFolder !== sourceFolder) {
throw new ProviderError(
`Target series folder already exists at '${normalizedNewPath}'`,
'mega',
'TARGET_EXISTS'
);
}
const pathParts = normalizedNewPath.split('/');