mudular code ready to fork

This commit is contained in:
gitea
2025-11-08 12:54:40 +01:00
parent 5f8d8330f5
commit 8c6bf598f5
21 changed files with 288 additions and 519 deletions
+23 -34
View File
@@ -5,22 +5,11 @@ import 'package:firebase_storage/firebase_storage.dart';
import 'package:firebase_auth/firebase_auth.dart' as firebase_auth;
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import '../../core/exceptions/firebase_exception.dart' show FirebaseServiceException;
import '../local/local_storage_service.dart';
import '../local/models/item.dart';
import 'models/firebase_config.dart';
/// Exception thrown when Firebase operations fail.
class FirebaseException implements Exception {
/// Error message.
final String message;
/// Creates a [FirebaseException] with the provided message.
FirebaseException(this.message);
@override
String toString() => 'FirebaseException: $message';
}
/// Service for Firebase integration (optional cloud sync, storage, auth, notifications, analytics).
///
/// This service provides:
@@ -86,7 +75,7 @@ class FirebaseService {
/// Must be called before using any Firebase services.
/// If Firebase is disabled, this method does nothing.
///
/// Throws [FirebaseException] if initialization fails.
/// Throws [FirebaseServiceException] if initialization fails.
Future<void> initialize() async {
if (!config.enabled) {
return; // Firebase disabled, nothing to initialize
@@ -135,7 +124,7 @@ class FirebaseService {
_initialized = true;
} catch (e) {
throw FirebaseException('Failed to initialize Firebase: $e');
throw FirebaseServiceException('Failed to initialize Firebase: $e');
}
}
@@ -146,17 +135,17 @@ class FirebaseService {
///
/// Returns the Firebase Auth user.
///
/// Throws [FirebaseException] if auth is disabled or login fails.
/// Throws [FirebaseServiceException] if auth is disabled or login fails.
Future<firebase_auth.User> loginWithEmailPassword({
required String email,
required String password,
}) async {
if (!config.enabled || !config.authEnabled) {
throw FirebaseException('Firebase Auth is not enabled');
throw FirebaseServiceException('Firebase Auth is not enabled');
}
if (!_initialized || _auth == null) {
throw FirebaseException(
throw FirebaseServiceException(
'Firebase not initialized. Call initialize() first.');
}
@@ -168,20 +157,20 @@ class FirebaseService {
_firebaseUser = credential.user;
return _firebaseUser!;
} catch (e) {
throw FirebaseException('Failed to login: $e');
throw FirebaseServiceException('Failed to login: $e');
}
}
/// Logs out the current user.
///
/// Throws [FirebaseException] if auth is disabled or logout fails.
/// Throws [FirebaseServiceException] if auth is disabled or logout fails.
Future<void> logout() async {
if (!config.enabled || !config.authEnabled) {
throw FirebaseException('Firebase Auth is not enabled');
throw FirebaseServiceException('Firebase Auth is not enabled');
}
if (!_initialized || _auth == null) {
throw FirebaseException(
throw FirebaseServiceException(
'Firebase not initialized. Call initialize() first.');
}
@@ -189,7 +178,7 @@ class FirebaseService {
await _auth!.signOut();
_firebaseUser = null;
} catch (e) {
throw FirebaseException('Failed to logout: $e');
throw FirebaseServiceException('Failed to logout: $e');
}
}
@@ -197,14 +186,14 @@ class FirebaseService {
///
/// [userId] - User ID to associate items with (for multi-user support).
///
/// Throws [FirebaseException] if Firestore is disabled or sync fails.
/// Throws [FirebaseServiceException] if Firestore is disabled or sync fails.
Future<void> syncItemsToFirestore(String userId) async {
if (!config.enabled || !config.firestoreEnabled) {
throw FirebaseException('Firestore is not enabled');
throw FirebaseServiceException('Firestore is not enabled');
}
if (!_initialized || _firestore == null) {
throw FirebaseException(
throw FirebaseServiceException(
'Firestore not initialized. Call initialize() first.');
}
@@ -229,7 +218,7 @@ class FirebaseService {
await batch.commit();
} catch (e) {
throw FirebaseException('Failed to sync items to Firestore: $e');
throw FirebaseServiceException('Failed to sync items to Firestore: $e');
}
}
@@ -237,14 +226,14 @@ class FirebaseService {
///
/// [userId] - User ID to fetch items for.
///
/// Throws [FirebaseException] if Firestore is disabled or sync fails.
/// Throws [FirebaseServiceException] if Firestore is disabled or sync fails.
Future<void> syncItemsFromFirestore(String userId) async {
if (!config.enabled || !config.firestoreEnabled) {
throw FirebaseException('Firestore is not enabled');
throw FirebaseServiceException('Firestore is not enabled');
}
if (!_initialized || _firestore == null) {
throw FirebaseException(
throw FirebaseServiceException(
'Firestore not initialized. Call initialize() first.');
}
@@ -271,7 +260,7 @@ class FirebaseService {
}
}
} catch (e) {
throw FirebaseException('Failed to sync items from Firestore: $e');
throw FirebaseServiceException('Failed to sync items from Firestore: $e');
}
}
@@ -282,14 +271,14 @@ class FirebaseService {
///
/// Returns the download URL.
///
/// Throws [FirebaseException] if Storage is disabled or upload fails.
/// Throws [FirebaseServiceException] if Storage is disabled or upload fails.
Future<String> uploadFile(File file, String path) async {
if (!config.enabled || !config.storageEnabled) {
throw FirebaseException('Firebase Storage is not enabled');
throw FirebaseServiceException('Firebase Storage is not enabled');
}
if (!_initialized || _storage == null) {
throw FirebaseException(
throw FirebaseServiceException(
'Firebase Storage not initialized. Call initialize() first.');
}
@@ -298,7 +287,7 @@ class FirebaseService {
await ref.putFile(file);
return await ref.getDownloadURL();
} catch (e) {
throw FirebaseException('Failed to upload file: $e');
throw FirebaseServiceException('Failed to upload file: $e');
}
}
+42 -60
View File
@@ -1,32 +1,14 @@
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import '../../core/logger.dart';
import '../../core/exceptions/immich_exception.dart';
import '../local/local_storage_service.dart';
import '../local/models/item.dart';
import 'models/immich_asset.dart';
import 'models/upload_response.dart';
/// Exception thrown when Immich API operations fail.
class ImmichException implements Exception {
/// Error message.
final String message;
/// HTTP status code if available.
final int? statusCode;
/// Creates an [ImmichException] with the provided message.
ImmichException(this.message, [this.statusCode]);
@override
String toString() {
if (statusCode != null) {
return 'ImmichException: $message (Status: $statusCode)';
}
return 'ImmichException: $message';
}
}
/// Service for interacting with Immich API.
///
/// This service provides:
@@ -175,15 +157,15 @@ class ImmichService {
}
final uploadUrl = '$_baseUrl$endpointPath';
debugPrint('=== Immich Upload Request ===');
debugPrint('URL: $uploadUrl');
debugPrint('Base URL: $_baseUrl');
debugPrint('File: $fileName, Size: ${await imageFile.length()} bytes');
debugPrint('Device ID: $deviceId');
debugPrint('Device Asset ID: $deviceAssetId');
debugPrint('File Created At: $fileCreatedAtIso');
debugPrint('File Modified At: $fileModifiedAtIso');
debugPrint('Metadata: $metadataJson');
Logger.debug('=== Immich Upload Request ===');
Logger.debug('URL: $uploadUrl');
Logger.debug('Base URL: $_baseUrl');
Logger.debug('File: $fileName, Size: ${await imageFile.length()} bytes');
Logger.debug('Device ID: $deviceId');
Logger.debug('Device Asset ID: $deviceAssetId');
Logger.debug('File Created At: $fileCreatedAtIso');
Logger.debug('File Modified At: $fileModifiedAtIso');
Logger.debug('Metadata: $metadataJson');
final response = await _dio.post(
endpointPath,
@@ -196,17 +178,17 @@ class ImmichService {
),
);
debugPrint('=== Immich Upload Response ===');
debugPrint('Status Code: ${response.statusCode}');
debugPrint('Response Data: ${response.data}');
debugPrint('Response Headers: ${response.headers}');
Logger.debug('=== Immich Upload Response ===');
Logger.debug('Status Code: ${response.statusCode}');
Logger.debug('Response Data: ${response.data}');
Logger.debug('Response Headers: ${response.headers}');
if (response.statusCode != 200 && response.statusCode != 201) {
final errorMessage = response.data is Map
? (response.data as Map)['message']?.toString() ??
response.statusMessage
: response.statusMessage;
debugPrint(
Logger.error(
'Upload failed with status ${response.statusCode}: $errorMessage');
throw ImmichException(
'Upload failed: $errorMessage',
@@ -216,15 +198,15 @@ class ImmichService {
// Log the response data structure
if (response.data is Map) {
debugPrint('Response is Map with keys: ${(response.data as Map).keys}');
debugPrint('Full response map: ${response.data}');
Logger.debug('Response is Map with keys: ${(response.data as Map).keys}');
Logger.debug('Full response map: ${response.data}');
} else if (response.data is List) {
debugPrint(
Logger.debug(
'Response is List with ${(response.data as List).length} items');
debugPrint('First item: ${(response.data as List).first}');
Logger.debug('First item: ${(response.data as List).first}');
} else {
debugPrint('Response type: ${response.data.runtimeType}');
debugPrint('Response value: ${response.data}');
Logger.debug('Response type: ${response.data.runtimeType}');
Logger.debug('Response value: ${response.data}');
}
// Handle response - it might be a single object or an array
@@ -232,7 +214,7 @@ class ImmichService {
if (response.data is List && (response.data as List).isNotEmpty) {
// If response is an array, take the first item
responseData = (response.data as List).first as Map<String, dynamic>;
debugPrint('Using first item from array response');
Logger.debug('Using first item from array response');
} else if (response.data is Map) {
responseData = response.data as Map<String, dynamic>;
} else {
@@ -243,24 +225,24 @@ class ImmichService {
}
final uploadResponse = UploadResponse.fromJson(responseData);
debugPrint('Parsed Upload Response:');
debugPrint(' ID: ${uploadResponse.id}');
debugPrint(' Duplicate: ${uploadResponse.duplicate}');
Logger.debug('Parsed Upload Response:');
Logger.debug(' ID: ${uploadResponse.id}');
Logger.debug(' Duplicate: ${uploadResponse.duplicate}');
// Fetch full asset details to store complete metadata
debugPrint('Fetching full asset details for ID: ${uploadResponse.id}');
Logger.debug('Fetching full asset details for ID: ${uploadResponse.id}');
try {
final asset = await _getAssetById(uploadResponse.id);
debugPrint('Fetched asset: ${asset.id}, ${asset.fileName}');
Logger.debug('Fetched asset: ${asset.id}, ${asset.fileName}');
// Store metadata in local storage
debugPrint('Storing asset metadata in local storage');
Logger.debug('Storing asset metadata in local storage');
await _storeAssetMetadata(asset);
debugPrint('Asset metadata stored successfully');
Logger.debug('Asset metadata stored successfully');
} catch (e) {
// Log error but don't fail the upload - asset was uploaded successfully
debugPrint('Warning: Failed to fetch/store asset metadata: $e');
debugPrint('Upload was successful, but metadata caching failed');
Logger.warning('Failed to fetch/store asset metadata: $e');
Logger.warning('Upload was successful, but metadata caching failed');
}
return uploadResponse;
@@ -558,9 +540,9 @@ class ImmichService {
}
try {
debugPrint('=== Immich Delete Assets ===');
debugPrint('Asset IDs to delete: $assetIds');
debugPrint('Count: ${assetIds.length}');
Logger.debug('=== Immich Delete Assets ===');
Logger.debug('Asset IDs to delete: $assetIds');
Logger.debug('Count: ${assetIds.length}');
// DELETE /api/assets with ids in request body
// According to Immich API: DELETE /api/assets with body: {"ids": ["uuid1", "uuid2", ...]}
@@ -568,7 +550,7 @@ class ImmichService {
'ids': assetIds,
};
debugPrint('Request body: $requestBody');
Logger.debug('Request body: $requestBody');
final response = await _dio.delete(
'/api/assets',
@@ -581,9 +563,9 @@ class ImmichService {
),
);
debugPrint('=== Immich Delete Response ===');
debugPrint('Status Code: ${response.statusCode}');
debugPrint('Response Data: ${response.data}');
Logger.debug('=== Immich Delete Response ===');
Logger.debug('Status Code: ${response.statusCode}');
Logger.debug('Response Data: ${response.data}');
if (response.statusCode != 200 && response.statusCode != 204) {
final errorMessage = response.data is Map
@@ -601,11 +583,11 @@ class ImmichService {
try {
await _localStorage.deleteItem('immich_$assetId');
} catch (e) {
debugPrint('Warning: Failed to remove asset $assetId from cache: $e');
Logger.warning('Failed to remove asset $assetId from cache: $e');
}
}
debugPrint('Successfully deleted ${assetIds.length} asset(s)');
Logger.info('Successfully deleted ${assetIds.length} asset(s)');
} on DioException catch (e) {
final statusCode = e.response?.statusCode;
final errorData = e.response?.data;
+4 -15
View File
@@ -1,26 +1,15 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:nostr_tools/nostr_tools.dart';
import 'package:http/http.dart' as http;
import '../../core/logger.dart';
import '../../core/exceptions/nostr_exception.dart';
import 'models/nostr_keypair.dart';
import 'models/nostr_event.dart';
import 'models/nostr_relay.dart';
import 'models/nostr_profile.dart';
/// Exception thrown when Nostr operations fail.
class NostrException implements Exception {
/// Error message.
final String message;
/// Creates a [NostrException] with the provided message.
NostrException(this.message);
@override
String toString() => 'NostrException: $message';
}
/// Service for interacting with Nostr protocol.
///
/// This service provides:
@@ -492,7 +481,7 @@ class NostrService {
}
} catch (e) {
// Ignore parsing errors
debugPrint('Error parsing profile event: $e');
Logger.warning('Error parsing profile event: $e');
}
} else if (message['type'] == 'EOSE' &&
message['subscription_id'] == reqId) {
@@ -634,7 +623,7 @@ class NostrService {
addedCount++;
} catch (e) {
// Skip invalid relay URLs
debugPrint('Warning: Invalid relay URL from NIP-05: $relayUrl');
Logger.warning('Invalid relay URL from NIP-05: $relayUrl');
}
}
+9 -20
View File
@@ -1,7 +1,8 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import '../../core/logger.dart';
import '../../core/exceptions/session_exception.dart';
import '../local/local_storage_service.dart';
import '../sync/sync_engine.dart';
import '../firebase/firebase_service.dart';
@@ -10,18 +11,6 @@ import '../nostr/models/nostr_keypair.dart';
import '../nostr/models/nostr_profile.dart';
import 'models/user.dart';
/// Exception thrown when session operations fail.
class SessionException implements Exception {
/// Error message.
final String message;
/// Creates a [SessionException] with the provided message.
SessionException(this.message);
@override
String toString() => 'SessionException: $message';
}
/// Service for managing user sessions, login, logout, and session isolation.
///
/// This service provides:
@@ -124,7 +113,7 @@ class SessionService {
await _firebaseService!.syncItemsFromFirestore(user.id);
} catch (e) {
// Log error but don't fail login - offline-first behavior
debugPrint('Warning: Failed to sync from Firebase on login: $e');
Logger.warning('Failed to sync from Firebase on login: $e');
}
}
@@ -174,7 +163,7 @@ class SessionService {
try {
profile = await _nostrService!.fetchProfile(keyPair.publicKey);
} catch (e) {
debugPrint('Warning: Failed to fetch Nostr profile: $e');
Logger.warning('Failed to fetch Nostr profile: $e');
// Continue without profile - offline-first behavior
}
@@ -195,7 +184,7 @@ class SessionService {
await _firebaseService!.syncItemsFromFirestore(user.id);
} catch (e) {
// Log error but don't fail login - offline-first behavior
debugPrint('Warning: Failed to sync from Firebase on login: $e');
Logger.warning('Failed to sync from Firebase on login: $e');
}
}
@@ -230,7 +219,7 @@ class SessionService {
await _firebaseService!.syncItemsToFirestore(userId);
} catch (e) {
// Log error but don't fail logout - offline-first behavior
debugPrint('Warning: Failed to sync to Firebase on logout: $e');
Logger.warning('Failed to sync to Firebase on logout: $e');
}
}
@@ -407,7 +396,7 @@ class SessionService {
try {
profile = await _nostrService!.fetchProfile(_currentUser!.id);
} catch (e) {
debugPrint('Warning: Failed to refresh Nostr profile: $e');
Logger.warning('Failed to refresh Nostr profile: $e');
// Continue without profile update - offline-first behavior
}
@@ -447,11 +436,11 @@ class SessionService {
);
if (addedCount > 0) {
debugPrint('Loaded $addedCount preferred relay(s) from NIP-05: $nip05');
Logger.info('Loaded $addedCount preferred relay(s) from NIP-05: $nip05');
}
} catch (e) {
// Log error but don't fail - offline-first behavior
debugPrint('Warning: Failed to load preferred relays from NIP-05: $e');
Logger.warning('Failed to load preferred relays from NIP-05: $e');
}
}
}
+1 -12
View File
@@ -1,4 +1,5 @@
import 'dart:async';
import '../../core/exceptions/sync_exception.dart';
import '../local/local_storage_service.dart';
import '../immich/immich_service.dart';
import '../nostr/nostr_service.dart';
@@ -6,18 +7,6 @@ import '../nostr/models/nostr_keypair.dart';
import 'models/sync_status.dart';
import 'models/sync_operation.dart';
/// Exception thrown when sync operations fail.
class SyncException implements Exception {
/// Error message.
final String message;
/// Creates a [SyncException] with the provided message.
SyncException(this.message);
@override
String toString() => 'SyncException: $message';
}
/// Engine for coordinating data synchronization between local storage, Immich, and Nostr.
///
/// This service provides: