forked from gordon-williams/arc-timeline-reader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport.js
More file actions
1554 lines (1310 loc) · 61 KB
/
Copy pathimport.js
File metadata and controls
1554 lines (1310 loc) · 61 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 Module - Handles all data import functionality
// Separated from app.js for maintainability
// =====================================================
(() => {
'use strict';
// Dependencies injected from app.js
let deps = null;
// Module state
let importAddedDays = [];
let importUpdatedDays = [];
let importChangedItemIds = new Set(); // itemIds that were added or modified in last import
let lastImportReport = '';
/**
* Initialize the import module with dependencies from app.js
* @param {Object} dependencies - Required dependencies
*/
function init(dependencies) {
deps = dependencies;
// Expose public API
// Note: Backup import functions (importFromBackupDir, importFromBackupFiles) remain in app.js
// because they have complex incremental sync logic that's tightly coupled to app state
window.ArcImport = {
importFilesToDatabase,
importMoreFiles,
getImportAddedDays: () => importAddedDays,
getImportUpdatedDays: () => importUpdatedDays,
getImportChangedItemIds: () => importChangedItemIds,
isItemChanged: (itemId) => importChangedItemIds.has(itemId)
};
logInfo('📦 Import module initialized');
}
// ========================================
// Core Import Functions
// ========================================
/**
* Generate a hash for a single timeline item to detect changes
* Uses actual stored values (not normalized) to detect real differences
*/
function generateItemHash(item) {
// Use actual stored values - don't normalize, so we detect real changes
const type = item.activityType || '';
const place = item.placeId || '';
const hasNote = item.noteId ? 'N' : '';
return `${type}:${place}:${hasNote}`;
}
/**
* Compute the differences between old and new day data
* @param {Object} oldData - Previous day data
* @param {Object} newData - New day data
* @param {boolean} trackItemChanges - Only track item-level changes for JSON-to-JSON imports
* @returns {{ summary: string, changedItemIds: string[] }}
*/
function computeDayDiff(oldData, newData, trackItemChanges = false) {
const changes = [];
const changedItemIds = [];
const oldItems = oldData?.timelineItems || [];
const newItems = newData?.timelineItems || [];
// Build maps by itemId for comparison
const oldById = new Map(oldItems.map(i => [i.itemId, i]));
const newById = new Map(newItems.map(i => [i.itemId, i]));
// Only track item-level changes for JSON-to-JSON imports
// Backup imports normalize data differently, causing false positives
if (trackItemChanges) {
// Find new items (added)
for (const [id, newItem] of newById) {
if (!oldById.has(id)) {
changedItemIds.push(id);
}
}
// Find modified items (changed hash)
for (const [id, newItem] of newById) {
const oldItem = oldById.get(id);
if (oldItem) {
const oldHash = generateItemHash(oldItem);
const newHash = generateItemHash(newItem);
if (oldHash !== newHash) {
changedItemIds.push(id);
}
}
}
}
// Item count changes (for summary)
if (oldItems.length !== newItems.length) {
const diff = newItems.length - oldItems.length;
if (diff > 0) {
changes.push(`+${diff} item${diff > 1 ? 's' : ''}`);
} else {
changes.push(`${diff} item${diff < -1 ? 's' : ''}`);
}
}
// Check for activity type changes (for summary)
const typeChanges = [];
for (const [id, newItem] of newById) {
const oldItem = oldById.get(id);
if (oldItem) {
const oldType = oldItem.activityType || (oldItem.isVisit ? 'visit' : 'unknown');
const newType = newItem.activityType || (newItem.isVisit ? 'visit' : 'unknown');
if (oldType !== newType) {
typeChanges.push(`${oldType}→${newType}`);
}
}
}
if (typeChanges.length > 0) {
if (typeChanges.length <= 2) {
changes.push(typeChanges.join(', '));
} else {
changes.push(`${typeChanges.length} type changes`);
}
}
// Check for place changes (for summary)
let placeChanges = 0;
for (const [id, newItem] of newById) {
const oldItem = oldById.get(id);
if (oldItem && oldItem.placeId !== newItem.placeId) {
placeChanges++;
}
}
if (placeChanges > 0) {
changes.push(`${placeChanges} place${placeChanges > 1 ? 's' : ''} reassigned`);
}
// Check for note changes (for summary)
let notesAdded = 0;
let notesRemoved = 0;
for (const [id, newItem] of newById) {
const oldItem = oldById.get(id);
if (oldItem) {
const hadNote = !!oldItem.noteId;
const hasNote = !!newItem.noteId;
if (!hadNote && hasNote) notesAdded++;
if (hadNote && !hasNote) notesRemoved++;
}
}
if (notesAdded > 0) changes.push(`+${notesAdded} note${notesAdded > 1 ? 's' : ''}`);
if (notesRemoved > 0) changes.push(`-${notesRemoved} note${notesRemoved > 1 ? 's' : ''}`);
// If no specific changes detected but hash differs, generic message
if (changes.length === 0) {
changes.push('content updated');
}
return {
summary: changes.join(', '),
changedItemIds
};
}
/**
* Generate a simple content hash for a day's timeline items
* Captures user-editable properties: item count, activity types, place IDs, notes
* This detects changes like car→walk, place reassignment, merging/deleting, adding notes
*/
function generateDayHash(dayData) {
const items = dayData?.timelineItems || [];
if (items.length === 0) return 'empty';
// Build a string from properties that users can edit in Arc:
// - Activity type (car, walk, cycling, etc.)
// - Place assignment (placeId)
// - Notes (noteId presence indicates a note exists)
// - Item count (changes when merging/deleting)
const parts = items.map(item => {
const type = item.activityType || (item.isVisit ? 'visit' : 'trip');
const place = item.placeId?.substring(0, 8) || '';
const hasNote = item.noteId ? 'N' : '';
return `${type}:${place}:${hasNote}`;
});
return parts.join('|');
}
/**
* Import day data to IndexedDB (with timestamp and content comparison)
* @param {string} dayKey - Day key (YYYY-MM-DD)
* @param {string} monthKey - Month key (YYYY-MM)
* @param {Object} dayData - Day data to import
* @param {string} sourceFile - Source filename
* @param {number} lastUpdated - File modification timestamp
* @param {Map} existingMetadata - Pre-loaded metadata for O(1) lookups
* @returns {Promise<{action: string, dayKey: string, diff?: string}>}
*/
async function importDayToDB(dayKey, monthKey, dayData, sourceFile, lastUpdated, existingMetadata = null) {
const db = deps.getDB();
if (!db) throw new Error('Database not initialized');
// Check if day exists and compare timestamps + content
let existingMeta = null;
let dayExists = false;
let existingData = null;
let existingSourceFile = null;
if (existingMetadata) {
existingMeta = existingMetadata.get(dayKey);
dayExists = existingMeta !== undefined;
if (existingMeta) {
existingSourceFile = existingMeta.sourceFile;
}
} else {
const existing = await deps.getDayFromDB(dayKey);
if (existing) {
existingMeta = {
lastUpdated: existing.lastUpdated,
// Use stored hash if available, compute for old records without it
contentHash: existing.contentHash || generateDayHash(existing.data)
};
existingData = existing.data;
existingSourceFile = existing.sourceFile;
dayExists = true;
}
}
if (dayExists) {
const newHash = generateDayHash(dayData);
// Skip only if content hash matches - no meaningful changes
// Hash captures: item count, activity types, place IDs, notes
// This detects: car→walk, place reassignment, merging/deleting, adding notes
if (existingMeta.contentHash === newHash) {
return { action: 'skipped', dayKey, reason: 'content unchanged' };
}
// Fetch existing data for diff if we don't have it yet
if (!existingData) {
const existing = await deps.getDayFromDB(dayKey);
existingData = existing?.data;
existingSourceFile = existing?.sourceFile;
}
}
// Compute hash for the new data to store with the record
const contentHash = generateDayHash(dayData);
// Compute diff if updating - only track item-level changes for JSON-to-JSON imports
// Backup imports normalize data differently, causing false positives
const isJsonToJson = existingSourceFile &&
!existingSourceFile.includes('backup') &&
!sourceFile.includes('backup');
const diff = (dayExists && existingData) ? computeDayDiff(existingData, dayData, isJsonToJson) : null;
return new Promise((resolve, reject) => {
const tx = db.transaction(['days'], 'readwrite');
const store = tx.objectStore('days');
const dayRecord = {
dayKey,
monthKey,
lastUpdated,
sourceFile,
contentHash,
data: dayData
};
store.put(dayRecord);
tx.oncomplete = () => {
const action = dayExists ? 'updated' : 'added';
resolve({ action, dayKey, diff });
};
tx.onerror = () => reject(tx.error);
});
}
/**
* Get day metadata from IndexedDB for import comparison
* Uses stored contentHash when available, falls back to computing for old records
* @returns {Promise<Map>} Map<dayKey, {lastUpdated, contentHash}>
*/
async function getDayMetadataFromDB() {
const db = deps.getDB();
if (!db) return new Map();
return new Promise((resolve, reject) => {
const metadata = new Map();
const tx = db.transaction(['days'], 'readonly');
const store = tx.objectStore('days');
const req = store.openCursor();
req.onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
const day = cursor.value;
metadata.set(day.dayKey, {
lastUpdated: day.lastUpdated,
// Use stored hash if available, compute for old records without it
contentHash: day.contentHash || generateDayHash(day.data),
// Track source for JSON-to-JSON change detection
sourceFile: day.sourceFile || null
});
cursor.continue();
} else {
resolve(metadata);
}
};
req.onerror = () => reject(req.error);
});
}
/**
* Get all day keys from IndexedDB (lightweight)
*/
async function getAllDayKeysFromDB() {
const db = deps.getDB();
if (!db) return [];
return new Promise((resolve, reject) => {
const tx = db.transaction(['days'], 'readonly');
const store = tx.objectStore('days');
const req = store.getAllKeys();
req.onsuccess = () => resolve(req.result || []);
req.onerror = () => reject(req.error);
});
}
// ========================================
// Daily JSON Import (from Arc Export folder)
// ========================================
/**
* Import files to IndexedDB with sync logic
* Main entry point for daily JSON import
*/
async function importFilesToDatabase() {
const selectedFiles = deps.getSelectedFiles();
if (!selectedFiles.length) {
alert('Please select a folder containing daily JSON files');
return;
}
deps.setCancelProcessing(false);
// Get UI elements
const fileInputSection = document.getElementById('fileInputSection');
const progress = document.getElementById('progress');
const progressFill = document.getElementById('progressFill');
const progressText = document.getElementById('progressText');
const cancelBtn = document.getElementById('cancelBtn');
const logDiv = document.getElementById('log');
const results = document.getElementById('results');
// Hide the import tile and legacy results panel, show the log report
if (fileInputSection) fileInputSection.style.display = 'none';
if (results) results.style.display = 'none';
progress.style.display = 'block';
cancelBtn.style.display = 'block';
logDiv.style.display = 'block';
logDiv.innerHTML = '';
// Clear previous import tags
importAddedDays = [];
importUpdatedDays = [];
// Memory flush
if (typeof window.gc === 'function') {
window.gc();
}
await new Promise(r => setTimeout(r, 100));
deps.addLog(`Starting import to database...`);
deps.addLog(`Found ${selectedFiles.length} daily JSON files`);
// Check if force full rescan is enabled
const forceFullRescan = document.getElementById('forceFullRescan')?.checked || false;
// Get last successful scan time
const lastScanTime = forceFullRescan ? null : await deps.getMetadata('lastSync');
if (forceFullRescan) {
deps.addLog(`⚠️ Force full rescan enabled - ignoring last scan time`);
} else if (lastScanTime) {
const lastScanDate = new Date(lastScanTime).toLocaleString();
deps.addLog(`Last scan: ${lastScanDate}`);
} else {
deps.addLog(`First scan - importing all files`);
}
// Filter files by valid date format
const validFiles = selectedFiles.filter(file => {
const match = file.name.match(/(\d{4}-\d{2}-\d{2})\.json\.gz/);
return !!match;
});
deps.addLog(`${validFiles.length} valid daily JSON files found`);
// Only process files modified since last scan
const filesToProcess = lastScanTime
? validFiles.filter(file => file.lastModified > lastScanTime)
: validFiles;
const skippedByModDate = validFiles.length - filesToProcess.length;
// Report scan results
deps.addLog(`\n📋 Scan Results:`);
deps.addLog(` Total files scanned: ${validFiles.length}`);
deps.addLog(` Files to import: ${filesToProcess.length}`);
deps.addLog(` Files skipped (unchanged): ${skippedByModDate}`);
if (filesToProcess.length === 0) {
deps.addLog(`\n✅ All files up to date - nothing to import`);
if (validFiles.length > 0) {
const dates = validFiles.map(f => f.name.match(/(\d{4}-\d{2}-\d{2})/)[1]).sort();
deps.addLog(` Date range: ${dates[0]} to ${dates[dates.length - 1]}`);
}
if (!forceFullRescan) {
await deps.saveMetadata('lastSync', Date.now());
}
const forceCheckbox = document.getElementById('forceFullRescan');
if (forceCheckbox) forceCheckbox.checked = false;
progress.style.display = 'none';
cancelBtn.style.display = 'none';
return;
}
// Show files to import
deps.addLog(`\n📂 Files to import (sorted by date):`);
const sortedFiles = [...filesToProcess].sort((a, b) => {
const dateA = a.name.match(/(\d{4}-\d{2}-\d{2})/)[1];
const dateB = b.name.match(/(\d{4}-\d{2}-\d{2})/)[1];
return dateA.localeCompare(dateB);
});
if (sortedFiles.length <= 20) {
sortedFiles.forEach(file => {
const modDate = new Date(file.lastModified).toLocaleString();
deps.addLog(` • ${file.name} (modified: ${modDate})`);
});
} else {
for (let i = 0; i < 10; i++) {
const file = sortedFiles[i];
const modDate = new Date(file.lastModified).toLocaleString();
deps.addLog(` • ${file.name} (modified: ${modDate})`);
}
deps.addLog(` ... ${sortedFiles.length - 20} more files ...`);
for (let i = sortedFiles.length - 10; i < sortedFiles.length; i++) {
const file = sortedFiles[i];
const modDate = new Date(file.lastModified).toLocaleString();
deps.addLog(` • ${file.name} (modified: ${modDate})`);
}
}
deps.addLog(`\n⏳ Starting import...`);
// Load existing metadata for O(1) lookups
deps.addLog(` Loading existing day metadata...`);
const existingMetadata = await getDayMetadataFromDB();
deps.addLog(` Found ${existingMetadata.size} existing days in database`);
let syncStats = { added: 0, updated: 0, skipped: 0 };
let addedDays = [];
let updatedDays = [];
let updateDiffs = new Map(); // dayKey -> diff description
let changedItemIds = new Set(); // itemIds that were added or modified
let processedFiles = 0;
let failedFiles = [];
for (const file of filesToProcess) {
if (deps.getCancelProcessing()) {
deps.addLog('Import cancelled', 'error');
break;
}
try {
const match = file.name.match(/(\d{4}-\d{2}-\d{2})\.json\.gz/);
const fileDate = match[1];
const [year, month] = fileDate.split('-');
const monthKey = `${year}-${month}`;
const dayKey = fileDate;
// Decompress and apply fixes
const data = await deps.decompressFile(file);
deps.applyImportFixes(data);
const lastUpdated = file.lastModified;
const result = await importDayToDB(dayKey, monthKey, data, file.name, lastUpdated, existingMetadata);
syncStats[result.action]++;
if (result.action === 'added') {
addedDays.push(dayKey);
} else if (result.action === 'updated') {
updatedDays.push(dayKey);
if (result.diff) {
updateDiffs.set(dayKey, result.diff.summary);
// Collect changed itemIds
if (result.diff.changedItemIds && result.diff.changedItemIds.length > 0) {
for (const itemId of result.diff.changedItemIds) {
changedItemIds.add(itemId);
}
}
}
}
processedFiles++;
const percent = Math.round((processedFiles / filesToProcess.length) * 100);
progressFill.style.width = percent + '%';
progressFill.textContent = percent + '%';
progressText.textContent = `Processing: ${file.name} (${processedFiles}/${filesToProcess.length})`;
} catch (error) {
failedFiles.push(file.name);
logError(`Error importing ${file.name}:`, error);
}
}
// Report failed files
if (failedFiles.length > 0) {
deps.addLog(`\n⚠️ ${failedFiles.length} files failed to read:`, 'error');
if (failedFiles.length <= 10) {
failedFiles.forEach(f => deps.addLog(` • ${f}`, 'error'));
} else {
failedFiles.slice(0, 5).forEach(f => deps.addLog(` • ${f}`, 'error'));
deps.addLog(` ... and ${failedFiles.length - 5} more`, 'error');
}
deps.addLog(`\nTip: Re-select the folder and import again to retry failed files.`, 'info');
}
// Save last sync time
await deps.saveMetadata('lastSync', Date.now());
// Reset force rescan checkbox
const forceCheckbox = document.getElementById('forceFullRescan');
if (forceCheckbox) forceCheckbox.checked = false;
// Sort days chronologically
addedDays.sort();
updatedDays.sort();
// Update module state
importAddedDays = addedDays.slice();
importUpdatedDays = updatedDays.slice();
importChangedItemIds = changedItemIds; // Already a Set
// Sync to app.js variables (for generateMarkdown to use)
if (deps.updateImportTracking) {
logInfo(`📊 Syncing import tracking: ${importAddedDays.length} added, ${importUpdatedDays.length} updated, ${importChangedItemIds.size} changed items`);
deps.updateImportTracking(importAddedDays, importUpdatedDays, importChangedItemIds);
}
// Invalidate cache for affected months
const affectedMonths = new Set();
[...addedDays, ...updatedDays].forEach(dayKey => {
affectedMonths.add(dayKey.substring(0, 7));
});
deps.invalidateMonthCache(affectedMonths);
// Save to IndexedDB for persistence
await deps.saveMetadata('importAddedDays', addedDays);
await deps.saveMetadata('importUpdatedDays', updatedDays);
// Convert Set to Array for JSON storage
await deps.saveMetadata('importChangedItemIds', [...changedItemIds]);
// Update analysis data in background
if (addedDays.length > 0 || updatedDays.length > 0) {
deps.updateAnalysisDataInBackground([...addedDays, ...updatedDays]);
}
// Build and display report with skip breakdown and diffs
displayImportReport(validFiles.length, addedDays, updatedDays, skippedByModDate, syncStats.skipped, logDiv, updateDiffs);
// Update UI
await deps.updateDBStatusDisplay();
await deps.loadMostRecentMonth();
// Notify other tabs
if (addedDays.length > 0 || updatedDays.length > 0) {
try {
const dataChannel = new BroadcastChannel('arc-data-update');
dataChannel.postMessage({
type: 'dataImported',
addedDays: addedDays.length,
updatedDays: updatedDays.length,
timestamp: Date.now()
});
dataChannel.close();
} catch (e) {
// BroadcastChannel not supported
}
}
progress.style.display = 'none';
cancelBtn.style.display = 'none';
// Reset file input
deps.resetFileInput();
}
/**
* Display formatted import report
* @param {Map} updateDiffs - Map of dayKey -> diff description for updated days
*/
function displayImportReport(filesScanned, addedDays, updatedDays, skippedByModDate, skippedByHash, logDiv, updateDiffs = new Map()) {
const formatDateForReport = (dayKey) => {
const date = new Date(dayKey + 'T00:00:00');
return date.toLocaleDateString('en-AU', {
weekday: 'short',
day: 'numeric',
month: 'short',
year: 'numeric'
});
};
const totalSkipped = skippedByModDate + skippedByHash;
// Build markdown report
let reportLines = [];
reportLines.push('# Arc Timeline Import Report');
reportLines.push(`**Date:** ${new Date().toLocaleString('en-AU')}`);
reportLines.push(`**Files scanned:** ${filesScanned}`);
reportLines.push('');
if (addedDays.length > 0) {
reportLines.push(`## 📥 Added (${addedDays.length} days)`);
addedDays.forEach(d => reportLines.push(`- ${formatDateForReport(d)}`));
reportLines.push('');
}
if (updatedDays.length > 0) {
reportLines.push(`## 🔄 Updated (${updatedDays.length} days)`);
updatedDays.forEach(d => {
const diff = updateDiffs.get(d);
if (diff) {
reportLines.push(`- ${formatDateForReport(d)} — ${diff}`);
} else {
reportLines.push(`- ${formatDateForReport(d)}`);
}
});
reportLines.push('');
}
if (totalSkipped > 0) {
reportLines.push(`## ⏭️ Skipped`);
if (skippedByModDate > 0) {
reportLines.push(`- ${skippedByModDate} files unchanged since last scan`);
}
if (skippedByHash > 0) {
reportLines.push(`- ${skippedByHash} files with identical content (hash match)`);
}
}
lastImportReport = reportLines.join('\n');
// Build HTML report
let reportHtml = `
<div style="padding: 20px;">
<h3 style="margin: 0 0 16px 0; color: #333; font-size: 18px;">✅ Import Complete</h3>
<div style="font-size: 13px; color: #666; margin-bottom: 20px;">
${new Date().toLocaleString('en-AU')} • ${filesScanned} files scanned
</div>`;
if (addedDays.length > 0) {
reportHtml += `
<div style="margin-bottom: 20px;">
<h4 style="margin: 0 0 10px 0; color: #2e7d32; font-size: 15px;">📥 Added (${addedDays.length} days)</h4>
<ul style="margin: 0; padding-left: 20px; color: #333;">
${addedDays.map(d => `<li style="margin: 4px 0;">${formatDateForReport(d)}</li>`).join('')}
</ul>
</div>`;
}
if (updatedDays.length > 0) {
reportHtml += `
<div style="margin-bottom: 20px;">
<h4 style="margin: 0 0 10px 0; color: #ef6c00; font-size: 15px;">🔄 Updated (${updatedDays.length} days)</h4>
<ul style="margin: 0; padding-left: 20px; color: #333;">
${updatedDays.map(d => {
const diff = updateDiffs.get(d);
if (diff) {
return `<li style="margin: 4px 0;">${formatDateForReport(d)} <span style="color: #666; font-size: 12px;">— ${diff}</span></li>`;
}
return `<li style="margin: 4px 0;">${formatDateForReport(d)}</li>`;
}).join('')}
</ul>
</div>`;
}
if (totalSkipped > 0) {
let skipDetails = [];
if (skippedByModDate > 0) {
skipDetails.push(`${skippedByModDate} unchanged since last scan`);
}
if (skippedByHash > 0) {
skipDetails.push(`${skippedByHash} identical content (hash match)`);
}
reportHtml += `
<div style="color: #666; font-size: 13px;">
⏭️ Skipped: ${skipDetails.join(', ')}
</div>`;
}
if (addedDays.length === 0 && updatedDays.length === 0) {
reportHtml += `
<div style="color: #666; font-size: 14px;">
No changes detected. All files are up to date.
</div>`;
}
// Add copy button
if (addedDays.length > 0 || updatedDays.length > 0) {
reportHtml += `
<div style="margin-top: 20px; padding-top: 16px; border-top: 1px solid #e0e0e0;">
<button id="copyReportBtn" style="background: #007AFF; color: white; border: none; padding: 10px 20px; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500;">
📋 Copy Report to Clipboard
</button>
<span id="copyReportStatus" style="margin-left: 12px; color: #388e3c; display: none;">✓ Copied!</span>
</div>`;
}
reportHtml += '</div>';
logDiv.innerHTML = reportHtml;
logDiv.style.display = 'block';
// Add copy button handler
const copyBtn = document.getElementById('copyReportBtn');
if (copyBtn) {
copyBtn.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(lastImportReport);
const status = document.getElementById('copyReportStatus');
status.style.display = 'inline';
setTimeout(() => { status.style.display = 'none'; }, 2000);
} catch (err) {
logError('Failed to copy:', err);
alert('Failed to copy to clipboard');
}
});
}
}
/**
* Import More Files button handler
*/
function importMoreFiles() {
// Close location search popup if open
if (typeof window.closeSearchPopup === 'function') {
window.closeSearchPopup();
}
const logDiv = document.getElementById('log');
if (logDiv) logDiv.style.display = 'none';
deps.resetFileInput();
document.getElementById('fileInputSection').style.display = 'block';
document.getElementById('fileInputSection').scrollIntoView({ behavior: 'smooth' });
}
// ========================================
// Backup Import (from Arc iCloud backup)
// ========================================
/**
* Helper: Order items by linked list (previousItemId/nextItemId)
*/
function orderItemsByLinkedList(items) {
if (!items || items.length === 0) return [];
if (items.length === 1) return items;
const byId = new Map();
const byPrevId = new Map();
for (const item of items) {
if (item.itemId) {
byId.set(item.itemId, item);
}
if (item.previousItemId) {
byPrevId.set(item.previousItemId, item);
}
}
const heads = [];
for (const item of items) {
if (!item.previousItemId || !byId.has(item.previousItemId)) {
heads.push(item);
}
}
if (heads.length === 0) {
heads.push(items[0]);
}
const ordered = [];
const visited = new Set();
for (const head of heads) {
let current = head;
while (current && !visited.has(current.itemId)) {
visited.add(current.itemId);
ordered.push(current);
if (current.nextItemId && byId.has(current.nextItemId)) {
current = byId.get(current.nextItemId);
} else {
current = byPrevId.get(current.itemId);
}
}
}
for (const item of items) {
if (!visited.has(item.itemId)) {
ordered.push(item);
}
}
return ordered;
}
/**
* Helper: Read gzipped file as JSON (File System Access API)
*/
async function readGzippedFileAsJson(fileHandle) {
try {
const file = await fileHandle.getFile();
const arrayBuffer = await file.arrayBuffer();
const decompressed = pako.ungzip(new Uint8Array(arrayBuffer), { to: 'string' });
return JSON.parse(decompressed);
} catch {
return null;
}
}
/**
* Helper: Read file as JSON (File System Access API)
*/
async function readFileAsJson(fileHandle) {
try {
const file = await fileHandle.getFile();
const text = await file.text();
return JSON.parse(text);
} catch {
return null;
}
}
/**
* Helper: Iterate JSON files from hex-structured directories
*/
async function* readJsonFilesFromHexDirs(dirHandle) {
for await (const [name, handle] of dirHandle.entries()) {
if (handle.kind === 'directory' && /^[0-9A-Fa-f]$/.test(name)) {
for await (const [fileName, fileHandle] of handle.entries()) {
if (fileHandle.kind === 'file' && fileName.endsWith('.json')) {
yield fileHandle;
}
}
}
}
}
/**
* Import from backup using File System Access API (Chrome/Edge)
*/
async function importFromBackupDir(dirHandle) {
deps.setCancelProcessing(false);
const fileInputSection = document.getElementById('fileInputSection');
const progress = document.getElementById('progress');
const progressFill = document.getElementById('progressFill');
const progressText = document.getElementById('progressText');
const cancelBtn = document.getElementById('cancelBtn');
const logDiv = document.getElementById('log');
if (fileInputSection) fileInputSection.style.display = 'none';
progress.style.display = 'block';
cancelBtn.style.display = 'block';
logDiv.style.display = 'block';
logDiv.innerHTML = '';
importAddedDays = [];
importUpdatedDays = [];
deps.addLog('🔄 Starting backup import (File System Access API)...');
const forceRescan = document.getElementById('backupForceRescan')?.checked || false;
const lastBackupSync = forceRescan ? null : await deps.getMetadata('lastBackupSync');
if (forceRescan) {
deps.addLog('⚠️ Force rescan enabled - reimporting all data');
} else if (lastBackupSync) {
deps.addLog(`📅 Last backup sync: ${lastBackupSync}`);
}
try {
// Get directory handles
const timelineDir = await dirHandle.getDirectoryHandle('TimelineItem');
const placeDir = await dirHandle.getDirectoryHandle('Place').catch(() => null);
const noteDir = await dirHandle.getDirectoryHandle('Note').catch(() => null);
const sampleDir = await dirHandle.getDirectoryHandle('LocomotionSample').catch(() => null);
// For "missing only" mode
let existingDays = new Set();
// Step 1: Load Places (0-5%)
deps.addLog('\n📍 Loading Places...');
progressFill.style.width = '0%';
progressFill.textContent = '0%';
const placeLookup = new Map();
if (placeDir) {
let placeCount = 0;
for await (const fileHandle of readJsonFilesFromHexDirs(placeDir)) {
if (deps.getCancelProcessing()) break;
const place = await readFileAsJson(fileHandle);
if (place && place.placeId && !place.deleted) {
placeLookup.set(place.placeId, place);
placeCount++;
}
if (placeCount % 500 === 0) {
progressText.textContent = `Loading places: ${placeCount.toLocaleString()}...`;
await new Promise(r => setTimeout(r, 0));
}
}
deps.addLog(` Loaded ${placeLookup.size.toLocaleString()} places`);
// Update global placesById
deps.updatePlacesById(placeLookup);
}
if (deps.getCancelProcessing()) {
deps.addLog('Import cancelled', 'error');
progress.style.display = 'none';
cancelBtn.style.display = 'none';
return;
}
// Step 2: Load Notes (5-10%)
deps.addLog('\n📝 Loading Notes...');
progressFill.style.width = '5%';
progressFill.textContent = '5%';
const noteLookup = new Map();
if (noteDir) {
let noteCount = 0;
for await (const fileHandle of readJsonFilesFromHexDirs(noteDir)) {
if (deps.getCancelProcessing()) break;
const note = await readFileAsJson(fileHandle);
if (note && note.noteId && !note.deleted) {
noteLookup.set(note.noteId, note);
noteCount++;
}
if (noteCount % 200 === 0) {
progressText.textContent = `Loading notes: ${noteCount.toLocaleString()}...`;
await new Promise(r => setTimeout(r, 0));
}
}
deps.addLog(` Loaded ${noteLookup.size.toLocaleString()} notes`);
}
if (deps.getCancelProcessing()) {
deps.addLog('Import cancelled', 'error');
progress.style.display = 'none';
cancelBtn.style.display = 'none';
return;
}
// Step 3: Index Timeline Items by day (10-30%)
deps.addLog('\n📅 Indexing Timeline Items...');
progressFill.style.width = '10%';
progressFill.textContent = '10%';
const itemsByDay = new Map();
let itemCount = 0;
for await (const fileHandle of readJsonFilesFromHexDirs(timelineDir)) {
if (deps.getCancelProcessing()) break;
const item = await readFileAsJson(fileHandle);
if (!item || item.deleted) continue;
// Determine day from startDate
const startDate = item.startDate;
if (!startDate) continue;
const dayKey = startDate.substring(0, 10);
if (!itemsByDay.has(dayKey)) {
itemsByDay.set(dayKey, []);
}
itemsByDay.get(dayKey).push(item);