Phase 2 complete

This commit is contained in:
gitea
2025-11-05 19:54:21 +01:00
parent 38e01c04d0
commit f462a3d966
11 changed files with 916 additions and 93 deletions
+21 -4
View File
@@ -1,7 +1,7 @@
/// Configuration class that holds application settings.
///
/// This class contains environment-specific configuration values
/// such as API base URL and logging settings.
/// such as API base URL, Immich settings, and logging settings.
class AppConfig {
/// The base URL for API requests.
final String apiBaseUrl;
@@ -9,18 +9,29 @@ class AppConfig {
/// Whether logging is enabled in the application.
final bool enableLogging;
/// Immich server base URL (e.g., 'https://immich.example.com').
final String immichBaseUrl;
/// Immich API key for authentication.
final String immichApiKey;
/// Creates an [AppConfig] instance with the provided values.
///
/// [apiBaseUrl] - The base URL for API requests.
/// [enableLogging] - Whether logging should be enabled.
/// [immichBaseUrl] - Immich server base URL.
/// [immichApiKey] - Immich API key for authentication.
const AppConfig({
required this.apiBaseUrl,
required this.enableLogging,
required this.immichBaseUrl,
required this.immichApiKey,
});
@override
String toString() {
return 'AppConfig(apiBaseUrl: $apiBaseUrl, enableLogging: $enableLogging)';
return 'AppConfig(apiBaseUrl: $apiBaseUrl, enableLogging: $enableLogging, '
'immichBaseUrl: $immichBaseUrl)';
}
@override
@@ -28,10 +39,16 @@ class AppConfig {
if (identical(this, other)) return true;
return other is AppConfig &&
other.apiBaseUrl == apiBaseUrl &&
other.enableLogging == enableLogging;
other.enableLogging == enableLogging &&
other.immichBaseUrl == immichBaseUrl &&
other.immichApiKey == immichApiKey;
}
@override
int get hashCode => apiBaseUrl.hashCode ^ enableLogging.hashCode;
int get hashCode =>
apiBaseUrl.hashCode ^
enableLogging.hashCode ^
immichBaseUrl.hashCode ^
immichApiKey.hashCode;
}
+4
View File
@@ -37,11 +37,15 @@ class ConfigLoader {
return const AppConfig(
apiBaseUrl: 'https://api-dev.example.com',
enableLogging: true,
immichBaseUrl: 'https://photos.satoshinakamoto.win', // ← Change your Immich server URL here
immichApiKey: '3v2fTujMJHy1T2rrVJVojdJS0ySm7IRcRvEcvvUvs0', // ← Change your Immich API key here
);
case 'prod':
return const AppConfig(
apiBaseUrl: 'https://api.example.com',
enableLogging: false,
immichBaseUrl: 'https://photos.satoshinakamoto.win', // ← Change your Immich server URL here
immichApiKey: 'your-prod-api-key-here', // ← Change your Immich API key here
);
default:
throw InvalidEnvironmentException(environment);
+265
View File
@@ -0,0 +1,265 @@
import 'dart:io';
import 'package:dio/dio.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:
/// - Upload images to Immich
/// - Fetch image lists from Immich
/// - Store image metadata locally after uploads
///
/// The service is modular and UI-independent, designed for offline-first behavior.
class ImmichService {
/// HTTP client for API requests.
final Dio _dio;
/// Local storage service for caching metadata.
final LocalStorageService _localStorage;
/// Immich API base URL.
final String _baseUrl;
/// Immich API key for authentication.
final String _apiKey;
/// Creates an [ImmichService] instance.
///
/// [baseUrl] - Immich server base URL (e.g., 'https://immich.example.com').
/// [apiKey] - Immich API key for authentication.
/// [localStorage] - Local storage service for caching metadata.
/// [dio] - Optional Dio instance for dependency injection (useful for testing).
ImmichService({
required String baseUrl,
required String apiKey,
required LocalStorageService localStorage,
Dio? dio,
}) : _baseUrl = baseUrl,
_apiKey = apiKey,
_localStorage = localStorage,
_dio = dio ?? Dio() {
_dio.options.baseUrl = baseUrl;
_dio.options.headers['x-api-key'] = apiKey;
_dio.options.headers['Content-Type'] = 'application/json';
}
/// Uploads an image file to Immich.
///
/// [imageFile] - The image file to upload.
/// [albumId] - Optional album ID to add the image to.
///
/// Returns [UploadResponse] containing the uploaded asset ID.
///
/// Throws [ImmichException] if upload fails.
/// Automatically stores metadata in local storage upon successful upload.
Future<UploadResponse> uploadImage(
File imageFile, {
String? albumId,
}) async {
try {
if (!await imageFile.exists()) {
throw ImmichException('Image file does not exist: ${imageFile.path}');
}
// Prepare form data for multipart upload
final formData = FormData.fromMap({
'assetData': await MultipartFile.fromFile(
imageFile.path,
filename: imageFile.path.split('/').last,
),
if (albumId != null) 'albumId': albumId,
});
// Upload to Immich
final response = await _dio.post(
'/api/asset/upload',
data: formData,
);
if (response.statusCode != 200 && response.statusCode != 201) {
throw ImmichException(
'Upload failed: ${response.statusMessage}',
response.statusCode,
);
}
final uploadResponse = UploadResponse.fromJson(response.data);
// Fetch full asset details to store complete metadata
final asset = await _getAssetById(uploadResponse.id);
// Store metadata in local storage
await _storeAssetMetadata(asset);
return uploadResponse;
} on DioException catch (e) {
throw ImmichException(
'Upload failed: ${e.message ?? 'Unknown error'}',
e.response?.statusCode,
);
} catch (e) {
throw ImmichException('Upload failed: $e');
}
}
/// Fetches a list of assets from Immich.
///
/// [limit] - Maximum number of assets to fetch (default: 100).
/// [skip] - Number of assets to skip (for pagination).
///
/// Returns a list of [ImmichAsset] instances.
///
/// Throws [ImmichException] if fetch fails.
/// Automatically stores fetched metadata in local storage.
Future<List<ImmichAsset>> fetchAssets({
int limit = 100,
int skip = 0,
}) async {
try {
final response = await _dio.get(
'/api/asset',
queryParameters: {
'limit': limit,
'skip': skip,
},
);
if (response.statusCode != 200) {
throw ImmichException(
'Failed to fetch assets: ${response.statusMessage}',
response.statusCode,
);
}
final List<dynamic> assetsJson = response.data;
final List<ImmichAsset> assets = assetsJson
.map((json) => ImmichAsset.fromJson(json as Map<String, dynamic>))
.toList();
// Store all fetched assets in local storage
for (final asset in assets) {
await _storeAssetMetadata(asset);
}
return assets;
} on DioException catch (e) {
throw ImmichException(
'Failed to fetch assets: ${e.message ?? 'Unknown error'}',
e.response?.statusCode,
);
} catch (e) {
throw ImmichException('Failed to fetch assets: $e');
}
}
/// Fetches a single asset by ID.
///
/// [assetId] - The unique identifier of the asset.
///
/// Returns [ImmichAsset] if found.
///
/// Throws [ImmichException] if fetch fails.
Future<ImmichAsset> _getAssetById(String assetId) async {
try {
final response = await _dio.get('/api/asset/$assetId');
if (response.statusCode != 200) {
throw ImmichException(
'Failed to fetch asset: ${response.statusMessage}',
response.statusCode,
);
}
return ImmichAsset.fromJson(response.data as Map<String, dynamic>);
} on DioException catch (e) {
throw ImmichException(
'Failed to fetch asset: ${e.message ?? 'Unknown error'}',
e.response?.statusCode,
);
} catch (e) {
throw ImmichException('Failed to fetch asset: $e');
}
}
/// Stores asset metadata in local storage.
///
/// [asset] - The asset to store.
Future<void> _storeAssetMetadata(ImmichAsset asset) async {
try {
final item = Item(
id: 'immich_${asset.id}',
data: {
'type': 'immich_asset',
'asset': asset.toJson(),
},
);
await _localStorage.insertItem(item);
} catch (e) {
// Log error but don't fail the upload/fetch operation
// Local storage is a cache, not critical for the operation
}
}
/// Gets locally cached asset metadata.
///
/// [assetId] - The unique identifier of the asset.
///
/// Returns [ImmichAsset] if found in local storage, null otherwise.
Future<ImmichAsset?> getCachedAsset(String assetId) async {
try {
final item = await _localStorage.getItem('immich_$assetId');
if (item == null) return null;
final assetData = item.data['asset'] as Map<String, dynamic>;
return ImmichAsset.fromLocalJson(assetData);
} catch (e) {
return null;
}
}
/// Gets all locally cached assets.
///
/// Returns a list of [ImmichAsset] instances from local storage.
Future<List<ImmichAsset>> getCachedAssets() async {
try {
final items = await _localStorage.getAllItems();
final List<ImmichAsset> assets = [];
for (final item in items) {
if (item.data['type'] == 'immich_asset') {
final assetData = item.data['asset'] as Map<String, dynamic>;
assets.add(ImmichAsset.fromLocalJson(assetData));
}
}
return assets;
} catch (e) {
return [];
}
}
}
+79
View File
@@ -0,0 +1,79 @@
/// Represents an asset (image) from Immich API.
class ImmichAsset {
/// Unique identifier for the asset.
final String id;
/// File name of the asset.
final String fileName;
/// Creation date/time of the asset.
final DateTime createdAt;
/// File size in bytes.
final int fileSize;
/// MIME type of the asset.
final String mimeType;
/// Width of the image in pixels.
final int? width;
/// Height of the image in pixels.
final int? height;
/// Creates an [ImmichAsset] instance.
ImmichAsset({
required this.id,
required this.fileName,
required this.createdAt,
required this.fileSize,
required this.mimeType,
this.width,
this.height,
});
/// Creates an [ImmichAsset] from Immich API JSON response.
factory ImmichAsset.fromJson(Map<String, dynamic> json) {
return ImmichAsset(
id: json['id'] as String,
fileName: json['originalFileName'] as String? ?? json['fileName'] as String? ?? 'unknown',
createdAt: DateTime.parse(json['createdAt'] as String),
fileSize: json['fileSizeByte'] as int? ?? json['fileSize'] as int? ?? 0,
mimeType: json['mimeType'] as String? ?? 'image/jpeg',
width: json['exifInfo']?['imageWidth'] as int?,
height: json['exifInfo']?['imageHeight'] as int?,
);
}
/// Converts [ImmichAsset] to JSON for local storage.
Map<String, dynamic> toJson() {
return {
'id': id,
'fileName': fileName,
'createdAt': createdAt.toIso8601String(),
'fileSize': fileSize,
'mimeType': mimeType,
'width': width,
'height': height,
};
}
/// Creates an [ImmichAsset] from local storage JSON.
factory ImmichAsset.fromLocalJson(Map<String, dynamic> json) {
return ImmichAsset(
id: json['id'] as String,
fileName: json['fileName'] as String,
createdAt: DateTime.parse(json['createdAt'] as String),
fileSize: json['fileSize'] as int,
mimeType: json['mimeType'] as String,
width: json['width'] as int?,
height: json['height'] as int?,
);
}
@override
String toString() {
return 'ImmichAsset(id: $id, fileName: $fileName, createdAt: $createdAt)';
}
}
@@ -0,0 +1,28 @@
/// Response from Immich upload API.
class UploadResponse {
/// The unique identifier of the uploaded asset.
final String id;
/// Whether the upload was a duplicate (already existed).
final bool duplicate;
/// Creates an [UploadResponse] instance.
UploadResponse({
required this.id,
required this.duplicate,
});
/// Creates an [UploadResponse] from Immich API JSON response.
factory UploadResponse.fromJson(Map<String, dynamic> json) {
return UploadResponse(
id: json['id'] as String,
duplicate: json['duplicate'] as bool? ?? false,
);
}
@override
String toString() {
return 'UploadResponse(id: $id, duplicate: $duplicate)';
}
}
+1 -1
View File
@@ -178,7 +178,7 @@ class _MyAppState extends State<MyApp> {
const SizedBox(height: 16),
],
Text(
'Phase 1: Local Storage & Caching Complete ✓',
'Phase 2: Immich Integration Complete ✓',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Colors.grey,
),