diff --git a/src/common/services/authService.js b/src/common/services/authService.js index a664ba1..fd4b9de 100644 --- a/src/common/services/authService.js +++ b/src/common/services/authService.js @@ -37,56 +37,64 @@ class AuthService { this.currentUserMode = 'local'; // 'local' or 'firebase' this.currentUser = null; this.isInitialized = false; + this.initializationPromise = null; } initialize() { - if (this.isInitialized) return; + if (this.isInitialized) return this.initializationPromise; - const auth = getFirebaseAuth(); - onAuthStateChanged(auth, async (user) => { - const previousUser = this.currentUser; + this.initializationPromise = new Promise((resolve) => { + const auth = getFirebaseAuth(); + onAuthStateChanged(auth, async (user) => { + const previousUser = this.currentUser; - if (user) { - // User signed IN - console.log(`[AuthService] Firebase user signed in:`, user.uid); - this.currentUser = user; - this.currentUserId = user.uid; - this.currentUserMode = 'firebase'; + if (user) { + // User signed IN + console.log(`[AuthService] Firebase user signed in:`, user.uid); + this.currentUser = user; + this.currentUserId = user.uid; + this.currentUserMode = 'firebase'; - // Start background task to fetch and save virtual key - (async () => { - try { - const idToken = await user.getIdToken(true); - const virtualKey = await getVirtualKeyByEmail(user.email, idToken); + // Start background task to fetch and save virtual key + (async () => { + try { + const idToken = await user.getIdToken(true); + const virtualKey = await getVirtualKeyByEmail(user.email, idToken); - if (global.modelStateService) { - global.modelStateService.setFirebaseVirtualKey(virtualKey); + if (global.modelStateService) { + global.modelStateService.setFirebaseVirtualKey(virtualKey); + } + console.log(`[AuthService] BG: Virtual key for ${user.email} has been processed.`); + + } catch (error) { + console.error('[AuthService] BG: Failed to fetch or save virtual key:', error); } - console.log(`[AuthService] BG: Virtual key for ${user.email} has been processed.`); + })(); - } catch (error) { - console.error('[AuthService] BG: Failed to fetch or save virtual key:', error); - } - })(); - - } else { - // User signed OUT - console.log(`[AuthService] No Firebase user.`); - if (previousUser) { - console.log(`[AuthService] Clearing API key for logged-out user: ${previousUser.uid}`); - if (global.modelStateService) { - global.modelStateService.setFirebaseVirtualKey(null); + } else { + // User signed OUT + console.log(`[AuthService] No Firebase user.`); + if (previousUser) { + console.log(`[AuthService] Clearing API key for logged-out user: ${previousUser.uid}`); + if (global.modelStateService) { + global.modelStateService.setFirebaseVirtualKey(null); + } } + this.currentUser = null; + this.currentUserId = 'default_user'; + this.currentUserMode = 'local'; } - this.currentUser = null; - this.currentUserId = 'default_user'; - this.currentUserMode = 'local'; - } - this.broadcastUserState(); + this.broadcastUserState(); + + if (!this.isInitialized) { + this.isInitialized = true; + console.log('[AuthService] Initialized and resolved initialization promise.'); + resolve(); + } + }); }); - this.isInitialized = true; - console.log('[AuthService] Initialized and attached to Firebase Auth state.'); + return this.initializationPromise; } async signInWithCustomToken(token) { diff --git a/src/common/services/sqliteClient.js b/src/common/services/sqliteClient.js index 5dea2eb..afd64f3 100644 --- a/src/common/services/sqliteClient.js +++ b/src/common/services/sqliteClient.js @@ -157,53 +157,6 @@ class SQLiteClient { return result.length > 0 && result[0].value === 'true'; } - getAutoUpdate(uid = this.defaultUserId) { - try { - const row = this.query( - 'SELECT auto_update_enabled FROM users WHERE uid = ?', - [uid] - ); - - if (row.length > 0) { - return row[0].auto_update_enabled !== 0; - } else { - // User doesn't exist, create them with default settings - const now = Math.floor(Date.now() / 1000); - this.query( - 'INSERT OR REPLACE INTO users (uid, display_name, email, created_at, auto_update_enabled) VALUES (?, ?, ?, ?, ?)', - [uid, 'User', 'user@example.com', now, 1] - ); - return true; // default to enabled - } - } catch (error) { - console.error('Error getting auto_update_enabled setting:', error); - return true; // fallback to enabled - } - } - - setAutoUpdate(isEnabled, uid = this.defaultUserId) { - try { - const result = this.query( - 'UPDATE users SET auto_update_enabled = ? WHERE uid = ?', - [isEnabled ? 1 : 0, uid] - ); - - // If no rows were updated, the user might not exist, so create them - if (result.changes === 0) { - const now = Math.floor(Date.now() / 1000); - this.query( - 'INSERT OR REPLACE INTO users (uid, display_name, email, created_at, auto_update_enabled) VALUES (?, ?, ?, ?, ?)', - [uid, 'User', 'user@example.com', now, isEnabled ? 1 : 0] - ); - } - - return result; - } catch (error) { - console.error('Error setting auto-update:', error); - throw error; - } - } - close() { if (this.db) { try { diff --git a/src/features/settings/SettingsView.js b/src/features/settings/SettingsView.js index f71344f..bd99937 100644 --- a/src/features/settings/SettingsView.js +++ b/src/features/settings/SettingsView.js @@ -492,9 +492,11 @@ export class SettingsView extends LitElement { const { ipcRenderer } = window.require('electron'); this.autoUpdateLoading = true; try { - const enabled = await ipcRenderer.invoke('get-auto-update'); + const enabled = await ipcRenderer.invoke('settings:get-auto-update'); this.autoUpdateEnabled = enabled; + console.log('Auto-update setting loaded:', enabled); } catch (e) { + console.error('Error loading auto-update setting:', e); this.autoUpdateEnabled = true; // fallback } this.autoUpdateLoading = false; @@ -508,8 +510,8 @@ export class SettingsView extends LitElement { this.requestUpdate(); try { const newValue = !this.autoUpdateEnabled; - const success = await ipcRenderer.invoke('set-auto-update', newValue); - if (success) { + const result = await ipcRenderer.invoke('settings:set-auto-update', newValue); + if (result && result.success) { this.autoUpdateEnabled = newValue; } else { console.error('Failed to update auto-update setting'); @@ -687,6 +689,7 @@ export class SettingsView extends LitElement { } else { this.firebaseUser = null; } + this.loadAutoUpdateSetting(); this.requestUpdate(); }; diff --git a/src/features/settings/repositories/index.js b/src/features/settings/repositories/index.js index 508ebe5..973a149 100644 --- a/src/features/settings/repositories/index.js +++ b/src/features/settings/repositories/index.js @@ -18,4 +18,6 @@ module.exports = { createPreset: (...args) => getRepository().createPreset(...args), updatePreset: (...args) => getRepository().updatePreset(...args), deletePreset: (...args) => getRepository().deletePreset(...args), + getAutoUpdate: (...args) => getRepository().getAutoUpdate(...args), + setAutoUpdate: (...args) => getRepository().setAutoUpdate(...args), }; \ No newline at end of file diff --git a/src/features/settings/repositories/sqlite.repository.js b/src/features/settings/repositories/sqlite.repository.js index 6611346..86769d9 100644 --- a/src/features/settings/repositories/sqlite.repository.js +++ b/src/features/settings/repositories/sqlite.repository.js @@ -90,10 +90,57 @@ function deletePreset(id, uid) { } } +function getAutoUpdate(uid) { + const db = sqliteClient.getDb(); + const targetUid = uid; + + try { + const row = db.prepare('SELECT auto_update_enabled FROM users WHERE uid = ?').get(targetUid); + + if (row) { + console.log('SQLite: Auto update setting found:', row.auto_update_enabled); + return row.auto_update_enabled !== 0; + } else { + // User doesn't exist, create them with default settings + const now = Math.floor(Date.now() / 1000); + const stmt = db.prepare( + 'INSERT OR REPLACE INTO users (uid, display_name, email, created_at, auto_update_enabled) VALUES (?, ?, ?, ?, ?)'); + stmt.run(targetUid, 'User', 'user@example.com', now, 1); + return true; // default to enabled + } + } catch (error) { + console.error('SQLite: Error getting auto_update_enabled setting:', error); + return true; // fallback to enabled + } +} + +function setAutoUpdate(uid, isEnabled) { + const db = sqliteClient.getDb(); + const targetUid = uid || sqliteClient.defaultUserId; + + try { + const result = db.prepare('UPDATE users SET auto_update_enabled = ? WHERE uid = ?').run(isEnabled ? 1 : 0, targetUid); + + // If no rows were updated, the user might not exist, so create them + if (result.changes === 0) { + const now = Math.floor(Date.now() / 1000); + const stmt = db.prepare('INSERT OR REPLACE INTO users (uid, display_name, email, created_at, auto_update_enabled) VALUES (?, ?, ?, ?, ?)'); + stmt.run(targetUid, 'User', 'user@example.com', now, isEnabled ? 1 : 0); + } + + return { success: true }; + } catch (error) { + console.error('SQLite: Error setting auto-update:', error); + throw error; + } +} + module.exports = { getPresets, getPresetTemplates, createPreset, updatePreset, - deletePreset + deletePreset, + getAutoUpdate, + setAutoUpdate }; \ No newline at end of file diff --git a/src/features/settings/settingsService.js b/src/features/settings/settingsService.js index 6360f36..76b0d1a 100644 --- a/src/features/settings/settingsService.js +++ b/src/features/settings/settingsService.js @@ -383,6 +383,29 @@ async function updateContentProtection(enabled) { } } +async function getAutoUpdateSetting() { + try { + const uid = authService.getCurrentUserId(); + // This can be awaited if the repository returns a promise. + // Assuming it's synchronous for now based on original structure. + return settingsRepository.getAutoUpdate(uid); + } catch (error) { + console.error('[SettingsService] Error getting auto update setting:', error); + return true; // Fallback to enabled + } +} + +async function setAutoUpdateSetting(isEnabled) { + try { + const uid = authService.getCurrentUserId(); + await settingsRepository.setAutoUpdate(uid, isEnabled); + return { success: true }; + } catch (error) { + console.error('[SettingsService] Error setting auto update setting:', error); + return { success: false, error: error.message }; + } +} + function initialize() { // cleanup windowNotificationManager.cleanup(); @@ -428,6 +451,15 @@ function initialize() { ipcMain.handle('settings:updateContentProtection', async (event, enabled) => { return await updateContentProtection(enabled); }); + + ipcMain.handle('settings:get-auto-update', async () => { + return await getAutoUpdateSetting(); + }); + + ipcMain.handle('settings:set-auto-update', async (event, isEnabled) => { + console.log('[SettingsService] Setting auto update setting:', isEnabled); + return await setAutoUpdateSetting(isEnabled); + }); console.log('[SettingsService] Initialized and ready.'); } @@ -459,4 +491,5 @@ module.exports = { saveApiKey, removeApiKey, updateContentProtection, + getAutoUpdateSetting, }; \ No newline at end of file diff --git a/src/index.js b/src/index.js index 8fa37e4..6015c26 100644 --- a/src/index.js +++ b/src/index.js @@ -190,7 +190,7 @@ app.whenReady().then(async () => { // Clean up zombie sessions from previous runs first sessionRepository.endAllActiveSessions(); - authService.initialize(); + await authService.initialize(); //////// after_modelStateService //////// modelStateService.initialize(); @@ -216,6 +216,7 @@ app.whenReady().then(async () => { ); } + // initAutoUpdater should be called after auth is initialized initAutoUpdater(); // Process any pending deep link after everything is initialized @@ -291,27 +292,6 @@ function setupGeneralIpcHandlers() { return authService.getCurrentUser(); }); - ipcMain.handle('get-auto-update', () => { - const uid = authService.getCurrentUserId(); - try { - return sqliteClient.getAutoUpdate(uid); - } catch (error) { - console.error('Error getting auto-update setting:', error); - return true; // fallback to enabled - } - }); - - ipcMain.handle('set-auto-update', (event, isEnabled) => { - const uid = authService.getCurrentUserId(); - try { - sqliteClient.setAutoUpdate(isEnabled, uid); - return true; - } catch (error) { - console.error('Error setting auto-update:', error); - return false; - } - }); - // --- Web UI Data Handlers (New) --- setupWebDataHandlers(); } @@ -673,9 +653,9 @@ async function startWebStack() { } // Auto-update initialization -function initAutoUpdater() { +async function initAutoUpdater() { try { - const autoUpdateEnabled = sqliteClient.getAutoUpdate(); + const autoUpdateEnabled = await settingsService.getAutoUpdateSetting(); if (!autoUpdateEnabled) { console.log('[AutoUpdater] Skipped because auto-updates are disabled in settings'); return;