-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.mjs
More file actions
1334 lines (1195 loc) · 51.8 KB
/
main.mjs
File metadata and controls
1334 lines (1195 loc) · 51.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
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 { app, BrowserWindow, ipcMain, Menu, dialog } from 'electron';
import path from 'path';
import fs from 'fs';
import { exec } from 'child_process';
import i18next from 'i18next';
import Backend from 'i18next-fs-backend';
import { exiftool } from 'exiftool-vendored';
import { sortImagesByCaptureTime } from './js/imageHelper.js';
import { sanitize, isNumber } from './js/generalHelpers.js';
import { loadSettings, saveSettings, openSettingsInSystemEditor } from './js/settingsHelper.js';
import { OllamaClient } from './aitagging/OllamaClient.js';
import { reverseGeocodeToXmp } from './js/nominatim.js'
import { isValidLatLng, dmsToDecimal } from './js/TrackAndGpsHandler.js';
const isDev = !app.isPackaged;
// write to a log file if the exe is used (production only)
if (!isDev) {
const logFilePath = path.join(app.getPath('userData'), 'geotagger.log');
let logStream;
try {
logStream = fs.createWriteStream(logFilePath, { flags: 'a' });
} catch (err) {
try {
process.stderr.write(
`[LOG-INIT ERROR] ${new Date().toISOString()} Failed to create log file at "${logFilePath}": ${String(err)}\n`
);
} catch {}
logStream = null;
}
if (logStream) {
// Minimal: direkten Override testen
const origLog = console.log;
console.log = (...args) => {
try {
logStream.write('[LOG] ' + args.join(' ') + '\n');
} catch (e) {
try {
process.stderr.write(
`[LOG-WRITE ERROR] ${new Date().toISOString()} ${String(e)}\n`
);
} catch {}
try { origLog(...args); } catch {}
}
};
app.on('will-quit', () => {
try { logStream.end(); } catch {}
});
}
}
let systemLanguage = 'en';
let win; // Variable für das Hauptfenster
let settings = {}; // Variable zum Speichern der Einstellungen
let extensions = ['jpg', 'webp', 'avif', 'heic', 'tiff', 'dng', 'nef', 'cr3']; // supported image extensions as default
let exiftoolPath = 'exiftool'; // system exiftool must be in PATH for this to work! (only for development!)
if (app.isPackaged) {
exiftoolPath = path.join(
process.resourcesPath,
'app.asar.unpacked',
'node_modules',
'exiftool-vendored.exe',
'bin',
process.platform === 'win32' ? 'exiftool.exe' : 'exiftool'
);
}
let exiftoolAvailable = false;
// Basisverzeichnis der App
const appRoot = app.getAppPath();
const localesPath = path.join(appRoot, 'locales');
const settingsFilePath = path.join(app.getPath('userData'), 'user-settings.json');
const ollamaConfigFilePath = path.join(app.getPath('userData'), 'ollama_config.json');
const ollamaPromptFilePath = path.join(app.getPath('userData'), 'prompt.txt');
const logFilePath = path.join(app.getPath('userData'), 'geotagger.log');
// Settings direkt beim Start laden
try {
if (fs.existsSync(settingsFilePath)) {
settings = JSON.parse(fs.readFileSync(settingsFilePath, 'utf8'));
if (settings.extensions && Array.isArray(settings.extensions)) extensions = settings.extensions;
console.log('Settings loaded from:', settingsFilePath);
}
} catch (err) {
console.log('Failed to load settings:', err);
}
// sharp availabability check
let sharpAvailable = false;
let sharp;
try {
sharp = (await import('sharp')).default;
sharpAvailable = true;
} catch (err) {
// das logging funktioniert hier nicht
console.log('[WARN] Sharp not available, skipping thumbnail rotation: ', err);
}
// AI Tagging with Ollama: check availability at startup
let ollamaAvailable = { status: false, model: '' };
let ollamaClient;
/** Hauptstart */
app.whenReady().then(async () => {
try {
exiftoolAvailable = await checkExiftoolAvailable(exiftoolPath);
console.log(`Exiftool available: ${exiftoolAvailable} from path: ${exiftoolPath}`);
} catch (err) {
console.log('Failed to check exiftool availability:', err);
console.log(`Using exiftool path: ${exiftoolPath}`);
}
try {
ollamaAvailable = await checkOllamaAvailable('ollama_config.json', 'prompt.txt');
//console.log(`Ollama available: ${ollamaAvailable.status} with model: ${ollamaAvailable.model}`);
} catch (err) {
console.log('Failed to check Ollama availability:', err);
}
// i18next initialisieren. i18next prevents XSS: https://www.i18next.com/translation-function/interpolation?utm_source=chatgpt.com
// So, no further sanitizing is done here and not in render.js.
systemLanguage = (app.getLocale() || 'en').split('-')[0];
try {
await i18next.use(Backend).init({
lng: systemLanguage,
fallbackLng: 'en',
backend: { loadPath: path.join(localesPath, '{{lng}}', 'translation.json') },
});
} catch (err) {
console.log('Error initializing i18next:', err);
// Fallback auf Englisch
try {
await i18next.init({ lng: 'en', fallbackLng: 'en' });
} catch (err2) {
console.log('Fallback i18next init failed:', err2);
}
}
if (win && !win.isDestroyed()) return;
createWindow();
if (win) {
win.on('closed', () => {
win = null;
});
}
setupMenu(i18next.t.bind(i18next));
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('before-quit', () => {
win = null;
});
/**
* Setup the main menu for the application.
* @param {function} t - The translation function for i18next.
* @returns void
*/
function setupMenu(t) {
const menuTemplate = [
{
label: t('file'),
submenu: [
{ label: t('reload'), role: 'reload' }, // this is required just for testing
{ label: t('reloadData'),
click: async () => {
if (!win || !settings.imagePath) {
console.warn('No image path set; reloadData skipped');
return;
}
reloadImageData(settings);
}
},
{
label: t('Open') + ' user-settings.json',
click: async () => {
try {
const result = openSettingsInSystemEditor(settingsFilePath);
// openPath gibt einen leeren String zurück, wenn ok; sonst Fehlermeldung als Text
if (result) {
dialog.showErrorBox(t('Could not open file'), result);
}
} catch (e) {
dialog.showErrorBox(t('error'), String(e));
}
}
},
{
label: t('Open') + ' ollama-config.json',
click: async () => {
try {
const result = openSettingsInSystemEditor(ollamaConfigFilePath);
// openPath gibt einen leeren String zurück, wenn ok; sonst Fehlermeldung als Text
if (result) {
dialog.showErrorBox(t('Could not open file'), result);
}
} catch (e) {
dialog.showErrorBox(t('error'), String(e));
}
}
},
{
label: t('Open') + ' prompt.txt',
click: async () => {
try {
const result = openSettingsInSystemEditor(ollamaPromptFilePath);
// openPath gibt einen leeren String zurück, wenn ok; sonst Fehlermeldung als Text
if (result) {
dialog.showErrorBox(t('Could not open file'), result);
}
} catch (e) {
dialog.showErrorBox(t('error'), String(e));
}
}
},
{
label: t('Open') + ' geotagger.log',
click: async () => {
try {
const result = openSettingsInSystemEditor(logFilePath);
// openPath gibt einen leeren String zurück, wenn ok; sonst Fehlermeldung als Text
if (result) {
dialog.showErrorBox(t('Could not open file'), result);
}
} catch (e) {
dialog.showErrorBox(t, String(e));
}
}
},
{ label: t('quit'), role: 'quit' }
]
},
{
label: t('gpxTrack'),
submenu: [
{
label: t('openGpxFile'),
click: async () => {
const { canceled, filePaths } = await dialog.showOpenDialog({
title: t('selectGpxFileTitle'),
filters: [{ name: t('gpxFiles'), extensions: ['gpx'] }], // do not puzzle with variable 'extensions' here!
properties: ['openFile']
});
if (!canceled && filePaths.length > 0) {
const gpxPath = filePaths[0];
console.log(t('gpxPath'), gpxPath);
settings.gpxPath = gpxPath;
// set the path to the icons for the map, which is required for leaflet map to show the icons on the track correctly.
settings.iconPath = appRoot;
sendToRenderer('gpx-data', gpxPath);
saveSettings(settingsFilePath, settings);
// reload the data
if (settings.imagePath && settings.imagePath.length > 3) {
reloadImageData(settings);
}
}
}
},
{
label: t('clearGpxFile'),
click: () => {
settings.gpxPath = '';
settings.iconPath = appRoot; // set the path to the icons for the map
sendToRenderer('clear-gpx');
saveSettings(settingsFilePath, settings);
}
}
]
},
{
label: t('imageFolder'),
submenu: [
{
label: t('selectFolder'),
click: async () => {
const { canceled, filePaths } = await dialog.showOpenDialog({
title: t('selectImageFolderTitle'),
properties: ['openDirectory']
});
if (!canceled && filePaths.length > 0) {
const imagePath = filePaths[0];
console.log(t('imagePath'), imagePath);
settings.imagePath = imagePath;
settings.iconPath = appRoot;
saveSettings(settingsFilePath, settings);
// read images from the folder if this is possible in the renderer process
sendToRenderer('image-loading-started', imagePath);
// Vor dem Aufruf von readImagesFromFolder
const startTime = Date.now();
console.log('Start reading images from folder at:', new Date(startTime).toLocaleString());
let allImages = await readImagesFromFolder(imagePath, extensions);
// Endzeit und Dauer berechnen:
const endTime = Date.now();
console.log('Finished reading images at:', new Date(endTime).toLocaleString());
console.log('Duration (ms):', endTime - startTime);
// send the images to the renderer process
sendToRenderer('set-image-path', imagePath, allImages);
}
}
},
{
label: t('clearImageFolder'),
click: () => {
settings.imagePath = '';
settings.iconPath = appRoot;
sendToRenderer('clear-image-path');
saveSettings(settingsFilePath, settings);
}
}
]
},
isDev && {
label: t('development'),
submenu: [
{
label: t('openDevTools'),
role: 'toggleDevTools',
accelerator: 'F12'
}
]
}
].filter(Boolean);
const menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);
}
/**
* Creates and configures the main Electron browser window for the application.
* Loads user settings, sets up window size and position, and initializes IPC handlers
* for UI events (resize, move, sidebar widths, bar sizes, image filter updates,
* exit with unsaved changes, save metadata, geotag image with exifTool).
* Loads translations and passes them to the renderer process.
* Loads images from the last used image folder (if available) extracts metadata and sends them to the renderer.
* Loads last used GPX file (if available) and sends it to the renderer.
*
* **Global Variables Used/Modified:**
* - `settings` (object): Stores user/application settings and is updated/saved during window events.
* - `win` (BrowserWindow): Stores the reference to the main window.
* - `extensions` (array): Supported image file extensions, used for image loading.
* - `settingsFilePath` (string): Path to the JSON file where settings are saved/loaded.
*
* @function createWindow
* @global {object} settings, settingsFilePath, appRoot, win
* @returns {void}
*/
function createWindow() {
settings = loadSettings(appRoot, settingsFilePath);
settings.iconPath = appRoot;
win = new BrowserWindow({
width: settings.width || 800,
height: settings.height || 600,
webPreferences: {
preload: path.join(appRoot, './build/preload.bundle.js'),
nodeIntegration: false,
contextIsolation: true,
webSecurity: true // aktiviert Standard-Sicherheitsrichtlinien:
//sandbox: true,
//enableRemoteModule: false
}
});
win.loadFile('index.html');
if (isDev) {
//win.webContents.openDevTools();
}
win.webContents.on('did-finish-load', () => {
// Send the saved settings to the renderer process
let translation = i18next.getDataByLanguage(systemLanguage)?.translation || {};
// append the translation object to the settings object
settings.translation = translation;
settings.lng = systemLanguage;
sendToRenderer('load-settings', settings);
if (settings.imagePath && fs.existsSync(settings.imagePath)) {
sendToRenderer('image-loading-started', settings.imagePath);
// Vor dem Aufruf von readImagesFromFolder
const startTime = Date.now();
console.log('Start reading images from folder at:', new Date(startTime).toLocaleString());
readImagesFromFolder(settings.imagePath, extensions).then(allImages => {
sendToRenderer('set-image-path', settings.imagePath, allImages);
const endTime = Date.now();
console.log('Finished reading images at:', new Date(endTime).toLocaleString());
console.log('Duration (ms):', endTime - startTime);
});
}
});
win.on('resize', () => {
let [width, height] = win.getSize();
settings.width = width;
settings.height = height;
saveSettings(settingsFilePath, settings);
});
win.on('move', () => {
let [x, y] = win.getPosition();
settings.x = x;
settings.y = y;
saveSettings(settingsFilePath, settings);
});
ipcMain.on('update-bars-size', (event, { topBarHeight, bottomBarHeight }) => {
settings.topBarHeight = topBarHeight;
settings.bottomBarHeight = bottomBarHeight;
saveSettings(settingsFilePath, settings);
});
ipcMain.on('update-sidebar-width', (event, { leftSidebarWidth, rightSidebarWidth }) => {
settings.leftSidebarWidth = leftSidebarWidth;
settings.rightSidebarWidth = rightSidebarWidth;
saveSettings(settingsFilePath, settings);
});
ipcMain.on('update-image-filter', (event, newSettings) => {
settings.imageFilter = newSettings.imageFilter;
settings.skipImagesWithGPS = newSettings.skipImagesWithGPS;
settings.ignoreGPXDate = newSettings.ignoreGPXDate;
settings.cameraModels = newSettings.cameraModels;
settings.timeDevSetting = newSettings.timeDevSetting;
saveSettings(settingsFilePath, settings);
});
ipcMain.on('update-map-settings', (event, newSettings) => {
if (newSettings.map.mapselector) {
settings.map.mapselector = newSettings.map.mapselector;
}
settings.map.mapcenter = newSettings.map.mapcenter;
settings.map.zoom = newSettings.map.zoom;
saveSettings(settingsFilePath, settings);
});
ipcMain.on('exit-with-unsaved-changes', (event, allImages) => {
const options = {
type: 'question',
buttons: [i18next.t('save'), i18next.t('discard')], // ['Save', 'Discard'],
defaultId: 0,
title: i18next.t('unsavedChanges'), //'Unsaved Changes',
message: i18next.t('unsavedChangesMessage'), //'You have unsaved changes. Do you want to save them?',
};
dialog.showMessageBox(win, options).then((response) => {
if (response.response === 0) { // 'Save' button
writeMetaData(allImages).then(() => {
console.log('exit-with-unsaved-changes: Changes saved.');
app.exit();
app.quit();
});
} else {
// 'Discard' button, do nothing an quit. The changes will be lost!
console.log('exit-with-unsaved-changes: Changes skipped.');
app.exit();
app.quit();
}
});
})
ipcMain.handle('save-meta-to-image', async (event, allImages) => {
if (!Array.isArray(allImages)) {
return { success: false, error: 'Invalid data format' };
}
await writeMetaData(allImages, event.sender);
return 'done';
});
ipcMain.handle('geotag-exiftool', async (event, data) => {
const { gpxPath, imagePath, options } = data;
// check if paths to files are valid
if (!fs.existsSync(gpxPath)) {
dialog.showErrorBox(i18next.t('GpxFileNotFound'), i18next.t('FileNotFoundMessage', { gpxPath }) );
return { success: false, error: i18next.t('GpxFileNotFound') };
}
if (!fs.existsSync(imagePath)) {
dialog.showErrorBox(i18next.t('ImageFileNotFound'), i18next.t('FileNotFoundMessage', { gpxPath }) );
return { success: false, error: i18next.t('ImageFileNotFound') };
}
if (exiftoolAvailable) {
return await geotagImageExiftool(gpxPath, imagePath, options);
} else {
dialog.showErrorBox(i18next.t('NoExiftool'), i18next.t('exiftoolNotFound') );
console.log('Exiftool is not installed or not in PATH.');
return { success: false, error: i18next.t('exiftoolNotAvailable') };
}
});
ipcMain.on('main-reload-data', (event, settings, lastImage ) => {
reloadImageData(settings, lastImage);
});
ipcMain.handle('ai-tagging-status', async (event) => {
return { ollamaAvailable };
});
ipcMain.handle('ai-tagging-start', async (event, data) => {
const { imagePath, captureDate, imageMeta, location } = data;
if (!fs.existsSync(imagePath)) {
dialog.showErrorBox(i18next.t('ImageFileNotFound'), i18next.t('FileNotFoundMessage', { gpxPath }) );
return { success: false, error: i18next.t('ImageFileNotFound') };
}
let geoLocationInfo = '';
if ( location === 'unknown') {
geoLocationInfo = 'No Location: ';
} else {
geoLocationInfo = location;
}
if (ollamaAvailable.status) {
let aiResult = await ollamaClient.generate(imagePath, captureDate, imageMeta, geoLocationInfo);
if (aiResult && aiResult.success) {
return {
'success': aiResult.success,
'imagePath': imagePath,
'location': geoLocationInfo,
'Title': aiResult.data.title || '',
'Description': aiResult.data.description || '',
'Keywords': aiResult.data.keywords || '', // Tags must be a comma-separated string for exiftool to write them correctly to the metadata. The AI model should generate the tags in this format as well, so that no further processing is required here. Security: Be cautious when writing AI-generated content to image metadata, especially if it includes user-generated input. Consider implementing validation and sanitization of the AI output before writing it to the metadata to prevent potential security issues or injection attacks.
};
} else {
console.log("Unexpected AI result format: ", aiResult);
return { success: false, error: 'Unexpected AI result format' };
}
} else {
dialog.showErrorBox(i18next.t('NoAITool'), i18next.t('AIToolNotFound') );
console.log('AI-Tool (Ollama) is not available.');
return { success: false, error: i18next.t('AIToolNotAvailable') };
}
});
ipcMain.handle('geocoding-start', async (event, data) => {
const { imagePath, imageMeta, location } = data;
if (!fs.existsSync(imagePath)) {
dialog.showErrorBox(i18next.t('ImageFileNotFound'), i18next.t('FileNotFoundMessage', { gpxPath }) );
return { success: false, error: i18next.t('ImageFileNotFound') };
}
// delete the location info
if (!isNumber(imageMeta.lat) || !isNumber(imageMeta.lng)) {
return {
'success': true,
'imagePath': imagePath,
'location': 'unknown',
'City': '',
'State': '',
'Country':''
};
} else {
let result = await reverseGeocodeToXmp(imageMeta.lat, imageMeta.lng);
if (!result) {
dialog.showErrorBox(i18next.t('GeocodingFailed'), i18next.t('GeocodingFailedMessage') );
return { success: false, error: i18next.t('GeocodingFailed') };
}
result.State = result['Province-State'];
let geolocation = `${result.City}, ${result.State}, ${result.Country}`;
return {
'success': true,
'imagePath': imagePath,
'location': geolocation,
'City': result.City,
'State': result.State,
'Country': result.Country
};
}
});
}
// ---- helper functions for the main process ----
// Mind: The following functions can only be called from the main process and so
// can't be move to a separate file(s). This is due to restrictions of electron, node.js runtime calls or whatever.
/**
* Sends a message to the renderer process with the given channel and arguments.
* If the renderer is not available (e.g., it has been closed or has not been created yet),
* a warning will be logged to the console.
* @param {string} channel - the channel to send the message to
* @param {...any} args - the arguments to send to the renderer
* @global {BrowserWindow} win
*
*/
function sendToRenderer(channel, ...args) {
if (win && !win.isDestroyed() && win.webContents) {
win.webContents.send(channel, ...args);
} else {
console.warn('Renderer not available:', channel);
}
}
/**
* Reads all image files from a folder, extracts EXIF metadata, and returns an array of image data objects.
* Supported extensions are filtered by the provided array.
* The returned objects contain relevant EXIF fields and file information.
* Images are sorted by their capture time (DateTimeOriginal).
* Uses exiftool-vendored for fast, concurrent metadata extraction.
*
* @async
* @function readImagesFromFolder
* @param {string} folderPath - Absolute path to the folder containing images.
* @param {string[]} extensions - Array of allowed file extensions (e.g. ['jpg', 'cr3']).
* @global {object} exiftool : singleton from exiftool-vendored
* @global {object} fs
* @global {object} path
*
* @returns {Promise<ImageMeta[]>} Resolves with an array of image metadata objects.
* @throws Will log errors to the console if reading or parsing fails.
*/
async function readImagesFromFolder(folderPath, extensions) {
/**
* @typedef {Object} ImageMeta
* @property {string|{rawValue: string}} DateTimeOriginal
* @property {string} DateCreated
* @property {string} DateTimeCreated
* @property {string} OffsetTimeOriginal
* @property {string} camera
* @property {string} lens
* @property {string} orientation
* @property {number|string} height
* @property {number|string} width
* @property {number|string} lat
* @property {number|string} lng
* @property {string} GPSLatitude
* @property {string} GPSLatitudeRef
* @property {string} GPSLongitude
* @property {string} GPSLongitudeRef
* @property {string} GPSAltitude
* @property {string} GPSImgDirection
* @property {string} pos
* @property {string} file
* @property {string} extension
* @property {string} imagePath
* @property {string} thumbnail
* @property {string} status
* @property {string} Title
* @property {string} CaptionAbstract
* @property {string} Description
* @property {string} ImageDescription
* @property {string} XPTitle
* @property {string} XPSubject
* @property {string} XPComment
* @property {number} index
*/
try {
// Read all files in the directory
let start = performance.now();
const files = fs.readdirSync(folderPath);
let end = performance.now();
console.log(`Read ${files.length} files from ${folderPath} in ${end - start}ms`);
// Filter files by the specified extensions
const imageFiles = files.filter(file => {
const ext = path.extname(file).toLowerCase().replace('.', '');
return extensions.includes(ext);
});
// Define a function to extract required EXIF metadata.
const getExifData = async (filePath) => {
const metadata = await exiftool.read(filePath, { ignoreMinorErrors: true });
// metadata["State"], metadata.City, metadata.Country
let thumbnailPath = '';
const maxAgeDays = 14;
//if (metadata.ThumbnailImage && metadata.ThumbnailImage.rawValue) {
if ( sharpAvailable ) {
const thumbnailPathTmp = path.join(app.getPath('temp'), `${path.basename(filePath)}_thumb.jpg`); // Security: Validate and normalize paths, then enforce a fixed base directory. Use path.resolve(base, input) and verify the result starts with base. Reject absolute paths, .. segments, and unsafe characters. Prefer allowlists for filenames.
let useExistingThumbnail = false;
// check if thumbnail exists and is not older than maxAgeDays. Delete if older and re-extract or keep existing
if (fs.existsSync(thumbnailPathTmp)) {
const now = Date.now();
const maxAgeMillis = maxAgeDays * 24 * 60 * 60 * 1000;
const stats = fs.statSync(thumbnailPathTmp);
if (now - stats.mtimeMs > maxAgeMillis) {
fs.unlinkSync(thumbnailPathTmp);
} else {
useExistingThumbnail = true;
thumbnailPath = thumbnailPathTmp;
}
}
if (!useExistingThumbnail) {
// add a config for long edge here: get it from the config of the ollamaClient if not use a default value of 1200 px.
// TODO : problem is that other LLM may need other sizes and we need to handle this. So we chose a bit bigger than required for gemma3:12b.
let longEdge = 1200;
if ( ollamaClient ) {
longEdge = ollamaClient.getPreferredLongEdge();
}
thumbnailPath = await resizeImage( metadata, filePath, thumbnailPathTmp, { longEdge: longEdge });
if ( !thumbnailPath) thumbnailPath = filePath;
}
} else {
thumbnailPath = filePath; // fallback to the file path if no thumbnail is available
}
// merge the geo location info to a single field for easier handling in the frontend and also for the AI tagging. Security: Be cautious when merging and displaying location information to prevent potential privacy issues. Consider allowing users to opt-out of sharing or displaying detailed location data.
metadata.Geolocation = [
metadata.City,
metadata.State,
metadata.Country
]
.filter(v => typeof v === 'string' && v.trim())
.join(', ') || 'unknown';
return {
DateTimeOriginal: metadata.DateTimeOriginal || '',
DateCreated: metadata.DateCreated || '',
DateTimeCreated: metadata.DateTimeCreated || '',
OffsetTimeOriginal: metadata.OffsetTimeOriginal || '',
camera: metadata.Model || 'none',
lens: metadata.LensModel || '',
orientation: metadata.Orientation || '',
//type: 'image',
height: metadata.ImageHeight || '',
width: metadata.ImageWidth || '',
lat: metadata.GPSLatitude || '',
GPSLatitude: metadata.GPSLatitude || '',
GPSLatitudeRef: metadata.GPSLatitudeRef || '',
lng: metadata.GPSLongitude || '',
GPSLongitude: metadata.GPSLongitude || '',
GPSLongitudeRef: metadata.GPSLongitudeRef || '',
pos: metadata.GPSPosition || '',
GPSAltitude: metadata.GPSAltitude || '',
GPSImgDirection: metadata.GPSImgDirection || '',
file: path.basename(filePath, path.extname(filePath)),
extension: path.extname(filePath).toLowerCase(),
imagePath: filePath,
thumbnail: thumbnailPath, // base64 encoded thumbnail or file path
status: (metadata.GPSLatitude && metadata.GPSLongitude) ? 'loaded-with-GPS' : 'loaded-no-GPS', // simple status field
// ---- TITLE ----
Title : metadata.Title || '', // will be used in frontend for entry
XPTitle: metadata.XPTitle || '', // TODO : What about Object Name?
// not used: IPTC:ObjectName
// ---- DESCRIPTION ---- with MWG:Description these entries shall be identical!
ImageDescription: metadata.ImageDescription || '', // EXIF: ImageDescription
CaptionAbstract: metadata.CaptionAbstract || '', // IPTC: Caption-Abstract
Description : metadata.Description || '', // will be used in frontend for entry // XMP-dc: Description
// ---- TAGS ----
Keywords: metadata.Keywords || [], // andere Felder enthalten die Keywords nicht.
// ---- GeoLocationInfo ----
// get the geo location info from xmp
City: metadata.City || '',
Country: metadata.Country || '',
ProvinceState: metadata.State || '',
// merge the above fields to a location info string like "City, ProvinceState, Country" and use it in the frontend for display and also for the AI tagging. Security: Be cautious when merging and displaying location information to prevent potential privacy issues. Consider allowing users to opt-out of sharing or displaying detailed location data.
Geolocation: metadata.Geolocation
}
};
// Extract EXIF data for each image and sort by capture time
start = performance.now();
const imagesData = await Promise.all(
imageFiles.map(async file => {
const filePath = path.join(folderPath, file); // Security: Validate and normalize paths, then enforce a fixed base directory. Use path.resolve(base, input) and verify the result starts with base. Reject absolute paths, .. segments, and unsafe characters. Prefer allowlists for filenames.
return await getExifData(filePath);
})
);
end = performance.now();
console.log(`Extracted EXIF data for ${imagesData.length} images in ${end - start}ms`);
// Sort images by capture time
start = performance.now();
sortImagesByCaptureTime(imagesData);
end = performance.now();
console.log(`Sorted ${imagesData.length} images by capture time in ${end - start}ms`);
// Laufende Nummer ergänzen
start = performance.now();
imagesData.forEach((img, idx) => {
img.index = idx; // Start bei 0, alternativ idx+1 für Start bei 1
});
end = performance.now();
console.log(`Added index to ${imagesData.length} images in ${end - start}ms`);
return imagesData;
} catch (error) {
console.log('Error reading images from folder:', error);
}
}
/**
* Writes the metadata of all images in the allmagesData array to their respective files.
* Only images with status 'loaded-with-GPS' or 'loaded-no-GPS' or 'geotagged' are written.
* If writeMetadataOneImage is not initialized, an error is logged and the function returns.
* Sends progress updates to the sender (if provided) after each image is processed.
*
* @param {object} sender - the IPC sender to send progress updates to (optional)
* @param {array} allmagesData - an array of objects containing information about all images
* @returns {Promise<void>} - a promise that resolves when all metadata has been written
*/
async function writeMetaData(allmagesData, sender=null) {
let totalImages = allmagesData.length;
let currentIndex = 1;
for (const img of allmagesData) {
if (img.status !== 'loaded-with-GPS' && img.status !== 'loaded-no-GPS' && img.status !== 'geotagged') {
console.log('Writing meta for Image:', img.file + img.extension);
// progressObject has the structure: { currentIndex: number, totalImages: number, result: string, imagePath: string}
try {
// TODO: remove this doubled code
const result = await writeMetadataOneImage(img.imagePath, img);
if (sender) sender.send('save-meta-progress', {
currentIndex,
totalImages,
imagePath: img.imagePath,
result: result.success ? 'done' : 'error',
message: result.data || result.message
});
} catch (error) {
if (sender) sender.send('save-meta-progress', {
currentIndex,
totalImages,
imagePath: img.imagePath,
result: 'error',
message: error.message
});
}
} else {
console.log('Skipping Image (no meta to write):', img.file + img.extension);
if (sender) sender.send('save-meta-progress', {
currentIndex,
totalImages,
imagePath: img.imagePath,
result: 'skipped'
})
}
currentIndex++;
};
}
/**
* Writes the metadata of one image to its respective file with exiftool-vendored.
* Only images with status 'loaded-with-GPS' or 'loaded-no-GPS' are written.
* If writeMetadataOneImage is not initialized, an error is logged and the function returns.
* @param {string} filePath - the path to the image file
* @param {object} metadata - an object containing information about the image
* @global {object} exifTool
* @global {string} exiftoolPath
* @global {boolean} exiftoolAvailable
* @returns {Promise<void>} - a promise that resolves when the metadata has been written
*/
async function writeMetadataOneImage(filePath, metadata) {
const writeData = {};
// --- GPS Altitude ---
const altitude = metadata.GPSAltitude;
if (altitude !== undefined && altitude !== null) {
writeData["EXIF:GPSAltitude"] = altitude;
}
// --- GPS ImageDirection ---
const imageDirection = metadata.GPSImgDirection;
if (imageDirection !== undefined && imageDirection !== null) {
writeData["EXIF:GPSImgDirection"] = imageDirection;
}
// --- GPS position ---
const pos = metadata.pos; // this is in different formats yet!
if (pos !== undefined && pos !== null && pos !== "") {
writeData["EXIF:GPSPosition"] = pos;
writeData["EXIF:GPSLatitude"] = metadata.GPSLatitude;
writeData["EXIF:GPSLatitudeRef"] = metadata.GPSLatitudeRef;
writeData["EXIF:GPSLongitude"] = metadata.GPSLongitude;
writeData["EXIF:GPSLongitudeRef"] = metadata.GPSLongitudeRef;
} else if (exiftoolAvailable && pos !== null) {
let command = `"${exiftoolPath}" -gps*= -overwrite_original_in_place "${filePath}"`;
console.log("ExifTool Command:", command);
// Comment missing why using the exiftool directly here. Warten auf exec, aber nur im Fehlerfall abbrechen mit return resolve....
const execResult = await new Promise((resolve) => {
// TODO : doubled to 'execDouble'
exec(command, (error, stdout, stderr) => { // Security: Command injection from function argument passed to child_process invocation
if (error) {
console.log(`ExifTool-Error: ${stderr || error.message}`);
return resolve({ success: false, error: `ExifTool-Error: ${stderr || error.message}` });
}
resolve({ success: true, output: stdout });
});
});
} else if (!exiftoolAvailable) {
console.log("exiftool is not available!");
dialog.showErrorBox(i18next.t('NoExiftool'), i18next.t('exiftoolNotFound'));
return { success: false, error: 'Exiftool is not installed or not in PATH.' };
}
// --- TITLE ---
const title = sanitize(metadata.Title);
if (title !== undefined && title !== null) {
writeData["XMP-dc:Title"] = title;
writeData["XPTitle"] = title; // This is not MWG standard! But Windows Special!
writeData["IPTC:ObjectName"] = title;
writeData["IPTCDigest"] = ""; // update IPTC digest
}
// --- DESCRIPTION ---
const desc = sanitize(metadata.Description);
if (desc !== undefined && desc !== null) {
writeData["MWG:Description"] = desc;
writeData["IPTC:Caption-Abstract"] = desc; // must be written after "MWG:Description"!
writeData["IPTCDigest"] = ""; // update IPTC digest
}
// --- KEYWORDS = TAGS ---
if (Array.isArray(metadata.Keywords)) {
metadata.Keywords = metadata.Keywords.join(',');
}
let tags = sanitize(metadata.Keywords);
if (tags !== undefined && tags !== null) {
tags = tags.split(',');
tags = [...new Set(
tags.map(v => v.trim()).filter(v => v.length > 0)
)]
writeData["MWG:Keywords"] = tags; // writes to "XMP-dc:Subject" and IPTC:Keywords but not IPTC:hierarchical Subject (written by LR). "XMP-dc:Subject" and IPTC:Keywords contain a flat List only.
writeData["XMP-lr:HierarchicalSubject"] = []; // remove the old "XMP-lr:HierarchicalSubject" which was written by LR unless the App implements an hierarchical list as well.
}
// --- GeoLocationInfo ---
let city = null, country = null, provinceState = null, countryCode = null;
if ( writeData["EXIF:GPSPosition"] && isValidLatLng(metadata.GPSLatitude, metadata.GPSLongitude) ) {
// get the geo location info from xmp. We are passing to different formats here!
let lat, lng = 0;
if ( Array.isArray(metadata.GPSLatitude) && Array.isArray(metadata.GPSLongitude) ) {
const roundTo = (value, decimals) => Math.round(value * 10 ** decimals) / 10 ** decimals;
let lat1 = metadata.GPSLatitude.join(' ');
let lng1 = metadata.GPSLongitude.join(' ');
lat = roundTo(dmsToDecimal(lat1, metadata.GPSLatitudeRef), 6); // float
lng = roundTo(dmsToDecimal(lng1, metadata.GPSLongitudeRef), 6); // float
} else {
lat = metadata.GPSLatitude;
lng = metadata.GPSLongitude;
}
let result = await reverseGeocodeToXmp(lat, lng);
if (result) {
metadata.City = result.City;
metadata.Country = result.Country;
metadata.State = result['Province-State'];
city = sanitize(metadata.City);
country = sanitize(metadata.Country);
provinceState = sanitize(metadata.State);
countryCode = sanitize(result.CountryCode);
}
} else {
city = null;
country = null;
provinceState = null;
countryCode = null;
}
// do not check for 'null' here because this is used for deleting Tags completely.
if (city !== undefined) {
writeData["XMP:City"] = city;
writeData["XMP-photoshop:City"] = city;