-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
1384 lines (1209 loc) · 40.7 KB
/
main.js
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
if (require("electron-squirrel-startup")) return;
const { app, BrowserWindow, ipcMain, clipboard, dialog, Menu } = require("electron");
app.setAppUserModelId('com.yuma-dev.clips');
const { setupTitlebar, attachTitlebarToWindow } = require("custom-electron-titlebar/main");
const logger = require('./logger');
const { exec, execFile } = require("child_process");
const util = require("util");
const execPromise = util.promisify(exec);
const { checkForUpdates } = require('./updater');
const isDev = !app.isPackaged;
const path = require("path");
const chokidar = require("chokidar");
const fs = require("fs").promises;
const os = require("os");
const crypto = require("crypto");
const { loadSettings, saveSettings } = require("./settings-manager");
const SteelSeriesProcessor = require('./steelseries-processor');
const readify = require("readify");
const delay = (ms) => new Promise((res) => setTimeout(res, ms));
const DiscordRPC = require('discord-rpc');
const clientId = '1264368321013219449';
const IDLE_TIMEOUT = 5 * 60 * 1000;
const ffmpeg = require('fluent-ffmpeg');
const ffmpegPath = require('ffmpeg-static').replace('app.asar', 'app.asar.unpacked');
const ffprobePath = require('@ffprobe-installer/ffprobe').path.replace('app.asar', 'app.asar.unpacked');
const CONCURRENT_GENERATIONS = 4; // Maximum concurrent FFmpeg processes
const thumbnailQueue = [];
const THUMBNAIL_RETRY_ATTEMPTS = 3;
let isProcessingQueue = false;
let completedThumbnails = 0;
ffmpeg.setFfmpegPath(ffmpegPath);
ffmpeg.setFfprobePath(ffprobePath);
execFile(ffmpegPath, ['-version'], (error, stdout, stderr) => {
if (error) {
logger.error('Error getting ffmpeg version:', error);
} else {
logger.info('FFmpeg version:', stdout);
}
});
function sendLog(window, type, message) {
if (window && !window.isDestroyed()) {
window.webContents.send('log', { type, message });
}
}
// Log ffmpeg version
ipcMain.handle('get-ffmpeg-version', async (event) => {
return new Promise((resolve, reject) => {
execFile(ffmpegPath, ['-version'], (error, stdout, stderr) => {
if (error) {
sendLog(event.sender.getOwnerBrowserWindow(), 'error', `Error getting ffmpeg version: ${error}`);
reject(error);
} else {
sendLog(event.sender.getOwnerBrowserWindow(), 'info', `FFmpeg version: ${stdout}`);
resolve(stdout);
}
});
});
});
let idleTimer;
const THUMBNAIL_CACHE_DIR = path.join(
app.getPath("userData"),
"thumbnail-cache",
);
// Ensure cache directory exists
fs.mkdir(THUMBNAIL_CACHE_DIR, { recursive: true }).catch(logger.error);
let mainWindow;
let settings;
setupTitlebar();
async function createWindow() {
settings = await loadSettings();
setupFileWatcher(settings.clipLocation);
if (settings.enableDiscordRPC) {
initDiscordRPC();
}
mainWindow = new BrowserWindow({
width: 1024,
height: 768,
titleBarStyle: "hidden",
backgroundColor: '#1e1e1e',
autoHideMenuBar: true,
frame: false,
titleBarOverlay: {
color: '#1e1e1e',
symbolColor: '#e0e0e0',
height: 30
},
show: false,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
enableRemoteModule: true
},
});
attachTitlebarToWindow(mainWindow);
mainWindow.loadFile("index.html");
mainWindow.maximize();
Menu.setApplicationMenu(null);
mainWindow.webContents.on('before-input-event', (event, input) => {
if (input.key.toLowerCase() === 'i' && input.control && input.shift) {
mainWindow.webContents.toggleDevTools();
event.preventDefault();
}
});
if (isDev) {
try {
require("electron-reloader")(module, {
debug: true,
watchRenderer: true,
});
} catch (_) {
logger.info("Error");
}
}
// detect idling
mainWindow.on('focus', () => {
clearTimeout(idleTimer);
if (settings.enableDiscordRPC) {
mainWindow.webContents.send('check-activity-state');
}
});
mainWindow.on('blur', () => {
if (settings.enableDiscordRPC) {
idleTimer = setTimeout(() => {
clearDiscordPresence();
}, IDLE_TIMEOUT);
}
});
powerMonitor.on('unlock-screen', () => {
clearTimeout(idleTimer);
if (settings.enableDiscordRPC) {
mainWindow.webContents.send('check-activity-state');
}
});
powerMonitor.on('lock-screen', () => {
if (settings.enableDiscordRPC) {
clearDiscordPresence();
}
});
}
app.whenReady().then(() => {
createWindow();
// Wait a bit for the window to be fully ready before checking updates
setTimeout(() => {
checkForUpdates(mainWindow);
}, 5000);
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit();
});
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
let rpc = null;
let rpcReady = false;
function initDiscordRPC() {
rpc = new DiscordRPC.Client({ transport: 'ipc' });
rpc.on('ready', () => {
logger.info('Discord RPC connected successfully');
rpcReady = true;
updateDiscordPresence('Browsing clips');
});
rpc.login({ clientId }).catch(error => {
logger.error('Failed to initialize Discord RPC:', error);
});
}
function updateDiscordPresence(details, state = null) {
if (!rpcReady || !settings.enableDiscordRPC) {
logger.info('RPC not ready or disabled');
return;
}
const activity = {
details: String(details),
largeImageKey: 'app_logo',
largeImageText: 'Clip Library',
buttons: [{ label: 'View on GitHub', url: 'https://github.com/yuma-dev/clip-library' }]
};
if (state !== null) {
activity.state = String(state);
}
rpc.setActivity(activity).catch(error => {
logger.error('Failed to update Discord presence:', error);
});
}
function clearDiscordPresence() {
if (rpcReady) {
rpc.clearActivity().catch(logger.error);
}
}
ipcMain.handle('update-discord-presence', (event, details, state, startTimestamp) => {
clearTimeout(idleTimer);
updateDiscordPresence(details, state, startTimestamp);
});
ipcMain.handle('toggle-discord-rpc', async (event, enable) => {
settings.enableDiscordRPC = enable;
await saveSettings(settings);
if (enable && !rpc) {
initDiscordRPC();
} else if (!enable && rpc) {
clearDiscordPresence();
rpc.destroy();
rpc = null;
rpcReady = false;
}
});
ipcMain.handle('clear-discord-presence', () => {
clearDiscordPresence();
});
ipcMain.handle('get-settings', () => {
return settings;
});
function generateThumbnailPath(clipPath) {
const hash = crypto.createHash("md5").update(clipPath).digest("hex");
return path.join(THUMBNAIL_CACHE_DIR, `${hash}.jpg`);
}
ipcMain.handle("get-clips", async () => {
const clipsFolder = settings.clipLocation;
const metadataFolder = path.join(clipsFolder, ".clip_metadata");
try {
const result = await readify(clipsFolder, {
type: "raw",
sort: "date",
order: "desc",
});
const clipInfoPromises = result.files
.filter((file) =>
[".mp4", ".avi", ".mov"].includes(
path.extname(file.name).toLowerCase(),
),
)
.map(async (file) => {
const customNamePath = path.join(
metadataFolder,
`${file.name}.customname`,
);
const trimPath = path.join(metadataFolder, `${file.name}.trim`);
let customName;
let isTrimmed = false;
try {
customName = await fs.readFile(customNamePath, "utf8");
} catch (error) {
if (error.code !== "ENOENT")
logger.error("Error reading custom name:", error);
customName = path.basename(file.name, path.extname(file.name));
}
try {
await fs.access(trimPath);
isTrimmed = true;
} catch (error) {
// If trim file doesn't exist, isTrimmed remains false
}
const thumbnailPath = generateThumbnailPath(
path.join(clipsFolder, file.name),
);
return {
originalName: file.name,
customName: customName,
createdAt: file.date.getTime(),
thumbnailPath: thumbnailPath,
isTrimmed: isTrimmed,
};
});
const clipInfos = await Promise.all(clipInfoPromises);
return clipInfos;
} catch (error) {
logger.error("Error reading directory:", error);
return [];
}
});
function setupFileWatcher(clipLocation) {
const watcher = chokidar.watch(clipLocation, {
ignored: /(^|[\/\\])\../, // ignore dotfiles
persistent: true
});
watcher.on('add', (filePath) => {
const ext = path.extname(filePath).toLowerCase();
if (['.mp4', '.avi', '.mov'].includes(ext)) {
const fileName = path.basename(filePath);
mainWindow.webContents.send('new-clip-added', fileName);
}
});
}
ipcMain.handle('get-app-version', () => {
return app.getVersion();
});
ipcMain.handle('get-new-clip-info', async (event, fileName) => {
const filePath = path.join(settings.clipLocation, fileName);
const stats = await fs.stat(filePath);
// Create bare minimum clip info without any trim data
const newClipInfo = {
originalName: fileName,
customName: path.basename(fileName, path.extname(fileName)),
createdAt: stats.birthtimeMs || stats.ctimeMs,
tags: [] // Initialize with empty tags array
};
return newClipInfo;
});
ipcMain.handle("save-custom-name", async (event, originalName, customName) => {
try {
await saveCustomNameData(originalName, customName);
return { success: true, customName };
} catch (error) {
logger.error("Error in save-custom-name handler:", error);
return { success: false, error: error.message };
}
});
ipcMain.handle("get-clip-info", async (event, clipName) => {
const clipPath = path.join(settings.clipLocation, clipName);
const thumbnailPath = generateThumbnailPath(clipPath);
try {
// Try to get metadata from cache first
const metadata = await getThumbnailMetadata(thumbnailPath);
if (metadata && metadata.duration) {
return {
format: {
filename: clipPath,
duration: metadata.duration
}
};
}
// If no cached metadata, get it from ffprobe and cache it
return new Promise((resolve, reject) => {
ffmpeg.ffprobe(clipPath, async (err, info) => {
if (err) reject(err);
else {
// Cache the metadata
const existingMetadata = await getThumbnailMetadata(thumbnailPath) || {};
await saveThumbnailMetadata(thumbnailPath, {
...existingMetadata,
duration: info.format.duration,
timestamp: Date.now()
});
resolve(info);
}
});
});
} catch (error) {
logger.error('Error getting clip info:', error);
throw error;
}
});
ipcMain.handle("get-trim", async (event, clipName) => {
logger.info(`Getting trim data for: ${clipName}`);
const clipsFolder = settings.clipLocation;
const metadataFolder = path.join(clipsFolder, ".clip_metadata");
const trimFilePath = path.join(metadataFolder, `${clipName}.trim`);
try {
const trimData = await fs.readFile(trimFilePath, "utf8");
logger.info(`Found trim data for ${clipName}:`, trimData);
return JSON.parse(trimData);
} catch (error) {
if (error.code === "ENOENT") {
logger.info(`No trim data found for ${clipName}`);
return null;
}
logger.error(`Error reading trim data for ${clipName}:`, error);
throw error;
}
});
ipcMain.handle("save-speed", async (event, clipName, speed) => {
const clipsFolder = settings.clipLocation;
const metadataFolder = path.join(clipsFolder, ".clip_metadata");
await ensureDirectoryExists(metadataFolder);
const speedFilePath = path.join(metadataFolder, `${clipName}.speed`);
try {
await writeFileAtomically(speedFilePath, speed.toString());
logger.info(`Speed saved successfully for ${clipName}: ${speed}`);
return { success: true };
} catch (error) {
logger.error(`Error saving speed for ${clipName}:`, error);
return { success: false, error: error.message };
}
});
ipcMain.handle("get-speed", async (event, clipName) => {
const clipsFolder = settings.clipLocation;
const metadataFolder = path.join(clipsFolder, ".clip_metadata");
const speedFilePath = path.join(metadataFolder, `${clipName}.speed`);
try {
const speedData = await fs.readFile(speedFilePath, "utf8");
const parsedSpeed = parseFloat(speedData);
if (isNaN(parsedSpeed)) {
logger.warn(`Invalid speed data for ${clipName}, using default`);
return 1;
}
return parsedSpeed;
} catch (error) {
if (error.code === "ENOENT") {
logger.info(`No speed data found for ${clipName}, using default`);
return 1; // Default speed if not set
}
logger.error(`Error reading speed for ${clipName}:`, error);
throw error;
}
});
ipcMain.handle("save-volume", async (event, clipName, volume) => {
const clipsFolder = settings.clipLocation;
const metadataFolder = path.join(clipsFolder, ".clip_metadata");
await ensureDirectoryExists(metadataFolder);
const volumeFilePath = path.join(metadataFolder, `${clipName}.volume`);
try {
await writeFileAtomically(volumeFilePath, volume.toString());
logger.info(`Volume saved successfully for ${clipName}: ${volume}`);
return { success: true };
} catch (error) {
logger.error(`Error saving volume for ${clipName}:`, error);
return { success: false, error: error.message };
}
});
ipcMain.handle("get-volume", async (event, clipName) => {
const clipsFolder = settings.clipLocation;
const metadataFolder = path.join(clipsFolder, ".clip_metadata");
const volumeFilePath = path.join(metadataFolder, `${clipName}.volume`);
try {
const volumeData = await fs.readFile(volumeFilePath, "utf8");
const parsedVolume = parseFloat(volumeData);
if (isNaN(parsedVolume)) {
logger.warn(`Invalid volume data for ${clipName}, using default`);
return 1;
}
return parsedVolume;
} catch (error) {
if (error.code === "ENOENT") {
logger.info(`No volume data found for ${clipName}, using default`);
return 1; // Default volume if not set
}
logger.error(`Error reading volume for ${clipName}:`, error);
throw error;
}
});
ipcMain.handle("get-clip-tags", async (event, clipName) => {
const clipsFolder = settings.clipLocation;
const metadataFolder = path.join(clipsFolder, ".clip_metadata");
const tagsFilePath = path.join(metadataFolder, `${clipName}.tags`);
try {
const tagsData = await fs.readFile(tagsFilePath, "utf8");
return JSON.parse(tagsData);
} catch (error) {
if (error.code === "ENOENT") {
return []; // No tags file exists
}
logger.error("Error reading tags:", error);
return [];
}
});
ipcMain.handle("save-clip-tags", async (event, clipName, tags) => {
const clipsFolder = settings.clipLocation;
const metadataFolder = path.join(clipsFolder, ".clip_metadata");
const tagsFilePath = path.join(metadataFolder, `${clipName}.tags`);
try {
await fs.writeFile(tagsFilePath, JSON.stringify(tags));
return { success: true };
} catch (error) {
logger.error("Error saving tags:", error);
return { success: false, error: error.message };
}
});
ipcMain.handle("load-global-tags", async () => {
const tagsFilePath = path.join(app.getPath("userData"), "global_tags.json");
try {
const tagsData = await fs.readFile(tagsFilePath, "utf8");
return JSON.parse(tagsData);
} catch (error) {
if (error.code === "ENOENT") {
return []; // No tags file exists yet
}
logger.error("Error reading global tags:", error);
return [];
}
});
ipcMain.handle("save-global-tags", async (event, tags) => {
const tagsFilePath = path.join(app.getPath("userData"), "global_tags.json");
try {
await fs.writeFile(tagsFilePath, JSON.stringify(tags));
return { success: true };
} catch (error) {
logger.error("Error saving global tags:", error);
return { success: false, error: error.message };
}
});
async function saveCustomNameData(clipName, customName) {
const clipsFolder = settings.clipLocation;
const metadataFolder = path.join(clipsFolder, ".clip_metadata");
await ensureDirectoryExists(metadataFolder);
const customNameFilePath = path.join(
metadataFolder,
`${clipName}.customname`,
);
try {
await writeFileAtomically(customNameFilePath, customName);
logger.info(`Custom name saved successfully for ${clipName}`);
} catch (error) {
logger.error(`Error saving custom name for ${clipName}:`, error);
throw error;
}
}
async function saveTrimData(clipName, trimData) {
const clipsFolder = settings.clipLocation;
const metadataFolder = path.join(clipsFolder, ".clip_metadata");
await ensureDirectoryExists(metadataFolder);
const trimFilePath = path.join(metadataFolder, `${clipName}.trim`);
try {
await writeFileAtomically(trimFilePath, JSON.stringify(trimData));
logger.info(`Trim data saved successfully for ${clipName}`);
} catch (error) {
logger.error(`Error saving trim data for ${clipName}:`, error);
throw error;
}
}
async function ensureDirectoryExists(dirPath) {
try {
await fs.access(dirPath);
} catch (error) {
if (error.code === "ENOENT") {
await fs.mkdir(dirPath, { recursive: true });
} else {
throw error;
}
}
}
async function ensureDirectoryExists(dirPath) {
try {
await fs.access(dirPath);
} catch (error) {
if (error.code === "ENOENT") {
await fs.mkdir(dirPath, { recursive: true });
} else {
throw error;
}
}
}
async function writeFileWithRetry(filePath, data, retries = 3) {
for (let attempt = 0; attempt < retries; attempt++) {
try {
await fs.writeFile(filePath, data, { flag: "w" });
return;
} catch (error) {
if (error.code === "EPERM" || error.code === "EACCES") {
if (attempt === retries - 1) throw error;
await new Promise((resolve) => setTimeout(resolve, 100)); // Wait 100ms before retry
} else {
throw error;
}
}
}
}
async function writeFileAtomically(filePath, data) {
const tempPath = `${filePath}.tmp`;
const dir = path.dirname(filePath);
try {
// Ensure the directory exists
await fs.mkdir(dir, { recursive: true });
await writeFileWithRetry(tempPath, data);
await fs.rename(tempPath, filePath);
} catch (error) {
logger.error(`Error in writeFileAtomically: ${error.message}`);
// If rename fails, try direct write as a fallback
await writeFileWithRetry(filePath, data);
} finally {
try {
await fs.unlink(tempPath);
} catch (error) {
// Ignore error if temp file doesn't exist
if (error.code !== "ENOENT")
logger.error(`Error deleting temp file: ${error.message}`);
}
}
}
ipcMain.handle("get-clip-location", () => {
return settings.clipLocation;
});
ipcMain.handle("set-clip-location", async (event, newLocation) => {
settings.clipLocation = newLocation;
await saveSettings(settings);
return settings.clipLocation;
});
ipcMain.handle("open-folder-dialog", async () => {
const result = await dialog.showOpenDialog(mainWindow, {
properties: ["openDirectory"],
});
if (!result.canceled && result.filePaths.length > 0) {
return result.filePaths[0];
}
return null;
});
// In main.js, modify the 'get-thumbnail-path' handler
ipcMain.handle("get-thumbnail-path", async (event, clipName) => {
const clipPath = path.join(settings.clipLocation, clipName);
const thumbnailPath = generateThumbnailPath(clipPath);
try {
await fs.access(thumbnailPath);
return thumbnailPath;
} catch (error) {
// Instead of throwing an error, return null if the thumbnail doesn't exist
return null;
}
});
async function getTrimData(clipName) {
const clipsFolder = settings.clipLocation;
const metadataFolder = path.join(clipsFolder, ".clip_metadata");
const trimFilePath = path.join(metadataFolder, `${clipName}.trim`);
try {
const trimData = await fs.readFile(trimFilePath, "utf8");
return JSON.parse(trimData);
} catch (error) {
if (error.code === "ENOENT") return null;
throw error;
}
}
async function validateThumbnail(clipName, thumbnailPath) {
const EPSILON = 0.001;
try {
// First check if thumbnail exists
try {
await fs.access(thumbnailPath);
} catch (error) {
logger.info(`${clipName}: No thumbnail file exists`);
return false;
}
// Then check if metadata exists
try {
const metadata = await getThumbnailMetadata(thumbnailPath);
if (!metadata) {
return false;
}
const currentTrimData = await getTrimData(clipName);
if (currentTrimData) {
const isValid = Math.abs(metadata.startTime - currentTrimData.start) < EPSILON;
/*
logger.info(`${clipName}: Validating trim data:`, {
metadataStartTime: metadata.startTime,
trimStartTime: currentTrimData.start,
diff: Math.abs(metadata.startTime - currentTrimData.start),
isValid
});
*/
return isValid;
}
if (metadata.duration) {
const expectedStartTime = metadata.duration > 40 ? metadata.duration / 2 : 0;
const isValid = Math.abs(metadata.startTime - expectedStartTime) < 0.1;
if (!isValid) {
logger.info(`${clipName}: Start time mismatch - Metadata: ${metadata.startTime}, Expected: ${expectedStartTime}`);
}
return isValid;
}
logger.info(`${clipName}: Missing duration in metadata`);
return false;
} catch (error) {
logger.info(`${clipName}: No metadata file exists`);
return false;
}
} catch (error) {
logger.error(`Error validating thumbnail for ${clipName}:`, error);
return false;
}
}
async function saveThumbnailMetadata(thumbnailPath, metadata) {
const metadataPath = thumbnailPath + '.meta';
await fs.writeFile(metadataPath, JSON.stringify(metadata));
}
async function getThumbnailMetadata(thumbnailPath) {
try {
const metadataPath = thumbnailPath + '.meta';
const data = await fs.readFile(metadataPath, 'utf8');
return JSON.parse(data);
} catch (error) {
return null;
}
}
async function processQueue() {
if (isProcessingQueue || thumbnailQueue.length === 0) return;
isProcessingQueue = true;
completedThumbnails = 0;
try {
while (thumbnailQueue.length > 0) {
const batch = thumbnailQueue.slice(0, CONCURRENT_GENERATIONS);
if (batch.length === 0) break;
const totalToProcess = batch[0].totalToProcess;
await Promise.all(batch.map(async ({ clipName, event, attempts = 0 }) => {
const clipPath = path.join(settings.clipLocation, clipName);
const thumbnailPath = generateThumbnailPath(clipPath);
try {
const isValid = await validateThumbnail(clipName, thumbnailPath);
if (!isValid) {
if (attempts >= THUMBNAIL_RETRY_ATTEMPTS) {
logger.error(`Failed to generate thumbnail for ${clipName} after ${THUMBNAIL_RETRY_ATTEMPTS} attempts`);
event.sender.send("thumbnail-generation-failed", {
clipName,
error: "Maximum retry attempts reached"
});
return;
}
// Get video info first
const info = await new Promise((resolve, reject) => {
ffmpeg.ffprobe(clipPath, (err, metadata) => {
if (err) reject(err);
else resolve(metadata);
});
});
const trimData = await getTrimData(clipName);
const duration = info.format.duration;
const startTime = trimData ? trimData.start : (duration > 40 ? duration / 2 : 0);
await new Promise((resolve, reject) => {
ffmpeg(clipPath)
.screenshots({
timestamps: [startTime],
filename: path.basename(thumbnailPath),
folder: path.dirname(thumbnailPath),
size: '640x360'
})
.on('end', resolve)
.on('error', (err) => {
if (attempts < THUMBNAIL_RETRY_ATTEMPTS) {
thumbnailQueue.push({ clipName, event, attempts: attempts + 1 });
}
reject(err);
});
});
await saveThumbnailMetadata(thumbnailPath, {
startTime,
duration,
clipName,
timestamp: Date.now()
});
}
completedThumbnails++;
// Send progress update
event.sender.send("thumbnail-progress", {
current: completedThumbnails,
total: totalToProcess,
clipName
});
} catch (error) {
logger.error(`Error processing thumbnail for ${clipName}:`, error);
if (attempts >= THUMBNAIL_RETRY_ATTEMPTS) {
event.sender.send("thumbnail-generation-failed", {
clipName,
error: error.message
});
}
}
}));
thumbnailQueue.splice(0, batch.length);
await new Promise(resolve => setTimeout(resolve, 100));
}
} finally {
isProcessingQueue = false;
// Send completion event if queue is empty
if (thumbnailQueue.length === 0) {
event.sender.send("thumbnail-generation-complete");
}
}
}
app.on('before-quit', () => {
// Clear the queue
thumbnailQueue.length = 0;
});
ipcMain.handle("regenerate-thumbnail-for-trim", async (event, clipName, startTime) => {
const clipPath = path.join(settings.clipLocation, clipName);
const thumbnailPath = generateThumbnailPath(clipPath);
try {
// Generate new thumbnail at trim point
await new Promise((resolve, reject) => {
ffmpeg(clipPath)
.screenshots({
timestamps: [startTime],
filename: path.basename(thumbnailPath),
folder: path.dirname(thumbnailPath),
size: '640x360'
})
.on('end', resolve)
.on('error', reject);
});
// Save new metadata
await saveThumbnailMetadata(thumbnailPath, {
startTime,
clipName,
timestamp: Date.now()
});
return { success: true, thumbnailPath };
} catch (error) {
logger.error('Error regenerating thumbnail:', error);
return { success: false, error: error.message };
}
});
// In main.js
ipcMain.handle('save-settings', async (event, newSettings) => {
try {
await saveSettings(newSettings);
settings = newSettings; // Update main process settings
return newSettings;
} catch (error) {
logger.error('Error in save-settings handler:', error);
throw error;
}
});
ipcMain.handle("generate-thumbnails-progressively", async (event, clipNames) => {
let clipsNeedingGeneration = [];
// First validate all thumbnails without showing progress
for (const clipName of clipNames) {
const clipPath = path.join(settings.clipLocation, clipName);
const thumbnailPath = generateThumbnailPath(clipPath);
try {
const isValid = await validateThumbnail(clipName, thumbnailPath);
if (!isValid) {
clipsNeedingGeneration.push(clipName);
}
} catch (error) {
logger.error(`Error validating thumbnail for ${clipName}:`, error);
clipsNeedingGeneration.push(clipName);
}
}
// Only show progress and send events if we actually need to generate thumbnails
if (clipsNeedingGeneration.length > 0) {
totalThumbnailsToProcess = clipsNeedingGeneration.length;
completedThumbnails = 0;
// Send validation start BEFORE adding to queue
event.sender.send("thumbnail-validation-start", {
total: totalThumbnailsToProcess
});
// Clear existing queue
thumbnailQueue.length = 0;
// Add only clips that need generation to the queue
thumbnailQueue.push(...clipsNeedingGeneration.map(clipName => ({
clipName,
event,
totalToProcess: totalThumbnailsToProcess
})));
if (!isProcessingQueue) {
processQueue();
}
}
return {
needsGeneration: clipsNeedingGeneration.length,
total: clipNames.length
};
});
ipcMain.handle("generate-thumbnail", async (event, clipName) => {
const clipPath = path.join(settings.clipLocation, clipName);
const thumbnailPath = generateThumbnailPath(clipPath);
try {
// Check if cached thumbnail exists
await fs.access(thumbnailPath);
return thumbnailPath;
} catch (error) {
logger.info(`Generating new thumbnail for ${clipName}`);
// If thumbnail doesn't exist, generate it
return new Promise((resolve, reject) => {
ffmpeg(clipPath)
.screenshots({
count: 1,
timemarks: ["00:00:00"],
folder: path.dirname(thumbnailPath),
filename: path.basename(thumbnailPath),
size: "640x360",
})
.on("end", () => {
logger.info(`Thumbnail generated successfully for ${clipName}`);
resolve(thumbnailPath);
})
.on("error", (err) => {
logger.error(`Error generating thumbnail for ${clipName}:`, err);
reject(err);
});
});
}
});
ipcMain.handle("save-trim", async (event, clipName, start, end) => {
try {
await saveTrimData(clipName, { start, end });
return { success: true };
} catch (error) {
logger.error("Error in save-trim handler:", error);