-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
1126 lines (956 loc) · 43.4 KB
/
app.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
class FlipperIRBrowser {
constructor() {
// Initialize UI Elements first
this.initializeUIElements();
// Check Web Serial API
if (!navigator.serial) {
this.showAlert('Web Serial API is not supported in this browser. Please use Chrome or Edge.', 'error');
if (this.connectBtn) {
this.connectBtn.disabled = true;
}
return;
}
if (!this.connectBtn) {
console.error('Connect button not found!');
return;
}
this.flipper = new FlipperSerial();
this.connected = false;
this.loading = false;
// Add event listeners
this.initializeEventListeners();
// Initialize view state with defaults
this.currentView = 'grid';
this.currentSection = 'device_type';
this.groupedFiles = null;
this.selectedCategories = new Set();
// Add view toggle handlers with improved error handling
document.querySelectorAll('.view-toggle button').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.view-toggle button').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
this.currentView = btn.dataset.view;
if (this.groupedFiles) {
this.refreshView();
}
});
});
// Set up section tabs with improved state management
document.querySelectorAll('.section-tab').forEach(tab => {
tab.addEventListener('click', () => {
document.querySelectorAll('.section-tab').forEach(t => t.classList.remove('active'));
tab.classList.add('active');
this.currentSection = tab.dataset.section;
if (this.groupedFiles) {
this.loadSection(this.currentSection);
}
});
});
// Add references to UI elements
this.searchInput = document.getElementById('searchInput');
this.activeGroupSelect = document.getElementById('activeGroup');
this.categoryChipsEl = document.getElementById('categoryChips');
// Initialize search and filter functionality
if (this.searchInput) {
this.searchInput.addEventListener('input', () => this.filterFiles());
}
if (this.activeGroupSelect) {
this.activeGroupSelect.addEventListener('change', () => this.filterFiles());
}
// Pagination settings
this.itemsPerPage = 12;
this.currentPage = 1;
this.filteredFiles = []; // Store filtered results
}
initializeUIElements() {
// UI Elements
this.connectBtn = document.getElementById('connectBtn');
this.alertEl = document.getElementById('alert');
this.statusEl = document.getElementById('status');
this.irFilesEl = document.getElementById('irFiles');
this.databaseFilesEl = document.getElementById('databaseFiles');
this.loadingOverlay = document.getElementById('loadingOverlay');
this.loadingStatus = document.getElementById('loadingStatus');
this.localTab = document.getElementById('localTab');
this.databaseTab = document.getElementById('databaseTab');
this.homeTab = document.getElementById('homeTab');
this.localContent = document.getElementById('localContent');
this.databaseContent = document.getElementById('databaseContent');
this.homeContent = document.getElementById('homeContent');
this.scanningIndicator = document.getElementById('scanningIndicator');
this.welcomeMessage = document.getElementById('welcomeMessage');
// Check if any required elements are missing
const requiredElements = [
'connectBtn', 'alertEl', 'statusEl', 'irFilesEl', 'databaseFilesEl',
'loadingOverlay', 'loadingStatus', 'localTab', 'databaseTab', 'homeTab',
'localContent', 'databaseContent', 'homeContent', 'scanningIndicator',
'welcomeMessage'
];
requiredElements.forEach(elementId => {
if (!this[elementId]) {
console.error(`Required element not found: ${elementId}`);
}
});
}
initializeEventListeners() {
// Add tab listeners
this.localTab.addEventListener('click', () => this.switchTab('local'));
this.databaseTab.addEventListener('click', () => this.switchTab('database'));
this.homeTab.addEventListener('click', () => this.switchTab('home'));
// Debug the button click directly
this.connectBtn.addEventListener('click', () => {
console.log('Connect button clicked');
console.log('Current state:', {
connected: this.connected,
flipperConnected: this.flipper?.isConnected,
buttonText: this.connectBtn.textContent
});
this.connectFlipper();
});
}
setLoading(isLoading, status = 'Loading...') {
this.loading = isLoading;
if (!this.connected) {
this.connectBtn.disabled = isLoading;
}
this.loadingOverlay.classList.toggle('active', isLoading);
this.loadingStatus.textContent = status;
this.scanningIndicator.style.display = isLoading ? 'flex' : 'none';
}
showAlert(message, type = 'error') {
if (!this.alertEl) {
console.error('Alert element not found!');
console.error(message);
return;
}
console.log(`Showing alert: ${message} (${type})`);
this.alertEl.textContent = message;
this.alertEl.className = `alert ${type}`;
this.alertEl.style.display = 'block';
if (type === 'success') {
setTimeout(() => {
if (this.alertEl) {
this.alertEl.style.display = 'none';
this.alertEl.className = 'alert';
}
}, 3000);
}
}
async connectFlipper() {
const ConnectionState = {
DISCONNECTING: 'disconnecting',
CONNECTING: 'connecting',
IDLE: 'idle'
};
let currentState = ConnectionState.IDLE;
try {
if (this.connected) {
currentState = ConnectionState.DISCONNECTING;
this.setLoading(true, 'Disconnecting...');
if (!this.flipper) throw new Error('Flipper instance not initialized');
await this.flipper.disconnect();
this.updateConnectionState(false);
this.showAlert('Disconnected from Flipper', 'success');
return;
}
currentState = ConnectionState.CONNECTING;
this.setLoading(true, 'Connecting to Flipper...');
if (!this.flipper) throw new Error('Internal error: Flipper Serial not initialized');
await this.flipper.connect();
this.updateConnectionState(true);
this.showAlert('Successfully connected to Flipper!', 'success');
await this.loadIRFiles();
} catch (err) {
console.error(`${currentState} error:`, err);
this.showAlert(`Failed to ${currentState}: ${err.message}`);
this.updateConnectionState(false);
} finally {
this.setLoading(false);
}
}
updateConnectionState(isConnected) {
this.connected = isConnected;
if (this.flipper) this.flipper.isConnected = isConnected;
if (this.connectBtn) {
this.connectBtn.textContent = isConnected ? 'Disconnect' : 'Connect Flipper';
this.connectBtn.classList.toggle('connected', isConnected);
}
if (!isConnected) {
this.irFilesEl.innerHTML = '';
}
}
async loadIRFiles() {
try {
console.log('Starting to load IR files...');
const emptyStateEl = document.getElementById('emptyLocalState');
const loadingStateEl = document.getElementById('localLoadingState');
this.irFilesEl.innerHTML = '';
// Only show loading and attempt to scan if connected
if (this.flipper && this.flipper.isConnected) {
loadingStateEl.style.display = 'block';
emptyStateEl.style.display = 'none';
await this.scanDirectory('/ext/infrared');
if (!this.irFilesEl.children.length) {
emptyStateEl.style.display = 'block';
this.showAlert('No IR files with valid metadata found in /ext/infrared/', 'error');
} else {
emptyStateEl.style.display = 'none';
this.showAlert(`Found ${this.irFilesEl.children.length} IR files with metadata`, 'success');
}
} else {
// Not connected, just show empty state
loadingStateEl.style.display = 'none';
emptyStateEl.style.display = 'block';
}
} catch (err) {
console.error('Failed to load IR files:', err);
loadingStateEl.style.display = 'none';
emptyStateEl.style.display = 'block';
if (this.flipper && this.flipper.isConnected) {
this.showAlert('Failed to load IR files: ' + err.message);
}
}
}
async scanDirectory(path) {
const files = await this.flipper.listDirectory(path);
const irFiles = files.filter(f => f.name.endsWith('.ir') && !f.name.startsWith('.'));
const directories = files.filter(f => f.isDirectory);
// Cache path components and IRDB check once per directory
const pathComponents = path.split('/').filter(p => p);
const isInIRDB = pathComponents.some(comp => comp.toUpperCase() === 'IRDB');
let processedFiles = 0;
const totalFiles = irFiles.length;
// Process files in parallel with a limit of 3 concurrent operations
const processFile = async (file) => {
processedFiles++;
this.setLoading(true, `Reading file ${processedFiles}/${totalFiles} from ${path}`);
try {
const content = await this.flipper.readFile(file.path);
let metadata = this.parseIRMetadata(content);
if (metadata) {
this.addIRFileCard(file, metadata, content);
return;
}
// Only attempt guessing if not in IRDB
if (!isInIRDB) {
metadata = this.guessMetadata(file.name, pathComponents);
if (metadata) {
this.addIRFileCard(file, metadata, content);
}
}
} catch (fileErr) {
console.error(`Error reading ${file.name}:`, fileErr);
}
};
// Process files in chunks of 3
for (let i = 0; i < irFiles.length; i += 3) {
const chunk = irFiles.slice(i, i + 3);
await Promise.all(chunk.map(processFile));
}
// Process directories sequentially
for (const dir of directories) {
await this.scanDirectory(dir.path);
}
}
parseIRMetadata(content) {
if (!content) return null;
const metadata = {
brand: null,
device_type: null,
model: null,
protocol: null
};
try {
const lines = content.split('\n');
for (const line of lines) {
if (!line.startsWith('#')) continue;
const [key, ...valueParts] = line.substring(2).split(':');
const cleanKey = key.toLowerCase().trim().replace(/ /g, '_');
if (cleanKey in metadata) {
metadata[cleanKey] = valueParts.join(':').trim();
}
}
// Check if required fields are present
const hasRequiredFields = ['brand', 'device_type', 'model']
.every(field => metadata[field]);
return hasRequiredFields ? metadata : null;
} catch (err) {
console.error('Metadata parsing error:', err);
return null;
}
}
addIRFileCard(file, metadata, content) {
const card = document.createElement('div');
card.className = 'ir-card';
if (metadata.isGuessed) {
card.classList.add('guessed-metadata');
}
card.innerHTML = `
<div class="ir-info">
<h3>${metadata.brand}</h3>
<div class="metadata-badges">
<span class="badge device-type" title="Device Category">${metadata.device_type}</span>
<span class="badge brand" title="Manufacturer">${metadata.brand}</span>
<span class="badge model" title="Model Number">${metadata.model}</span>
${metadata.protocol ? `<span class="badge protocol" title="IR Protocol">${metadata.protocol}</span>` : ''}
<span class="badge filename" title="File: ${file.path}">${file.name}</span>
${metadata.isGuessed ? '<span class="badge warning" title="Metadata was automatically detected">Guessed Metadata</span>' : ''}
${file.size ? `<span class="badge size" title="File Size">${this.formatFileSize(file.size)}</span>` : ''}
</div>
<p class="file-path">${file.path}</p>
</div>
<div class="button-group">
${metadata.isGuessed ?
'<button class="confirm-metadata-btn">Confirm Metadata</button>' :
'<button class="share-btn">Share to Database</button>'
}
</div>
`;
// Add event listeners
if (metadata.isGuessed) {
const confirmBtn = card.querySelector('.confirm-metadata-btn');
confirmBtn.addEventListener('click', () => {
this.confirmMetadata(file, metadata, content, card);
});
} else {
const shareBtn = card.querySelector('.share-btn');
shareBtn.addEventListener('click', () => {
this.uploadToDatabase(file, metadata, content);
});
}
this.irFilesEl.appendChild(card);
}
async confirmMetadata(file, metadata, content, card) {
// After successful confirmation, update the card to match normal files
try {
await this.saveMetadataToFile(file.path, content, metadata);
// Update the card UI
card.classList.remove('guessed-metadata');
const buttonGroup = card.querySelector('.button-group');
buttonGroup.innerHTML = '<button class="share-btn">Share to Database</button>';
// Remove the guessed badge
card.querySelector('.badge.guessed')?.remove();
// Add share button listener
const shareBtn = buttonGroup.querySelector('.share-btn');
shareBtn.addEventListener('click', () => {
this.uploadToDatabase(file, metadata, content);
});
this.showAlert('Metadata saved successfully!', 'success');
} catch (err) {
this.showAlert('Failed to save metadata: ' + err.message);
}
}
async uploadToDatabase(file, metadata, content) {
try {
// Check if user is authenticated
if (!firebase.auth().currentUser) {
// Sign in anonymously
await firebase.auth().signInAnonymously();
}
const irRef = firebase.database().ref('ir_files');
await irRef.push({
name: file.name,
metadata: metadata,
content: content,
uploadedAt: firebase.database.ServerValue.TIMESTAMP
});
this.showAlert('Successfully shared to database!', 'success');
} catch (err) {
console.error('Upload failed:', err);
this.showAlert('Failed to share to database: ' + err.message);
}
}
// Simplified view refresh logic
refreshView() {
if (!this.groupedFiles) {
console.warn('No files loaded to display');
return;
}
const files = this.currentSection === 'all'
? this.groupedFiles.all
: this.groupedFiles[this.currentSection];
this.displayFiles(files);
}
// Improved section loading
loadSection(section) {
if (!this.groupedFiles) return;
this.currentSection = section;
// Update UI state
this.updateCategoryChips(this.groupedFiles);
this.displayFiles(this.groupedFiles[section]);
// Reset filters
if (this.searchInput) this.searchInput.value = '';
if (this.activeGroupSelect) this.activeGroupSelect.value = '';
}
// Improved file display logic
displayFiles(files) {
if (!this.databaseFilesEl) {
console.error('Database files element not found');
return;
}
// Clear current display
this.databaseFilesEl.innerHTML = '';
if (!files || typeof files !== 'object') {
console.warn('Invalid files data:', files);
return;
}
// Reset pagination state
this.currentPage = 1;
this.filteredFiles = [];
// Collect all files to be displayed
if (this.currentSection === 'all') {
this.filteredFiles = Object.values(files);
} else {
Object.values(files).forEach(groupFiles => {
if (!groupFiles || typeof groupFiles !== 'object') return;
this.filteredFiles.push(...Object.values(groupFiles));
});
}
// Display first page and setup pagination
this.displayCurrentPage();
this.updatePagination();
this.updateSearchResultsCount(this.filteredFiles.length);
}
// Improved shared files loading
async loadSharedFiles() {
try {
const databaseLoadingState = document.getElementById('databaseLoadingState');
const emptyDatabaseState = document.getElementById('emptyDatabaseState');
if (!databaseLoadingState || !emptyDatabaseState) {
console.error('Required elements not found');
return;
}
databaseLoadingState.style.display = 'block';
emptyDatabaseState.style.display = 'none';
this.databaseFilesEl.innerHTML = '';
// Get all files
const snapshot = await firebase.database().ref('ir_files').once('value');
const files = snapshot.val() || {};
if (!Object.keys(files).length) {
emptyDatabaseState.style.display = 'block';
return;
}
// Group files and update state
this.groupedFiles = this.groupFilesByMetadata(files);
// Update UI
this.updateSectionCounts(this.groupedFiles);
this.loadSection(this.currentSection);
} catch (err) {
console.error('Failed to load shared files:', err);
this.showAlert('Failed to load shared files: ' + err.message);
} finally {
document.getElementById('databaseLoadingState').style.display = 'none';
}
}
updateSectionCounts(groupedFiles) {
document.querySelectorAll('.section-tab').forEach(tab => {
const section = tab.dataset.section;
const count = Object.keys(groupedFiles[section]).length;
tab.querySelector('.count').textContent = count;
});
}
setupSectionTabs(groupedFiles) {
const tabs = document.querySelectorAll('.section-tab');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
tabs.forEach(t => t.classList.remove('active'));
tab.classList.add('active');
this.loadSection(tab.dataset.section, groupedFiles);
});
});
}
groupFilesByMetadata(files) {
const grouped = {
device_type: {},
brand: {},
all: files
};
Object.entries(files).forEach(([id, file]) => {
const { metadata } = file;
if (!metadata) return;
// Group by device type
if (metadata.device_type) {
if (!grouped.device_type[metadata.device_type]) {
grouped.device_type[metadata.device_type] = {};
}
grouped.device_type[metadata.device_type][id] = file;
}
// Group by brand
if (metadata.brand) {
if (!grouped.brand[metadata.brand]) {
grouped.brand[metadata.brand] = {};
}
grouped.brand[metadata.brand][id] = file;
}
});
return grouped;
}
switchTab(tab) {
// First hide all content
document.querySelectorAll('.tab-content').forEach(content => {
content.style.display = 'none';
});
// Remove active class from all tabs
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.classList.remove('active');
});
// Show selected content and activate tab
switch(tab) {
case 'local':
this.localTab.classList.add('active');
this.localContent.style.display = 'block';
const emptyStateEl = document.getElementById('emptyLocalState');
// Only show empty state if we're not connected OR we have no files
if (!this.flipper?.isConnected) {
emptyStateEl.style.display = 'block';
} else if (!this.irFilesEl.children.length) {
this.loadIRFiles();
}
break;
case 'database':
this.databaseTab.classList.add('active');
this.databaseContent.style.display = 'block';
this.loadSharedFiles();
break;
case 'home':
this.homeTab.classList.add('active');
this.homeContent.style.display = 'block';
break;
}
}
guessMetadata(filename, pathComponents) {
// Cache the device type map
if (!this.deviceTypeMap) {
this.deviceTypeMap = {
'ACS': 'AC',
'AIR_PURIFIERS': 'Air Purifier',
'AUDIO_AND_VIDEO_RECEIVERS': 'AV Receiver',
'BIDET': 'Bidet',
'BLU-RAY': 'Blu-Ray',
'CCTV': 'CCTV',
'CD_PLAYERS': 'CD Player',
'CABLE_BOXES': 'Cable Box',
'CAMERAS': 'Camera',
'CAR_MULTIMEDIA': 'Car Multimedia',
'CONSOLES': 'Game Console',
'CONVERTERS': 'Converter',
'DVB-T': 'DVB-T',
'DVD_PLAYERS': 'DVD Player',
'DIGITAL_SIGNS': 'Digital Sign',
'FANS': 'Fan',
'FIREPLACES': 'Fireplace',
'HEAD_UNITS': 'Head Unit',
'HEATERS': 'Heater',
'HUMIDIFIERS': 'Humidifier',
'LED_LIGHTING': 'LED Light',
'MONITORS': 'Monitor',
'PROJECTORS': 'Projector',
'SOUNDBARS': 'Soundbar',
'SPEAKERS': 'Speaker',
'STREAMING_DEVICES': 'Streaming Device',
'TVS': 'TV',
'VACUUM_CLEANERS': 'Vacuum',
'VIDEOCONFERENCING': 'Video Conference'
};
}
// Remove .ir extension and split by underscore once
const parts = filename.replace('.ir', '').split('_');
if (parts.length < 2) return null;
// Find device type in path
let deviceType = null;
for (const component of pathComponents) {
const upperComponent = component.toUpperCase().replace(/\s+/g, '_');
if (this.deviceTypeMap[upperComponent]) {
deviceType = this.deviceTypeMap[upperComponent];
break;
}
}
if (!deviceType) return null;
const brand = parts[0].toUpperCase();
const model = parts.slice(1).join('_').toUpperCase();
// Cache regex patterns
if (!this.modelPatterns) {
this.modelPatterns = [
/^[A-Z]{0,3}\d{2,3}[A-Z]{2,3}\d{3,4}[A-Z]?$/,
/^[A-Z]+\d{3,4}[A-Z]?$/,
/^[A-Z]{2,3}\d{2,3}[A-Z]\d{2,3}[A-Z]?(_20\d{2})?$/
];
this.brandPattern = /^[A-Z]{2,15}$/;
}
// Quick validation before more expensive regex tests
if (!this.brandPattern.test(brand)) return null;
// Test model patterns
if (!this.modelPatterns.some(pattern => pattern.test(model))) return null;
return {
brand,
model,
device_type: deviceType,
isGuessed: true
};
}
async confirmGuessedMetadata(filename, metadata) {
return new Promise(resolve => {
const dialog = document.createElement('div');
dialog.className = 'metadata-dialog';
dialog.innerHTML = `
<div class="metadata-dialog-content">
<h3>Guessed Metadata for ${filename}</h3>
<p>We found no metadata in the file but guessed the following:</p>
<div class="metadata-fields">
<div class="field">
<label>Brand:</label>
<input type="text" id="brand" value="${metadata.brand}">
</div>
<div class="field">
<label>Model:</label>
<input type="text" id="model" value="${metadata.model}">
</div>
<div class="field">
<label>Device Type:</label>
<input type="text" id="device_type" value="${metadata.device_type}">
</div>
</div>
<div class="dialog-buttons">
<button class="confirm-btn">Confirm</button>
<button class="cancel-btn">Skip</button>
</div>
</div>
`;
document.body.appendChild(dialog);
const confirmBtn = dialog.querySelector('.confirm-btn');
const cancelBtn = dialog.querySelector('.cancel-btn');
confirmBtn.addEventListener('click', () => {
metadata.brand = dialog.querySelector('#brand').value;
metadata.model = dialog.querySelector('#model').value;
metadata.device_type = dialog.querySelector('#device_type').value;
document.body.removeChild(dialog);
resolve(true);
});
cancelBtn.addEventListener('click', () => {
document.body.removeChild(dialog);
resolve(false);
});
});
}
async saveMetadataToFile(path, content, metadata) {
// Add metadata comments at the start of the file
const metadataComments = [
'# Brand: ' + metadata.brand,
'# Model: ' + metadata.model,
'# Device Type: ' + metadata.device_type
].join('\n');
// Find the position after Filetype and Version headers
const lines = content.split('\n');
let insertPosition = 0;
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith('Version:')) {
insertPosition = i + 1;
break;
}
}
// Insert metadata
lines.splice(insertPosition, 0, metadataComments);
const newContent = lines.join('\n');
// Save back to file
await this.flipper.writeFile(path, newContent);
}
// Add helper method for file size formatting
formatFileSize(bytes) {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}
addDatabaseFileCard(file, viewType = 'grid') {
// Add validation check at the start
if (!file || !file.metadata) {
console.error('Invalid file data:', file);
return null;
}
const { metadata } = file;
// Ensure all required metadata fields exist with fallbacks
const safeMetadata = {
brand: metadata.brand || 'Unknown Brand',
device_type: metadata.device_type || 'Unknown Type',
model: metadata.model || 'Unknown Model',
protocol: metadata.protocol || 'Unknown'
};
let element;
if (viewType === 'list') {
element = document.createElement('div');
element.className = 'ir-list-item';
element.innerHTML = `
<span class="filename" title="${file.name}">${file.name}</span>
<div class="metadata-pills">
<span class="pill" title="Brand">${safeMetadata.brand}</span>
<span class="pill" title="Device Type">${safeMetadata.device_type}</span>
<span class="pill" title="Model">${safeMetadata.model}</span>
</div>
<span class="file-size">${this.formatFileSize(file.size || 0)}</span>
<div class="item-actions">
<button class="download-btn" title="Download to computer">
<svg width="16" height="16" viewBox="0 0 16 16">
<path d="M8 12l-4-4h2.5V3h3v5H12L8 12z" fill="currentColor"/>
<path d="M2 13h12v2H2z" fill="currentColor"/>
</svg>
</button>
<button class="send-to-flipper-btn" title="Send to Flipper">
<div class="button-content">
<svg width="16" height="16" viewBox="0 0 16 16">
<path d="M8 1L5 4h2v8h2V4h2L8 1z" fill="currentColor"/>
</svg>
Send
</div>
</button>
</div>
`;
} else {
element = document.createElement('div');
element.className = 'ir-card';
element.innerHTML = `
<div class="ir-info">
<h3>${safeMetadata.brand}</h3>
<div class="metadata-badges">
<span class="badge device-type" title="Device Category">${safeMetadata.device_type}</span>
<span class="badge model" title="Model">${safeMetadata.model}</span>
<span class="badge protocol" title="Protocol">${safeMetadata.protocol}</span>
</div>
<span class="filename">${file.name || 'Unnamed File'}</span>
<div class="button-group">
<button class="download-btn">
<svg width="16" height="16" viewBox="0 0 16 16">
<path d="M8 12l-4-4h2.5V3h3v5H12L8 12z" fill="currentColor"/>
<path d="M2 13h12v2H2z" fill="currentColor"/>
</svg>
Download
</button>
<button class="send-to-flipper-btn">
<svg width="16" height="16" viewBox="0 0 16 16">
<path d="M8 1L5 4h2v8h2V4h2L8 1z" fill="currentColor"/>
</svg>
Send to Flipper
</button>
</div>
</div>
`;
}
// Add download handler
const downloadBtn = element.querySelector('.download-btn');
downloadBtn.addEventListener('click', () => {
const blob = new Blob([file.content], { type: 'text/plain' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = file.name;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
});
// Add send to flipper handler
const sendToFlipperBtn = element.querySelector('.send-to-flipper-btn');
sendToFlipperBtn.addEventListener('click', async () => {
try {
if (!this.flipper.isConnected) {
throw new Error('Please connect your Flipper Zero first');
}
const savePath = `/ext/infrared/${file.name}`;
await this.flipper.writeFile(savePath, file.content);
this.showAlert('File sent to Flipper successfully!', 'success');
// Refresh local files to show the new file
await this.scanDirectory('/ext/infrared');
} catch (err) {
console.error('Send to Flipper failed:', err);
this.showAlert('Failed to send file to Flipper: ' + err.message);
}
});
return element;
}
// Updated method to handle category chips
updateCategoryChips(files) {
if (!this.categoryChipsEl) return;
this.categoryChipsEl.innerHTML = '';
// Get categories based on current section
const categories = new Set();
const categoryCounts = new Map();
// Extract categories from files
Object.values(files[this.currentSection] || {}).forEach(groupFiles => {
Object.values(groupFiles).forEach(file => {
if (!file.metadata) return;
const category = file.metadata[this.currentSection];
if (category) {
categories.add(category);
categoryCounts.set(category, (categoryCounts.get(category) || 0) + 1);
}
});
});
// Update dropdown options
if (this.activeGroupSelect) {
this.activeGroupSelect.innerHTML = `
<option value="">All Categories</option>
${Array.from(categories).sort().map(category =>
`<option value="${category}">${category} (${categoryCounts.get(category)})</option>`
).join('')}
`;
}
// Create category chips
Array.from(categories).sort().forEach(category => {
const chip = document.createElement('div');
chip.className = 'category-chip';
chip.dataset.category = category;
chip.innerHTML = `
${category}
<span class="count">${categoryCounts.get(category)}</span>
`;
chip.addEventListener('click', () => {
chip.classList.toggle('active');
this.filterFiles();
});
this.categoryChipsEl.appendChild(chip);
});
}
// Improved filter method
filterFiles() {
if (!this.groupedFiles || !this.databaseFilesEl) return;
const filters = {
search: this.searchInput?.value.toLowerCase().trim() || '',
group: this.activeGroupSelect?.value || '',
categories: new Set(
Array.from(this.categoryChipsEl?.querySelectorAll('.category-chip.active') || [])
.map(chip => chip.dataset.category)
)
};
const searchTerms = filters.search.split(/\s+/).filter(term => term.length > 0);
const matchesFilters = (file) => {
if (!file.metadata) return false;
// Search filter - now supports multiple terms
const searchableFields = [
file.name,
file.metadata.brand,
file.metadata.model,
file.metadata.device_type,
file.metadata.protocol // Added protocol to searchable fields
].map(field => (field || '').toLowerCase());
const searchMatch = searchTerms.length === 0 || searchTerms.every(term =>
searchableFields.some(field => field.includes(term))
);
// Group filter
const groupMatch = !filters.group || file.metadata[this.currentSection] === filters.group;
// Category filter
const categoryMatch = filters.categories.size === 0 ||
filters.categories.has(file.metadata[this.currentSection]);
return searchMatch && groupMatch && categoryMatch;
};
// Debounce the actual filtering and UI update
clearTimeout(this._filterTimeout);
this._filterTimeout = setTimeout(() => {
// Get all matching files first
this.filteredFiles = [];
const files = this.groupedFiles[this.currentSection];
Object.values(files || {}).forEach(groupFiles => {
Object.values(groupFiles).forEach(file => {
if (matchesFilters(file)) {
this.filteredFiles.push(file);