refactor autoUpdate
This commit is contained in:
		
							parent
							
								
									ee28516a4e
								
							
						
					
					
						commit
						e87c73058a
					
				@ -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) {
 | 
			
		||||
 | 
			
		||||
@ -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 {
 | 
			
		||||
 | 
			
		||||
@ -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();
 | 
			
		||||
        };
 | 
			
		||||
        
 | 
			
		||||
 | 
			
		||||
@ -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),
 | 
			
		||||
};
 | 
			
		||||
@ -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
 | 
			
		||||
};
 | 
			
		||||
@ -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,
 | 
			
		||||
};
 | 
			
		||||
							
								
								
									
										28
									
								
								src/index.js
									
									
									
									
									
								
							
							
						
						
									
										28
									
								
								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;
 | 
			
		||||
 | 
			
		||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user