-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
2306 lines (1988 loc) · 70.2 KB
/
main.js
File metadata and controls
2306 lines (1988 loc) · 70.2 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
const { app, BrowserWindow, Tray, Menu, ipcMain, dialog, shell, nativeImage, clipboard } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');
const crypto = require('crypto');
const { exec } = require('child_process');
const axios = require('axios');
const FormData = require('form-data');
const { autoUpdater } = require('electron-updater');
const Store = require('electron-store');
const chokidar = require('chokidar');
const { encryptFileToZkeContainer, decryptZkeContainer, parseHeader } = require('./utils/zke-stream');
// Initialize electron-store for settings
const store = new Store();
// Keep references to prevent garbage collection
let mainWindow = null;
let tray = null;
let uploadQueue = [];
let isQuitting = false;
// FileShot Drive (Windows): map a drive letter to a local inbox folder
let driveWatcher = null;
let driveQueue = [];
let driveQueueRunning = false;
// App configuration
const isDev = process.argv.includes('--dev');
const API_URL = isDev ? 'http://localhost:3000/api' : 'https://api.fileshot.io/api';
const FRONTEND_URL = isDev ? 'http://localhost:8080' : 'https://fileshot.io';
// Local fallback (bundled) frontend
const LOCAL_FRONTEND_INDEX = path.join(__dirname, 'renderer', 'site', 'index.html');
const LOCAL_OFFLINE_PAGE = path.join(__dirname, 'renderer', 'offline.html');
// Local-first UI (always available in v1.2+)
const LOCAL_UI_INDEX = path.join(__dirname, 'renderer', 'local', 'index.html');
// Local vault paths
function getVaultRoot() {
// userData is per-user/per-install and writable.
return path.join(app.getPath('userData'), 'vault');
}
function getVaultFilesDir() {
return path.join(getVaultRoot(), 'files');
}
function getVaultTmpDir() {
return path.join(getVaultRoot(), 'tmp');
}
function getDriveInboxDir() {
return path.join(getVaultRoot(), 'drive-inbox');
}
function getDriveUploadingDir() {
return path.join(getDriveInboxDir(), '_uploading');
}
function getDriveUploadedDir() {
return path.join(getDriveInboxDir(), '_uploaded');
}
function getDriveFailedDir() {
return path.join(getDriveInboxDir(), '_failed');
}
function getConfiguredDriveLetter() {
const raw = String(store.get('drive.letter', 'F') || 'F').trim();
const letter = raw.replace(':', '').toUpperCase().slice(0, 1);
return /^[A-Z]$/.test(letter) ? letter : 'F';
}
function isDriveLetterAvailable(letter) {
const L = String(letter || '').replace(':', '').toUpperCase().slice(0, 1);
if (!/^[A-Z]$/.test(L)) return false;
// Avoid A/B (floppy legacy) and C (system drive).
if (L === 'A' || L === 'B' || L === 'C') return false;
try {
return !fs.existsSync(`${L}:\\`);
} catch (_) {
return false;
}
}
function pickAvailableDriveLetter(preferred) {
const pref = String(preferred || '').replace(':', '').toUpperCase().slice(0, 1);
const order = [];
if (/^[A-Z]$/.test(pref)) order.push(pref);
// Common “nice” letters first.
for (let c = 'F'.charCodeAt(0); c <= 'Z'.charCodeAt(0); c++) {
order.push(String.fromCharCode(c));
}
// Fall back to D/E if available.
order.push('E');
order.push('D');
for (const L of order) {
if (isDriveLetterAvailable(L)) return L;
}
return null;
}
async function isRunningAsAdmin() {
if (process.platform !== 'win32') return false;
// net session succeeds only when elevated.
try {
await execPromise('net session', { timeout: 5000 });
return true;
} catch (_) {
return false;
}
}
async function relaunchAsStandardUser() {
if (process.platform !== 'win32') return false;
// Best-effort: launching via explorer.exe usually uses the non-elevated shell token.
try {
const exePath = process.execPath;
await execPromise(`explorer.exe "${exePath}"`);
return true;
} catch (_) {
return false;
}
}
function isDriveFeatureAvailable() {
return process.platform === 'win32';
}
function execPromise(command, opts = {}) {
return new Promise((resolve, reject) => {
exec(command, { windowsHide: true, ...opts }, (error, stdout, stderr) => {
if (error) return reject({ error, stdout: String(stdout || ''), stderr: String(stderr || '') });
resolve({ stdout: String(stdout || ''), stderr: String(stderr || '') });
});
});
}
async function ensureDriveDirs() {
ensureVaultDirs();
fs.mkdirSync(getDriveInboxDir(), { recursive: true });
fs.mkdirSync(getDriveUploadingDir(), { recursive: true });
fs.mkdirSync(getDriveUploadedDir(), { recursive: true });
fs.mkdirSync(getDriveFailedDir(), { recursive: true });
}
// ============================================================================
// STORAGE QUOTA (tier usage/limit)
// ============================================================================
const STORAGE_USAGE_TTL_MS = 2 * 60 * 1000;
let storageUsageCache = {
data: null,
lastFetchMs: 0,
lastError: null
};
function formatBytes(bytes) {
const n = Number(bytes);
if (!Number.isFinite(n) || n < 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let v = n;
let i = 0;
while (v >= 1024 && i < units.length - 1) {
v /= 1024;
i++;
}
const digits = i === 0 ? 0 : i === 1 ? 1 : 2;
return `${v.toFixed(digits)} ${units[i]}`;
}
function formatQuotaLine(info) {
if (!info) return 'Storage: (not loaded yet)';
const tier = String(info.tier || 'free');
const usage = Number(info.usage || 0);
const limit = info.limit;
if (limit === null || typeof limit === 'undefined') {
return `Storage: ${formatBytes(usage)} used (Tier: ${tier})`;
}
const lim = Number(limit);
if (!Number.isFinite(lim) || lim <= 0) {
return `Storage: ${formatBytes(usage)} used (Tier: ${tier})`;
}
const remaining = Math.max(0, lim - usage);
return `Storage: ${formatBytes(usage)} / ${formatBytes(lim)} (Remaining: ${formatBytes(remaining)})`;
}
async function fetchStorageUsageFromApi() {
const token = store.get('authToken', null);
if (!token) throw new Error('Not logged in');
const res = await axios.get(`${API_URL}/files/usage`, {
headers: { Authorization: `Bearer ${token}` },
timeout: 15000
});
const usage = res?.data?.usage;
const limit = res?.data?.limit;
const tier = res?.data?.tier;
if (typeof usage === 'undefined') throw new Error('Usage API returned no usage');
return { usage, limit, tier };
}
function buildStorageStatusText({ info, error }) {
const now = new Date();
const lines = [];
lines.push('FileShot Drive — Storage Status');
lines.push('');
lines.push(`Updated: ${now.toLocaleString()}`);
lines.push('');
if (error) {
lines.push('Status: unavailable');
lines.push(`Error: ${String(error)}`);
} else if (info) {
const tier = String(info.tier || 'free');
const usage = Number(info.usage || 0);
const limit = info.limit;
lines.push(`Tier: ${tier}`);
if (limit === null || typeof limit === 'undefined') {
lines.push(`Used: ${formatBytes(usage)}`);
lines.push('Limit: Unlimited');
} else {
const lim = Number(limit);
lines.push(`Used: ${formatBytes(usage)}`);
lines.push(`Limit: ${formatBytes(lim)}`);
lines.push(`Remaining: ${formatBytes(Math.max(0, lim - usage))}`);
}
lines.push('');
lines.push('Tip: Upgrade or manage storage at https://fileshot.io/pricing.html');
} else {
lines.push('Status: not loaded');
lines.push('Log in to see your plan storage limit.');
}
lines.push('');
lines.push('Note: Windows Explorer drive “capacity” cannot be customized when using SUBST.');
lines.push('This file shows your actual FileShot account storage limit.');
lines.push('');
return lines.join(os.EOL);
}
async function writeDriveStorageStatusFile({ info, error }) {
if (!isDriveFeatureAvailable()) return;
try {
await ensureDriveDirs();
const statusPath = path.join(getDriveInboxDir(), 'FILESHOT_STORAGE.txt');
fs.writeFileSync(statusPath, buildStorageStatusText({ info, error }), 'utf8');
} catch (_) {
// Best-effort.
}
}
async function refreshStorageUsage({ force = false, reason = '' } = {}) {
const now = Date.now();
const isFresh = storageUsageCache.data && (now - storageUsageCache.lastFetchMs) < STORAGE_USAGE_TTL_MS;
if (!force && isFresh) return storageUsageCache.data;
try {
const info = await fetchStorageUsageFromApi();
storageUsageCache = { data: info, lastFetchMs: now, lastError: null };
await writeDriveStorageStatusFile({ info, error: null });
rebuildTrayMenu();
return info;
} catch (e) {
const msg = e?.response?.data?.error || e?.message || String(e);
storageUsageCache = { ...storageUsageCache, lastFetchMs: now, lastError: msg };
await writeDriveStorageStatusFile({ info: storageUsageCache.data, error: msg });
// Don't spam rebuilds on failure; but tray may need to show error.
rebuildTrayMenu();
return storageUsageCache.data;
} finally {
if (reason) {
// Lightweight debug breadcrumb.
try { console.log('[StorageUsage] refreshed', { reason, ok: !storageUsageCache.lastError }); } catch (_) {}
}
}
}
function sanitizeFileName(name) {
const s = String(name || '').trim();
// Windows invalid characters: \ / : * ? " < > |
return s.replace(/[\\/:*?"<>|]/g, '_').replace(/\s+/g, ' ').slice(0, 180) || 'file';
}
async function waitForStableFile(filePath, stableMs = 1500, maxWaitMs = 10 * 60 * 1000) {
const p = String(filePath || '');
const start = Date.now();
let lastSize = -1;
let lastMtime = 0;
let stableFor = 0;
let lastTick = Date.now();
while (Date.now() - start < maxWaitMs) {
let st;
try {
st = await fs.promises.stat(p);
} catch (_) {
// File might still be being moved/created; retry.
await new Promise(r => setTimeout(r, 250));
continue;
}
const size = Number(st.size || 0);
const mtime = Number(st.mtimeMs || 0);
const now = Date.now();
const dt = now - lastTick;
lastTick = now;
const unchanged = size === lastSize && mtime === lastMtime;
if (unchanged) {
stableFor += dt;
if (stableFor >= stableMs) return true;
} else {
stableFor = 0;
lastSize = size;
lastMtime = mtime;
}
await new Promise(r => setTimeout(r, 300));
}
throw new Error('Timed out waiting for file to become stable');
}
async function mapDriveLetter(letter, targetDir) {
if (!isDriveFeatureAvailable()) throw new Error('Drive mapping is only supported on Windows');
const L = String(letter || '').replace(':', '').toUpperCase();
if (!/^[A-Z]$/.test(L)) throw new Error('Invalid drive letter');
const dir = String(targetDir || '');
if (!dir) throw new Error('Missing target directory');
// Ensure directory exists.
fs.mkdirSync(dir, { recursive: true });
// SUBST will fail if the letter is already in use.
await execPromise(`subst ${L}: "${dir}"`);
}
async function unmapDriveLetter(letter) {
if (!isDriveFeatureAvailable()) return;
const L = String(letter || '').replace(':', '').toUpperCase();
if (!/^[A-Z]$/.test(L)) return;
// Best-effort.
try {
await execPromise(`subst ${L}: /D`);
} catch (_) {}
}
function getDriveRootPath(letter) {
const L = String(letter || '').replace(':', '').toUpperCase();
return `${L}:\\`;
}
function pushRecentUpload(fileName, url) {
const recentUploads = store.get('recentUploads', []);
recentUploads.unshift({ fileName, url, uploadedAt: Date.now() });
if (recentUploads.length > 10) recentUploads.length = 10;
store.set('recentUploads', recentUploads);
rebuildTrayMenu();
}
async function uploadPlainFileAsZke({ inputPath, originalName, onProgress }) {
const p = String(inputPath || '');
if (!p || !fs.existsSync(p)) throw new Error('Missing input file');
const st = fs.statSync(p);
if (!st.isFile()) throw new Error('Input must be a file');
const token = store.get('authToken', null);
if (!token) throw new Error('Not logged in');
const headers = { Authorization: `Bearer ${token}` };
const safeName = String(originalName || path.basename(p) || 'file');
const tmpId = crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}_${crypto.randomBytes(8).toString('hex')}`;
ensureVaultDirs();
const tmpOut = path.join(getVaultTmpDir(), `${tmpId}.fszk`);
if (typeof onProgress === 'function') onProgress({ percent: 5, stage: 'Encrypting locally (ZKE)...' });
const enc = await encryptFileToZkeContainer({
inputPath: p,
outputPath: tmpOut,
originalName: safeName,
originalMimeType: 'application/octet-stream',
mode: 'raw',
chunkSize: 512 * 1024
});
const encryptedSize = fs.statSync(tmpOut).size;
if (typeof onProgress === 'function') onProgress({ percent: 20, stage: 'Requesting upload slot...' });
const preUploadBody = {
fileName: safeName,
fileSize: st.size,
isZeroKnowledge: 'true',
originalFileName: safeName,
originalFileSize: st.size,
originalMimeType: 'application/octet-stream'
};
const pre = await axios.post(`${API_URL}/files/pre-upload`, preUploadBody, {
headers: {
'Content-Type': 'application/json',
...headers
},
timeout: 60000
});
const fileId = pre?.data?.fileId;
if (!fileId) throw new Error('Pre-upload failed (missing fileId)');
const NET_CHUNK_SIZE = 8 * 1024 * 1024; // 8MB
const totalChunks = Math.max(1, Math.ceil(encryptedSize / NET_CHUNK_SIZE));
let uploaded = 0;
if (typeof onProgress === 'function') onProgress({ percent: 25, stage: `Uploading (${totalChunks} chunks)...` });
const fd = fs.openSync(tmpOut, 'r');
try {
for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
const start = chunkIndex * NET_CHUNK_SIZE;
const end = Math.min(start + NET_CHUNK_SIZE, encryptedSize);
const len = end - start;
const buf = Buffer.allocUnsafe(len);
const read = fs.readSync(fd, buf, 0, len, start);
if (read !== len) throw new Error('Failed to read encrypted chunk');
const form = new FormData();
form.append('chunk', buf, { filename: `chunk-${chunkIndex}` });
form.append('totalChunks', String(totalChunks));
form.append('isLastChunk', String(chunkIndex === totalChunks - 1));
await axios.post(`${API_URL}/files/upload-chunk/${fileId}/${chunkIndex}`, form, {
headers: {
...form.getHeaders(),
...headers
},
maxContentLength: Infinity,
maxBodyLength: Infinity,
timeout: 600000
});
uploaded += len;
const pct = 25 + Math.floor((uploaded / encryptedSize) * 70);
if (typeof onProgress === 'function') onProgress({ percent: Math.min(95, pct), stage: `Uploading... ${chunkIndex + 1}/${totalChunks}` });
}
} finally {
try { fs.closeSync(fd); } catch (_) {}
}
if (typeof onProgress === 'function') onProgress({ percent: 96, stage: 'Finalizing...' });
await axios.post(`${API_URL}/files/finalize-upload/${fileId}`, {}, {
headers: {
'Content-Type': 'application/json',
...headers
},
timeout: 600000
});
const shareUrl = `${FRONTEND_URL}/downloads.html?f=${encodeURIComponent(fileId)}${enc.rawKey ? `#k=${encodeURIComponent(enc.rawKey)}` : ''}`;
try { fs.unlinkSync(tmpOut); } catch (_) {}
if (typeof onProgress === 'function') onProgress({ percent: 100, stage: 'Done' });
return { fileId, shareUrl };
}
async function startDriveWatcher() {
if (!isDriveFeatureAvailable()) return;
if (driveWatcher) return;
await ensureDriveDirs();
driveWatcher = chokidar.watch(getDriveInboxDir(), {
persistent: true,
ignoreInitial: true,
depth: 99,
awaitWriteFinish: false,
ignored: [
/\\_uploading\\/i,
/\\_uploaded\\/i,
/\\\.tmp\\/i,
/\.url$/i,
/\.lnk$/i
]
});
async function processDriveQueue() {
if (driveQueueRunning) return;
driveQueueRunning = true;
try {
while (driveQueue.length) {
if (!isDriveFeatureAvailable()) return;
const next = driveQueue.shift();
const originalPath = String(next || '');
if (!originalPath) continue;
const notifier = require('node-notifier');
try {
// Only handle real files.
const st = safeStat(originalPath);
if (!st || !st.isFile()) continue;
// Wait for Explorer copy to finish.
await waitForStableFile(originalPath, 1500, 10 * 60 * 1000);
const baseName = path.basename(originalPath);
const safeBase = sanitizeFileName(baseName);
// Best-effort: check quota before uploading so we can fail fast with a clear message.
// If we can't fetch usage (offline/not logged in), we still attempt the upload and let the server enforce.
let quotaInfo = null;
try {
quotaInfo = await refreshStorageUsage({ force: false, reason: 'drive:precheck' });
} catch (_) {
quotaInfo = storageUsageCache.data;
}
if (quotaInfo && quotaInfo.limit !== null && typeof quotaInfo.limit !== 'undefined') {
const usage = Number(quotaInfo.usage || 0);
const limit = Number(quotaInfo.limit);
const fileSize = Number(st.size || 0);
if (Number.isFinite(limit) && limit > 0 && Number.isFinite(usage) && (usage + fileSize) > limit) {
const tier = String(quotaInfo.tier || 'free');
const msg = `Storage full (${tier}): ${formatBytes(usage)} used of ${formatBytes(limit)}. File is ${formatBytes(fileSize)}.`;
try {
notifier.notify({
title: 'FileShot Drive',
message: msg,
icon: path.join(__dirname, 'assets', 'icon.png'),
sound: false
});
} catch (_) {}
// Move into _failed so it's not retried endlessly.
try {
fs.mkdirSync(getDriveFailedDir(), { recursive: true });
let dest = path.join(getDriveFailedDir(), safeBase);
if (fs.existsSync(dest)) {
const ext = path.extname(safeBase);
const stem = safeBase.slice(0, safeBase.length - ext.length);
dest = path.join(getDriveFailedDir(), `${stem}-${Date.now()}${ext}`);
}
fs.renameSync(originalPath, dest);
const errPath = `${dest}.error.txt`;
const details = [
'FileShot Drive — Upload blocked (storage limit reached)',
'',
msg,
'',
'Manage your storage or upgrade:',
'https://fileshot.io/pricing.html',
''
].join(os.EOL);
fs.writeFileSync(errPath, details, 'utf8');
} catch (_) {
// If we can't move it, leave it where it is.
}
continue;
}
}
// Move into _uploading to prevent re-trigger and to visually separate state.
const uploadingPath = path.join(getDriveUploadingDir(), safeBase);
let workPath = originalPath;
try {
fs.mkdirSync(getDriveUploadingDir(), { recursive: true });
// If destination exists, add a suffix.
let dest = uploadingPath;
if (fs.existsSync(dest)) {
const ext = path.extname(safeBase);
const stem = safeBase.slice(0, safeBase.length - ext.length);
dest = path.join(getDriveUploadingDir(), `${stem}-${Date.now()}${ext}`);
}
fs.renameSync(originalPath, dest);
workPath = dest;
} catch (_) {
// If rename fails (locked), upload in-place.
workPath = originalPath;
}
notifier.notify({
title: 'FileShot Drive',
message: `Uploading: ${safeBase}`,
icon: path.join(__dirname, 'assets', 'icon.png'),
sound: false
});
const { shareUrl } = await uploadPlainFileAsZke({
inputPath: workPath,
originalName: safeBase,
onProgress: (_) => {}
});
pushRecentUpload(safeBase, shareUrl);
// Move to _uploaded and drop a .url shortcut for the share link.
try {
fs.mkdirSync(getDriveUploadedDir(), { recursive: true });
const uploadedFilePath = path.join(getDriveUploadedDir(), path.basename(workPath));
if (workPath !== uploadedFilePath) {
let dest = uploadedFilePath;
if (fs.existsSync(dest)) {
const ext = path.extname(dest);
const stem = dest.slice(0, dest.length - ext.length);
dest = `${stem}-${Date.now()}${ext}`;
}
fs.renameSync(workPath, dest);
}
const urlName = `${sanitizeFileName(safeBase)}.url`;
const urlPath = path.join(getDriveUploadedDir(), urlName);
const shortcut = `[InternetShortcut]\r\nURL=${shareUrl}\r\n`;
fs.writeFileSync(urlPath, shortcut, 'utf8');
} catch (_) {}
notifier.notify({
title: 'FileShot Drive',
message: `Uploaded: ${safeBase}`,
icon: path.join(__dirname, 'assets', 'icon.png'),
sound: false
});
} catch (e) {
const msg = e && e.message ? e.message : String(e);
console.warn('[Drive] Upload failed:', msg);
try {
notifier.notify({
title: 'FileShot Drive',
message: `Upload failed: ${msg}`,
icon: path.join(__dirname, 'assets', 'icon.png'),
sound: false
});
} catch (_) {}
}
}
} finally {
driveQueueRunning = false;
}
}
driveWatcher.on('add', (filePath) => {
if (!isDriveFeatureAvailable()) return;
const p = String(filePath || '');
if (!p) return;
// Small guard against pathological spikes.
if (driveQueue.length < 5000) {
driveQueue.push(p);
}
processDriveQueue().catch(() => {});
});
}
async function stopDriveWatcher() {
if (driveWatcher) {
try {
await driveWatcher.close();
} catch (_) {}
driveWatcher = null;
}
// Clear any queued work; we'll rescan/continue fresh on next enable.
driveQueue = [];
driveQueueRunning = false;
}
async function cleanupFileShotDriveRuntime() {
if (!isDriveFeatureAvailable()) return;
const letter = getConfiguredDriveLetter();
await stopDriveWatcher();
await unmapDriveLetter(letter);
}
async function enableFileShotDrive() {
if (!isDriveFeatureAvailable()) {
dialog.showMessageBox({ type: 'info', message: 'FileShot Drive is currently Windows-only.' });
return;
}
await ensureDriveDirs();
let letter = getConfiguredDriveLetter();
// If the chosen letter is already in use, pick a free one automatically.
if (!isDriveLetterAvailable(letter)) {
const picked = pickAvailableDriveLetter(letter);
if (picked) {
letter = picked;
store.set('drive.letter', letter);
}
}
// If we're running elevated, this is a common reason the drive doesn't appear
// in normal Explorer. Warn and offer to relaunch normally.
const elevated = await isRunningAsAdmin();
if (elevated) {
const res = await dialog.showMessageBox({
type: 'warning',
title: 'FileShot Drive',
message: 'FileShot is running as Administrator. Mapped drives created from an elevated app may not show up in normal File Explorer.',
detail: 'Recommended: restart FileShot normally (not as administrator) so the drive appears under “This PC”.',
buttons: ['Restart normally', 'Continue anyway', 'Disable Drive'],
defaultId: 0,
cancelId: 1
});
if (res.response === 0) {
const relaunched = await relaunchAsStandardUser();
if (relaunched) {
app.quit();
return;
}
}
if (res.response === 2) {
await disableFileShotDrive();
return;
}
}
try {
await mapDriveLetter(letter, getDriveInboxDir());
} catch (e) {
// If it failed because the letter is in use, try a different letter automatically.
const picked = pickAvailableDriveLetter(letter);
if (picked && picked !== letter) {
try {
await mapDriveLetter(picked, getDriveInboxDir());
letter = picked;
store.set('drive.letter', letter);
} catch (e2) {
const details2 = (e2 && e2.stderr) ? String(e2.stderr).trim() : '';
dialog.showMessageBox({
type: 'error',
title: 'FileShot Drive',
message: `Could not map a drive letter automatically.`,
detail: details2
});
return;
}
} else {
const details = (e && e.stderr) ? String(e.stderr).trim() : '';
dialog.showMessageBox({
type: 'error',
title: 'FileShot Drive',
message: `Could not map drive ${letter}:\\. It may already be in use.`,
detail: details
});
return;
}
}
store.set('drive.enabled', true);
await startDriveWatcher();
rebuildTrayMenu();
// Best-effort: create/update the storage status file immediately.
refreshStorageUsage({ force: true, reason: 'drive:enabled' }).catch(() => {
writeDriveStorageStatusFile({ info: storageUsageCache.data, error: storageUsageCache.lastError }).catch(() => {});
});
try {
shell.openPath(getDriveRootPath(letter));
} catch (_) {}
}
async function disableFileShotDrive() {
if (!isDriveFeatureAvailable()) return;
const letter = getConfiguredDriveLetter();
await stopDriveWatcher();
await unmapDriveLetter(letter);
store.set('drive.enabled', false);
rebuildTrayMenu();
}
function ensureVaultDirs() {
fs.mkdirSync(getVaultFilesDir(), { recursive: true });
fs.mkdirSync(getVaultTmpDir(), { recursive: true });
}
function getVaultItems() {
return store.get('vault.items', []);
}
function setVaultItems(items) {
store.set('vault.items', items);
}
function genId() {
if (crypto.randomUUID) return crypto.randomUUID();
return `${Date.now()}_${crypto.randomBytes(8).toString('hex')}`;
}
function safeStat(p) {
try { return fs.statSync(p); } catch (_) { return null; }
}
/**
* Add a file to the vault with AES-256-GCM encryption.
* Uses password-based encryption with PBKDF2 key derivation.
*/
async function addFileToVault(sourcePath, passphrase) {
ensureVaultDirs();
const st = safeStat(sourcePath);
if (!st || !st.isFile()) return null;
const id = genId();
const name = path.basename(sourcePath);
const storedName = `${id}.fszk`; // Always use .fszk extension for encrypted files
const destPath = path.join(getVaultFilesDir(), storedName);
// Encrypt the file using ZKE format with PASSWORD-BASED encryption
const result = await encryptFileToZkeContainer({
inputPath: sourcePath,
outputPath: destPath,
originalName: name,
mode: 'passphrase', // Use password-based encryption
passphrase: passphrase
});
const encryptedStat = safeStat(destPath);
return {
id,
name,
originalSize: st.size,
size: encryptedStat ? encryptedStat.size : st.size,
addedAt: Date.now(),
localPath: destPath,
sourcePath,
encrypted: true,
encryptionMode: 'passphrase' // Indicate password-based encryption
// Note: No key stored - user must remember password
};
}
function vaultTotalBytes(items) {
return (items || []).reduce((sum, it) => sum + Number(it.size || 0), 0);
}
// ============================================================================
// SECURE SHRED (BEST-EFFORT)
// ============================================================================
function shredPassesForMethod(method) {
const m = String(method || '').toLowerCase();
if (m === 'gutmann') return 35;
if (m === 'dod') return 7;
if (m === 'simple' || m === 'single') return 1;
return 1;
}
function isProbablyDir(p) {
try {
const st = fs.statSync(p);
return st.isDirectory();
} catch (_) {
return false;
}
}
async function listFilesRecursive(rootPath, fileList = []) {
const p = String(rootPath || '');
if (!p) return fileList;
let ents;
try {
ents = await fs.promises.readdir(p, { withFileTypes: true });
} catch (_) {
return fileList;
}
for (const ent of ents) {
const full = path.join(p, ent.name);
try {
if (ent.isDirectory()) {
await listFilesRecursive(full, fileList);
} else if (ent.isFile()) {
fileList.push(full);
}
// Skip symlinks and others
} catch (_) {}
}
return fileList;
}
async function tryRemoveEmptyDirs(rootPath) {
const p = String(rootPath || '');
if (!p) return;
let ents;
try {
ents = await fs.promises.readdir(p, { withFileTypes: true });
} catch (_) {
return;
}
for (const ent of ents) {
if (!ent.isDirectory()) continue;
const full = path.join(p, ent.name);
await tryRemoveEmptyDirs(full);
}
// Now try removing this dir if empty
try {
const left = await fs.promises.readdir(p);
if (left.length === 0) {
await fs.promises.rmdir(p);
}
} catch (_) {}
}
async function overwriteAndDeleteFile(filePath, passes, onProgress) {
const p = String(filePath || '');
if (!p) return;
let st;
try {
st = await fs.promises.stat(p);
} catch (e) {
throw new Error(`Missing file: ${p}`);
}
if (!st.isFile()) return;
// Rename before wipe (best-effort)
let workPath = p;
try {
const dir = path.dirname(p);
const rnd = crypto.randomBytes(12).toString('hex');
const renamed = path.join(dir, rnd);
await fs.promises.rename(p, renamed);
workPath = renamed;
} catch (_) {}
if (passes <= 0) {
await fs.promises.unlink(workPath);
return;
}
const size = Number(st.size || 0);
const chunkSize = 1024 * 1024; // 1MB
const buf = Buffer.allocUnsafe(chunkSize);
const fh = await fs.promises.open(workPath, 'r+');
try {
for (let pass = 1; pass <= passes; pass++) {
let offset = 0;
while (offset < size) {
const len = Math.min(chunkSize, size - offset);
crypto.randomFillSync(buf, 0, len);
await fh.write(buf, 0, len, offset);
offset += len;
}
try { await fh.sync(); } catch (_) {}
if (typeof onProgress === 'function') {
onProgress({ pass, passes });
}
}
} finally {
try { await fh.close(); } catch (_) {}
}
try { await fs.promises.truncate(workPath, 0); } catch (_) {}
await fs.promises.unlink(workPath);
}
function resolveSpecialTargetPaths(targets) {
const t = Array.isArray(targets) ? targets.map(String) : [];
const out = [];
const platform = process.platform;
if (t.includes('downloads')) {
try { out.push(app.getPath('downloads')); } catch (_) {}
}
if (t.includes('temp')) {
try { out.push(app.getPath('temp')); } catch (_) { out.push(os.tmpdir()); }
}
if (t.includes('recycle')) {
if (platform === 'win32') {
// Best-effort: common recycle bin folder (permissions may block)
out.push('C:\\$Recycle.Bin');
} else if (platform === 'darwin') {
out.push(path.join(os.homedir(), '.Trash'));
} else {
out.push(path.join(os.homedir(), '.local', 'share', 'Trash', 'files'));