-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloud-auth.js
More file actions
1065 lines (903 loc) · 36.8 KB
/
cloud-auth.js
File metadata and controls
1065 lines (903 loc) · 36.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
/**
* Enhanced Cloud Storage Sync Manager
* Automatically detects cloud provider based on browser and uses browser-native APIs
* Works with Google Drive (Chrome), OneDrive (Edge), Dropbox, and other cloud storage
*/
class CloudStorageManager {
constructor() {
this.isConnected = false;
this.provider = null;
this.autoSyncEnabled = false;
this.autoSyncInterval = null;
this.syncFrequency = 15; // minutes
this.userEmail = null;
this.lastSync = null;
this.storage = null;
this.encryptBeforeSync = true;
this.syncFileName = 'productivity-suite-backup.json';
this.fileHandle = null;
this.detectedProvider = null;
this.browserInfo = this.detectBrowser();
this.offlineSyncEnabled = true; // New property for offline sync
}
// ===== BROWSER DETECTION =====
detectBrowser() {
const userAgent = navigator.userAgent;
let browser = 'unknown';
let version = 'unknown';
// Chrome detection
if (userAgent.includes('Chrome') && !userAgent.includes('Edg')) {
browser = 'chrome';
version = userAgent.match(/Chrome\/(\d+)/)?.[1] || 'unknown';
}
// Edge detection
else if (userAgent.includes('Edg')) {
browser = 'edge';
version = userAgent.match(/Edg\/(\d+)/)?.[1] || 'unknown';
}
// Firefox detection
else if (userAgent.includes('Firefox')) {
browser = 'firefox';
version = userAgent.match(/Firefox\/(\d+)/)?.[1] || 'unknown';
}
// Safari detection
else if (userAgent.includes('Safari') && !userAgent.includes('Chrome')) {
browser = 'safari';
version = userAgent.match(/Version\/(\d+)/)?.[1] || 'unknown';
}
return { browser, version, userAgent };
}
// ===== CLOUD PROVIDER DETECTION =====
async detectCloudProvider() {
try {
// Check if user is signed into cloud services via browser
const providers = await this.checkCloudSignIn();
if (providers.length > 0) {
// Prioritize based on browser
const browserPriority = {
'chrome': ['google-drive', 'dropbox', 'onedrive'],
'edge': ['onedrive', 'google-drive', 'dropbox'],
'firefox': ['dropbox', 'google-drive', 'onedrive'],
'safari': ['icloud', 'dropbox', 'google-drive', 'onedrive']
};
const priority = browserPriority[this.browserInfo.browser] || ['google-drive', 'onedrive', 'dropbox'];
// Find the first available provider in priority order
for (const preferredProvider of priority) {
if (providers.includes(preferredProvider)) {
return preferredProvider;
}
}
// Fallback to first available provider
return providers[0];
}
return null;
} catch (error) {
console.error('Error detecting cloud provider:', error);
return null;
}
}
async checkCloudSignIn() {
const providers = [];
try {
// Check for Google Drive (Chrome/Edge)
if (await this.checkGoogleDriveSignIn()) {
providers.push('google-drive');
}
// Check for OneDrive (Edge/Chrome)
if (await this.checkOneDriveSignIn()) {
providers.push('onedrive');
}
// Check for Dropbox
if (await this.checkDropboxSignIn()) {
providers.push('dropbox');
}
// Check for iCloud (Safari)
if (this.browserInfo.browser === 'safari' && await this.checkICloudSignIn()) {
providers.push('icloud');
}
} catch (error) {
console.error('Error checking cloud sign-in status:', error);
}
return providers;
}
async checkGoogleDriveSignIn() {
try {
// Skip cloud detection if running locally (file:// protocol)
if (window.location.protocol === 'file:') {
console.log('Running locally - skipping Google Drive detection');
return false;
}
// Check if user is signed into Google account
const response = await fetch('https://accounts.google.com/gsi/status', {
method: 'GET',
credentials: 'include'
});
if (response.ok) {
const data = await response.json();
return data.signedIn || false;
}
// Alternative check using Google Drive API
try {
const driveResponse = await fetch('https://www.googleapis.com/drive/v3/about?fields=user', {
credentials: 'include'
});
return driveResponse.ok;
} catch (e) {
// Ignore API errors
console.log('Google Drive API check failed:', e.message);
}
return false;
} catch (error) {
console.log('Google Drive sign-in check failed:', error.message);
return false;
}
}
async checkOneDriveSignIn() {
try {
// Skip cloud detection if running locally (file:// protocol)
if (window.location.protocol === 'file:') {
console.log('Running locally - skipping OneDrive detection');
return false;
}
// Check if user is signed into Microsoft account
const response = await fetch('https://graph.microsoft.com/v1.0/me', {
method: 'GET',
credentials: 'include'
});
return response.ok;
} catch (error) {
console.log('OneDrive sign-in check failed:', error.message);
return false;
}
}
async checkDropboxSignIn() {
try {
// Skip cloud detection if running locally (file:// protocol)
if (window.location.protocol === 'file:') {
console.log('Running locally - skipping Dropbox detection');
return false;
}
// Check if user is signed into Dropbox
const response = await fetch('https://api.dropboxapi.com/2/users/get_current_account', {
method: 'POST',
credentials: 'include'
});
return response.ok;
} catch (error) {
console.log('Dropbox sign-in check failed:', error.message);
return false;
}
}
async checkICloudSignIn() {
try {
// Skip cloud detection if running locally (file:// protocol)
if (window.location.protocol === 'file:') {
console.log('Running locally - skipping iCloud detection');
return false;
}
// Check if user is signed into iCloud (Safari)
if (this.browserInfo.browser === 'safari') {
// Safari has built-in iCloud integration
return true;
}
return false;
} catch (error) {
console.log('iCloud sign-in check failed:', error.message);
return false;
}
}
// ===== ENHANCED INITIALIZATION =====
async initialize(storage) {
this.storage = storage;
await this.loadCloudSettings();
// Auto-detect cloud provider on initialization
this.detectedProvider = await this.detectCloudProvider();
this.updateCloudUI();
// Start auto-sync if it was previously enabled
if (this.autoSyncEnabled && this.isConnected) {
this.startAutoSync();
}
// Auto-connect if we're in a background iframe and not already connected
if (this.isInBackgroundIframe() && !this.isConnected) {
console.log('Background iframe detected - attempting auto-connect to cloud storage');
try {
await this.connectToCloud();
if (this.isConnected) {
console.log('Auto-connected to cloud storage in background');
// Enable auto-sync by default in background mode
this.setAutoSyncEnabled(true);
this.startAutoSync();
}
} catch (error) {
console.log('Auto-connect failed in background:', error.message);
}
}
}
async loadCloudSettings() {
try {
const settings = await this.storage.loadEncrypted('cloud-settings');
if (settings) {
this.provider = settings.provider;
this.autoSyncEnabled = settings.autoSyncEnabled || false;
this.syncFrequency = settings.syncFrequency || 15;
this.lastSync = settings.lastSync;
this.userEmail = settings.userEmail;
this.encryptBeforeSync = settings.encryptBeforeSync !== undefined ? settings.encryptBeforeSync : true;
this.syncFileName = settings.syncFileName || 'productivity-suite-backup.json';
this.offlineSyncEnabled = settings.offlineSyncEnabled !== undefined ? settings.offlineSyncEnabled : true;
// Restore file handle if available
if (settings.fileHandle && 'showOpenFilePicker' in window) {
try {
this.fileHandle = await window.showOpenFilePicker({
multiple: false,
types: [{
description: 'Productivity Suite Backup',
accept: { 'application/json': ['.json'] }
}]
});
} catch (error) {
console.log('File handle not restored:', error);
}
}
}
} catch (error) {
console.error('Error loading cloud settings:', error);
}
}
async saveCloudSettings() {
try {
const settings = {
provider: this.provider,
autoSyncEnabled: this.autoSyncEnabled,
syncFrequency: this.syncFrequency,
lastSync: this.lastSync,
userEmail: this.userEmail,
encryptBeforeSync: this.encryptBeforeSync,
syncFileName: this.syncFileName,
offlineSyncEnabled: this.offlineSyncEnabled
};
await this.storage.saveEncrypted('cloud-settings', settings);
} catch (error) {
console.error('Error saving cloud settings:', error);
}
}
// ===== BACKGROUND IFRAME DETECTION =====
isInBackgroundIframe() {
// Skip background iframe detection if running locally (file:// protocol)
if (window.location.protocol === 'file:') {
console.log('Running locally - skipping background iframe detection');
return false;
}
// Check if we're in a hidden iframe (background settings)
const isInIframe = window !== window.top;
const isHidden = document.body.style.display === 'none' ||
document.body.style.visibility === 'hidden' ||
window.location.href.includes('background-settings');
// Additional check for the specific background iframe ID
let isBackgroundIframe = false;
try {
isBackgroundIframe = document.getElementById('background-settings') !== null ||
(window.parent && window.parent.document &&
window.parent.document.getElementById('background-settings') === window.frameElement);
} catch (error) {
// Ignore cross-origin errors
console.log('Cross-origin iframe check failed:', error.message);
}
const result = isInIframe && (isHidden || isBackgroundIframe);
console.log('Background iframe check:', { isInIframe, isHidden, isBackgroundIframe, result });
return result;
}
// ===== ENHANCED CLOUD CONNECTION =====
async connectToCloud() {
try {
console.log('Enhanced connectToCloud called');
// Auto-detect cloud provider if not already set
if (!this.detectedProvider) {
this.detectedProvider = await this.detectCloudProvider();
console.log('Detected cloud provider:', this.detectedProvider);
}
// Check if we're in an iframe (which blocks File System Access API)
const isInIframe = window !== window.top;
// Use File System Access API if available and not in iframe
if ('showSaveFilePicker' in window && !isInIframe) {
console.log('Using File System Access API for cloud sync');
return await this.connectWithFileSystemAPI();
} else {
if (isInIframe) {
console.log('In iframe - using enhanced download/upload mode');
} else {
console.log('File System Access API not supported - using enhanced download/upload mode');
}
return await this.connectWithEnhancedDownloadAPI();
}
} catch (error) {
console.error('Failed to connect to cloud:', error);
throw error;
}
}
async connectWithFileSystemAPI() {
try {
// Suggest filename based on detected provider
const providerNames = {
'google-drive': 'Productivity Suite Backup (Google Drive)',
'onedrive': 'Productivity Suite Backup (OneDrive)',
'dropbox': 'Productivity Suite Backup (Dropbox)',
'icloud': 'Productivity Suite Backup (iCloud)'
};
const suggestedName = providerNames[this.detectedProvider] || this.syncFileName;
// Let user choose where to save the file (Google Drive, OneDrive, etc.)
const fileHandle = await window.showSaveFilePicker({
suggestedName: suggestedName,
types: [{
description: 'Productivity Suite Backup',
accept: { 'application/json': ['.json'] }
}]
});
this.fileHandle = fileHandle;
this.isConnected = true;
this.provider = this.detectedProvider || 'browser-native';
this.userEmail = `Connected to ${this.getProviderDisplayName(this.provider)}`;
// Test the connection by creating a small test file
await this.testConnection();
await this.saveCloudSettings();
this.updateCloudUI();
// Auto-enable sync if this is the first connection
if (!this.autoSyncEnabled) {
this.setAutoSyncEnabled(true);
}
return true;
} catch (error) {
if (error.name === 'AbortError') {
throw new Error('File selection was cancelled');
}
throw error;
}
}
async connectWithEnhancedDownloadAPI() {
// Enhanced fallback for browsers without File System Access API or when in iframe
this.isConnected = true;
this.provider = this.detectedProvider || 'download';
this.userEmail = `Manual sync via ${this.getProviderDisplayName(this.provider)}`;
await this.saveCloudSettings();
this.updateCloudUI();
// Show user instructions for manual sync with detected provider
console.log(`Connected using manual download/upload mode for ${this.getProviderDisplayName(this.provider)}`);
// Auto-enable sync even in manual mode
if (!this.autoSyncEnabled) {
this.setAutoSyncEnabled(true);
}
return true;
}
getProviderDisplayName(provider) {
const names = {
'google-drive': 'Google Drive',
'onedrive': 'OneDrive',
'dropbox': 'Dropbox',
'icloud': 'iCloud',
'browser-native': 'Browser Cloud Storage',
'download': 'Manual Download'
};
return names[provider] || provider;
}
async testConnection() {
if (!this.fileHandle) return false;
try {
const testData = { test: true, timestamp: new Date().toISOString() };
const writable = await this.fileHandle.createWritable();
await writable.write(JSON.stringify(testData, null, 2));
await writable.close();
// Verify we can read it back
const file = await this.fileHandle.getFile();
const content = await file.text();
const parsed = JSON.parse(content);
return parsed.test === true;
} catch (error) {
console.error('Connection test failed:', error);
return false;
}
}
async disconnectFromCloud() {
this.isConnected = false;
this.provider = null;
this.userEmail = null;
this.fileHandle = null;
this.stopAutoSync();
await this.saveCloudSettings();
this.updateCloudUI();
}
// ===== SYNC OPERATIONS =====
async syncToCloud() {
if (!this.isConnected) {
throw new Error('Not connected to cloud storage');
}
try {
// Create complete export of all data
const allData = await this.gatherAllData();
let syncData = allData;
// Apply encryption if enabled
if (this.encryptBeforeSync) {
syncData = await this.encryptData(allData);
}
// Save to cloud using appropriate method
if (this.fileHandle) {
await this.saveWithFileSystemAPI(syncData);
} else {
await this.saveWithDownloadAPI(syncData);
}
this.lastSync = new Date().toISOString();
await this.saveCloudSettings();
this.updateCloudUI();
return true;
} catch (error) {
console.error('Sync failed:', error);
throw error;
}
}
async gatherAllData() {
const allData = {
version: '1.0',
timestamp: new Date().toISOString(),
app: 'Productivity Suite',
tools: {}
};
// Export data from all tools
const toolKeys = [
{ key: 'notebook-data', name: 'notebook' },
{ key: 'pomodoro-data', name: 'pomodoro' },
{ key: 'checklist-data', name: 'checklist' },
{ key: 'eisenhower-data', name: 'eisenhower' }
];
for (const {key, name} of toolKeys) {
try {
const data = await this.storage.loadEncrypted(key);
if (data) {
allData.tools[name] = data;
}
} catch (error) {
console.error(`Error loading ${name}:`, error);
}
}
return allData;
}
async saveWithFileSystemAPI(data) {
if (!this.fileHandle) {
throw new Error('No file handle available');
}
const writable = await this.fileHandle.createWritable();
await writable.write(JSON.stringify(data, null, 2));
await writable.close();
}
async saveWithDownloadAPI(data) {
// Create download link for manual save
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = this.syncFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
async downloadFromCloud() {
if (!this.isConnected) {
throw new Error('Not connected to cloud storage');
}
try {
let data;
if (this.fileHandle) {
data = await this.loadWithFileSystemAPI();
} else {
throw new Error('Please manually upload your backup file');
}
// Decrypt if needed
if (this.encryptBeforeSync) {
data = await this.decryptData(data);
}
// Import data to all tools
await this.importAllData(data);
this.lastSync = new Date().toISOString();
await this.saveCloudSettings();
this.updateCloudUI();
return true;
} catch (error) {
console.error('Download failed:', error);
throw error;
}
}
async loadWithFileSystemAPI() {
if (!this.fileHandle) {
throw new Error('No file handle available');
}
const file = await this.fileHandle.getFile();
const content = await file.text();
return JSON.parse(content);
}
async importAllData(data) {
if (!data.tools) {
throw new Error('Invalid backup file format');
}
for (const [toolName, toolData] of Object.entries(data.tools)) {
try {
const key = `${toolName}-data`;
await this.storage.saveEncrypted(key, toolData);
} catch (error) {
console.error(`Error importing ${toolName}:`, error);
}
}
}
// ===== ENCRYPTION =====
async encryptData(data) {
try {
// Simple encryption - in production, use proper crypto
const dataString = JSON.stringify(data);
const encoded = btoa(unescape(encodeURIComponent(dataString)));
return {
encrypted: true,
data: encoded,
timestamp: new Date().toISOString()
};
} catch (error) {
console.error('Encryption failed:', error);
return data; // Return unencrypted if encryption fails
}
}
async decryptData(encryptedData) {
try {
if (!encryptedData.encrypted) {
return encryptedData;
}
const decoded = decodeURIComponent(escape(atob(encryptedData.data)));
return JSON.parse(decoded);
} catch (error) {
console.error('Decryption failed:', error);
throw new Error('Failed to decrypt data');
}
}
// ===== ENHANCED AUTO SYNC =====
startAutoSync() {
if (this.autoSyncInterval) {
clearInterval(this.autoSyncInterval);
}
this.autoSyncEnabled = true;
// Initial sync after a short delay
setTimeout(async () => {
try {
await this.syncToCloud();
console.log('Initial auto-sync completed successfully');
} catch (error) {
console.error('Initial auto-sync failed:', error);
}
}, 5000); // 5 second delay for initial sync
// Set up recurring sync
this.autoSyncInterval = setInterval(async () => {
try {
await this.syncToCloud();
console.log('Recurring auto-sync completed successfully');
} catch (error) {
console.error('Recurring auto-sync failed:', error);
}
}, this.syncFrequency * 60 * 1000);
this.saveCloudSettings();
this.updateCloudUI();
console.log(`Auto-sync started with ${this.syncFrequency} minute intervals`);
}
stopAutoSync() {
if (this.autoSyncInterval) {
clearInterval(this.autoSyncInterval);
this.autoSyncInterval = null;
}
this.autoSyncEnabled = false;
this.saveCloudSettings();
this.updateCloudUI();
}
setSyncFrequency(minutes) {
this.syncFrequency = minutes;
if (this.autoSyncEnabled) {
this.stopAutoSync();
this.startAutoSync();
}
this.saveCloudSettings();
}
setAutoSyncEnabled(enabled) {
this.autoSyncEnabled = enabled;
if (enabled && this.isConnected) {
this.startAutoSync();
} else {
this.stopAutoSync();
}
this.saveCloudSettings();
this.updateCloudUI();
}
setEncryptBeforeSync(encrypt) {
this.encryptBeforeSync = encrypt;
this.saveCloudSettings();
}
setOfflineSyncEnabled(enabled) {
this.offlineSyncEnabled = enabled;
this.saveCloudSettings();
}
setSyncFrequency(minutes) {
this.syncFrequency = minutes;
this.saveCloudSettings();
// If auto-sync is enabled, restart it with new frequency
if (this.autoSyncEnabled && minutes > 0) {
this.stopAutoSync();
this.startAutoSync();
}
}
// ===== ENHANCED UI UPDATES =====
updateCloudUI() {
// Update connection status
const statusElement = document.getElementById('cloud-connection-status');
const providerElement = document.getElementById('cloud-provider-name');
const lastSyncElement = document.getElementById('cloud-last-sync');
const autoSyncElement = document.getElementById('cloud-auto-sync-status');
if (statusElement) {
statusElement.textContent = this.isConnected ? 'Connected' : 'Not connected';
statusElement.className = this.isConnected ? 'info-value connected' : 'info-value';
}
if (providerElement) {
if (this.isConnected) {
providerElement.textContent = this.getProviderDisplayName(this.provider);
} else {
providerElement.textContent = 'None';
}
}
if (lastSyncElement) {
if (this.lastSync) {
const date = new Date(this.lastSync);
lastSyncElement.textContent = date.toLocaleString();
} else {
lastSyncElement.textContent = 'Never';
}
}
if (autoSyncElement) {
autoSyncElement.textContent = this.autoSyncEnabled ? 'Enabled' : 'Disabled';
}
// Update control buttons
this.updateControlButtons();
// Show browser detection info
this.updateBrowserInfo();
// Notify parent window of sync status (for background iframe)
if (window.parent && window.parent !== window) {
try {
window.parent.postMessage({
type: 'cloud-sync-status',
connected: this.isConnected,
lastSync: this.lastSync,
autoSyncEnabled: this.autoSyncEnabled,
provider: this.provider,
browser: this.browserInfo.browser
}, '*');
} catch (error) {
// Ignore cross-origin errors
}
}
}
updateBrowserInfo() {
// Add browser detection info to the UI if not already present
let browserInfoElement = document.getElementById('browser-info');
if (!browserInfoElement) {
const cloudSection = document.querySelector('.settings-section h3');
if (cloudSection && cloudSection.textContent.includes('Cloud Storage')) {
browserInfoElement = document.createElement('div');
browserInfoElement.id = 'browser-info';
browserInfoElement.className = 'storage-info';
browserInfoElement.style.marginTop = '10px';
browserInfoElement.style.fontSize = '0.85rem';
browserInfoElement.style.color = '#666';
const section = cloudSection.parentNode;
section.insertBefore(browserInfoElement, section.querySelector('.setting-item'));
}
}
if (browserInfoElement) {
const providerName = this.detectedProvider ? this.getProviderDisplayName(this.detectedProvider) : 'None detected';
const isLocal = window.location.protocol === 'file:';
browserInfoElement.innerHTML = `
<div class="info-item">
<span class="info-label">Browser:</span>
<span class="info-value">${this.browserInfo.browser.charAt(0).toUpperCase() + this.browserInfo.browser.slice(1)} ${this.browserInfo.version}</span>
</div>
<div class="info-item">
<span class="info-label">Environment:</span>
<span class="info-value">${isLocal ? 'Local Development' : 'Production'}</span>
</div>
<div class="info-item">
<span class="info-label">Detected Cloud:</span>
<span class="info-value">${providerName}${isLocal ? ' (Cloud detection disabled locally)' : ''}</span>
</div>
`;
}
}
updateControlButtons() {
const connectBtn = document.getElementById('connect-cloud-btn');
const disconnectBtn = document.getElementById('disconnect-cloud-btn');
const syncBtn = document.getElementById('sync-now-btn');
const autoSyncBtn = document.getElementById('toggle-auto-sync-btn');
const providerSelect = document.getElementById('cloud-provider-select');
if (connectBtn) {
connectBtn.disabled = this.isConnected;
connectBtn.style.display = this.isConnected ? 'none' : 'inline-block';
}
if (disconnectBtn) {
disconnectBtn.style.display = this.isConnected ? 'inline-block' : 'none';
}
if (syncBtn) {
syncBtn.style.display = this.isConnected ? 'inline-block' : 'none';
}
if (autoSyncBtn) {
autoSyncBtn.style.display = this.isConnected ? 'inline-block' : 'none';
autoSyncBtn.textContent = `⚙️ Auto-sync: ${this.autoSyncEnabled ? 'ON' : 'OFF'}`;
}
if (providerSelect) {
providerSelect.value = this.provider || '';
}
}
// ===== PUBLIC API =====
async handleConnect() {
try {
console.log('handleConnect called');
await this.connectToCloud();
return { success: true, message: 'Successfully connected to cloud storage' };
} catch (error) {
console.error('handleConnect error:', error);
return { success: false, message: error.message };
}
}
async handleDisconnect() {
try {
await this.disconnectFromCloud();
return { success: true, message: 'Disconnected from cloud storage' };
} catch (error) {
return { success: false, message: error.message };
}
}
async handleSyncNow() {
try {
await this.syncToCloud();
return { success: true, message: 'Data synced successfully' };
} catch (error) {
return { success: false, message: error.message };
}
}
async handleDownload() {
try {
await this.downloadFromCloud();
return { success: true, message: 'Data downloaded successfully' };
} catch (error) {
return { success: false, message: error.message };
}
}
handleToggleAutoSync() {
if (this.autoSyncEnabled) {
this.stopAutoSync();
return { success: true, message: 'Auto-sync disabled' };
} else {
this.startAutoSync();
return { success: true, message: 'Auto-sync enabled' };
}
}
}
// ===== UI MANAGEMENT =====
class CloudAuthUI {
constructor(cloudManager) {
this.cloudManager = cloudManager;
}
initialize() {
this.setupEventListeners();
this.updateUI();
}
setupEventListeners() {
// Cloud provider selection
const providerSelect = document.getElementById('cloud-provider-select');
if (providerSelect) {
providerSelect.addEventListener('change', () => {
this.cloudManager.provider = providerSelect.value;
this.updateUI();
});
}
// Control buttons
const connectBtn = document.getElementById('connect-cloud-btn');
if (connectBtn) {
connectBtn.addEventListener('click', async () => {
console.log('Connect button clicked!');
await this.handleConnect();
});
}
const disconnectBtn = document.getElementById('disconnect-cloud-btn');
if (disconnectBtn) {
disconnectBtn.addEventListener('click', async () => {
await this.handleDisconnect();
});
}
const syncBtn = document.getElementById('sync-now-btn');
if (syncBtn) {
syncBtn.addEventListener('click', async () => {
await this.handleSyncNow();
});
}
const autoSyncBtn = document.getElementById('toggle-auto-sync-btn');
if (autoSyncBtn) {
autoSyncBtn.addEventListener('click', async () => {
await this.handleToggleAutoSync();
});
}
// Sync settings
const encryptCheckbox = document.getElementById('encrypt-before-sync');
if (encryptCheckbox) {
encryptCheckbox.addEventListener('change', (e) => {
this.cloudManager.setEncryptBeforeSync(e.target.checked);
});
}
const frequencySelect = document.getElementById('sync-frequency-select');
if (frequencySelect) {
frequencySelect.addEventListener('change', (e) => {
this.cloudManager.setSyncFrequency(parseInt(e.target.value));
});
}
}
async handleConnect() {
const result = await this.cloudManager.handleConnect();
this.showMessage(result.message, result.success ? 'success' : 'error');
}
async handleDisconnect() {
const result = await this.cloudManager.handleDisconnect();
this.showMessage(result.message, result.success ? 'success' : 'error');
}