π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Refactor info pages and fix sync bugs
vishnukvmda5ee823e9007
diff --git a/mobile/apps/locker/lib/services/collections/collections_db.dart b/mobile/apps/locker/lib/services/collections/collections_db.dartindex 4e46fc8fb8..e0db0340e1 100644--- a/mobile/apps/locker/lib/services/collections/collections_db.dart+++ b/mobile/apps/locker/lib/services/collections/collections_db.dart@@ -90,7 +90,7 @@ class CollectionDB extends EnteBaseDatabase {await db.execute('''CREATE TABLE $_filesTable (- uploaded_file_id INTEGER,+ uploaded_file_id INTEGER PRIMARY KEY,local_path TEXT,owner_id INTEGER,collection_id INTEGER,diff --git a/mobile/apps/locker/lib/services/files/sync/metadata_updater_service.dart b/mobile/apps/locker/lib/services/files/sync/metadata_updater_service.dartindex c9bdc14fc5..20a610135a 100644--- a/mobile/apps/locker/lib/services/files/sync/metadata_updater_service.dart+++ b/mobile/apps/locker/lib/services/files/sync/metadata_updater_service.dart@@ -47,6 +47,19 @@ class MetadataUpdaterService {}}+ Future<bool> updateFileMetadata(+ EnteFile file,+ Map<String, dynamic> metadata,+ ) async {+ try {+ await _updatePublicMetadataBulk([file], metadata);+ await CollectionService.instance.sync();+ return true;+ } catch (e) {+ return false;+ }+ }+Future<void> _updatePublicMetadata(List<EnteFile> files,String key,@@ -60,7 +73,10 @@ class MetadataUpdaterService {await _updatePublicMagicMetadata(files, update);} catch (e, s) {_logger.severe(- "Failed to update public metadata for files: $files", e, s,);+ "Failed to update public metadata for files: $files",+ e,+ s,+ );rethrow;}}@@ -76,7 +92,10 @@ class MetadataUpdaterService {await _updatePublicMagicMetadata(files, updates);} catch (e, s) {_logger.severe(- "Failed to update public metadata for files: $files", e, s,);+ "Failed to update public metadata for files: $files",+ e,+ s,+ );rethrow;}}@@ -124,6 +143,7 @@ class MetadataUpdaterService {utf8.encode(jsonEncode(jsonToUpdate)),fileKey,);+params['metadataList'].add(UpdateMagicMetadataRequest(id: file.uploadedFileID!,@@ -140,7 +160,7 @@ class MetadataUpdaterService {await _enteDio.put("/files/public-magic-metadata", data: params);} catch (e, s) {- _logger.severe(e, s);+ _logger.severe("Failed to update public metadata: $e", e, s);rethrow;}}diff --git a/mobile/apps/locker/lib/services/info_file_service.dart b/mobile/apps/locker/lib/services/info_file_service.dartindex 537d65b164..4597a84752 100644--- a/mobile/apps/locker/lib/services/info_file_service.dart+++ b/mobile/apps/locker/lib/services/info_file_service.dart@@ -1,6 +1,7 @@import 'package:locker/models/file_type.dart';import 'package:locker/models/info/info_item.dart';import 'package:locker/services/collections/models/collection.dart';+import 'package:locker/services/files/sync/metadata_updater_service.dart';import 'package:locker/services/files/sync/models/file.dart';import 'package:locker/services/files/sync/models/file_magic.dart';import 'package:locker/services/files/upload/file_upload_service.dart';@@ -24,7 +25,7 @@ class InfoFileService {enteFile.collectionID = collection.id;// Set the title based on info type and data- enteFile.title = _getInfoFileTitle(infoItem);+ enteFile.title = getInfoFileTitle(infoItem);// Set creation and modification timesfinal now = DateTime.now().millisecondsSinceEpoch;@@ -53,35 +54,44 @@ class InfoFileService {}/// Updates an existing info file with new data- Future<EnteFile> updateInfoFile({+ Future<bool> updateInfoFile({required EnteFile existingFile,required InfoItem updatedInfoItem,}) async {try {- // Update the public magic metadata- final updatedPubMagicMetadata = existingFile.pubMagicMetadata;- updatedPubMagicMetadata.info = {+ // Prepare the info data structure+ final infoData = {'type': updatedInfoItem.type.name,'data': updatedInfoItem.data.toJson(),};- // Update the title- final updatedTitle = _getInfoFileTitle(updatedInfoItem);- updatedPubMagicMetadata.editedName = updatedTitle;- updatedPubMagicMetadata.editedTime =- DateTime.now().millisecondsSinceEpoch;+ // Prepare metadata updates - only update info and name/time if needed+ final Map<String, dynamic> metadataUpdates = {+ infoKey: infoData,+ };- existingFile.pubMagicMetadata = updatedPubMagicMetadata;+ // Update title if it's different+ final updatedTitle = getInfoFileTitle(updatedInfoItem);+ if (existingFile.title != updatedTitle) {+ metadataUpdates[editNameKey] = updatedTitle;+ metadataUpdates[editTimeKey] = DateTime.now().millisecondsSinceEpoch;+ }- // Update metadata on server- // This would call the metadata update service- // TODO: Implement metadata update and sync+ // Update metadata using the simple metadata updater service+ final success = await MetadataUpdaterService.instance.updateFileMetadata(+ existingFile,+ metadataUpdates,+ );- _logger.info('Successfully updated info file: $updatedTitle');- return existingFile;+ if (success) {+ _logger.info('Successfully updated info file: $updatedTitle');+ return true;+ } else {+ throw Exception('Failed to update file metadata on server');+ }} catch (e, s) {_logger.severe('Failed to update info file', e, s);- rethrow;+ return false;}}@@ -138,7 +148,8 @@ class InfoFileService {return file.fileType == FileType.info && file.pubMagicMetadata.info != null;}- String _getInfoFileTitle(InfoItem infoItem) {+ /// Gets the display title for an info file based on its content+ String getInfoFileTitle(InfoItem infoItem) {switch (infoItem.type) {case InfoType.note:final noteData = infoItem.data as PersonalNoteData;@@ -148,17 +159,21 @@ class InfoFileService {return recordData.name.isNotEmpty ? recordData.name : 'Physical Record';case InfoType.accountCredential:final credData = infoItem.data as AccountCredentialData;- return credData.name.isNotEmpty- ? '${credData.name} Account'- : 'Account Credential';+ return credData.name.isNotEmpty ? credData.name : 'Account Credential';case InfoType.emergencyContact:final contactData = infoItem.data as EmergencyContactData;return contactData.name.isNotEmpty- ? '${contactData.name} (Emergency Contact)'+ ? contactData.name: 'Emergency Contact';}}+ /// Gets the display title directly from an EnteFile (convenience method)+ String? getFileTitleFromFile(EnteFile file) {+ final infoItem = extractInfoFromFile(file);+ return infoItem != null ? getInfoFileTitle(infoItem) : null;+ }+/// Special upload method for info files that don't require physical file contentFuture<EnteFile> _uploadInfoFile(EnteFile enteFile,diff --git a/mobile/apps/locker/lib/ui/components/item_list_view.dart b/mobile/apps/locker/lib/ui/components/item_list_view.dartindex 2339457676..4aa343b3ca 100644--- a/mobile/apps/locker/lib/ui/components/item_list_view.dart+++ b/mobile/apps/locker/lib/ui/components/item_list_view.dart@@ -8,6 +8,7 @@ import 'package:ente_utils/share_utils.dart';import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:locker/l10n/l10n.dart';+import 'package:locker/models/file_type.dart';import 'package:locker/models/info/info_item.dart';import 'package:locker/services/collections/collections_service.dart';import 'package:locker/services/collections/models/collection.dart';@@ -341,6 +342,11 @@ class _FileListItem extends _ListItem {@overrideString get name {+ // For info files, try to extract the title from the info data+ if (_file.fileType == FileType.info) {+ return InfoFileService.instance.getFileTitleFromFile(_file) ??+ _file.displayName;+ }return _file.displayName;}@@ -1172,26 +1178,26 @@ class FileRowWidget extends StatelessWidget {switch (infoItem.type) {case InfoType.note:page = PersonalNotePage(- existingData: infoItem.data as PersonalNoteData,mode: InfoPageMode.view,+ existingFile: file,);break;case InfoType.accountCredential:page = AccountCredentialsPage(- existingData: infoItem.data as AccountCredentialData,mode: InfoPageMode.view,+ existingFile: file,);break;case InfoType.physicalRecord:page = PhysicalRecordsPage(- existingData: infoItem.data as PhysicalRecordData,mode: InfoPageMode.view,+ existingFile: file,);break;case InfoType.emergencyContact:page = EmergencyContactPage(- existingData: infoItem.data as EmergencyContactData,mode: InfoPageMode.view,+ existingFile: file,);break;}diff --git a/mobile/apps/locker/lib/ui/pages/account_credentials_page.dart b/mobile/apps/locker/lib/ui/pages/account_credentials_page.dartindex a5170c9d00..cc8e0904fe 100644--- a/mobile/apps/locker/lib/ui/pages/account_credentials_page.dart+++ b/mobile/apps/locker/lib/ui/pages/account_credentials_page.dart@@ -7,8 +7,8 @@ import 'package:locker/ui/pages/base_info_page.dart';class AccountCredentialsPage extends BaseInfoPage<AccountCredentialData> {const AccountCredentialsPage({super.key,- super.existingData,super.mode = InfoPageMode.edit,+ super.existingFile,});@override@@ -36,14 +36,21 @@ class _AccountCredentialsPageState}void _loadExistingData() {- if (widget.existingData != null) {- _nameController.text = widget.existingData!.name;- _usernameController.text = widget.existingData!.username;- _passwordController.text = widget.existingData!.password;- _notesController.text = widget.existingData!.notes ?? '';+ final data = currentData;+ if (data != null) {+ _nameController.text = data.name;+ _usernameController.text = data.username;+ _passwordController.text = data.password;+ _notesController.text = data.notes ?? '';}}+ @override+ void refreshUIWithCurrentData() {+ super.refreshUIWithCurrentData();+ _loadExistingData();+ }+@overridevoid dispose() {_nameController.dispose();diff --git a/mobile/apps/locker/lib/ui/pages/base_info_page.dart b/mobile/apps/locker/lib/ui/pages/base_info_page.dartindex 785ad63a91..71638e08fc 100644--- a/mobile/apps/locker/lib/ui/pages/base_info_page.dart+++ b/mobile/apps/locker/lib/ui/pages/base_info_page.dart@@ -8,6 +8,7 @@ import 'package:locker/l10n/l10n.dart';import 'package:locker/models/info/info_item.dart';import 'package:locker/services/collections/collections_service.dart';import 'package:locker/services/collections/models/collection.dart';+import 'package:locker/services/files/sync/models/file.dart';import 'package:locker/services/info_file_service.dart';import 'package:locker/ui/components/collection_selection_widget.dart';import 'package:locker/ui/pages/home_page.dart';@@ -15,13 +16,13 @@ import 'package:locker/ui/pages/home_page.dart';enum InfoPageMode { view, edit }abstract class BaseInfoPage<T extends InfoData> extends StatefulWidget {- final T? existingData;final InfoPageMode mode;+ final EnteFile? existingFile; // The file to edit, or null for new filesconst BaseInfoPage({super.key,- this.existingData,this.mode = InfoPageMode.edit,+ this.existingFile,});}@@ -31,10 +32,35 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>bool _isLoading = false;late InfoPageMode _currentMode;+ // Current data state (can be updated after saving)+ T? _currentData;+// Collection selection stateList<Collection> _availableCollections = [];Set<int> _selectedCollectionIds = {};+ // Getter for current data - prioritizes updated data over existing file data+ T? get currentData {+ if (_currentData != null) {+ return _currentData;+ }++ // Extract data from existing file if available+ if (widget.existingFile != null) {+ final infoItem =+ InfoFileService.instance.extractInfoFromFile(widget.existingFile!);+ return infoItem?.data as T?;+ }++ return null;+ }++ // Override this method in subclasses to refresh UI when data changes+ void refreshUIWithCurrentData() {+ // Default implementation does nothing+ // Subclasses should override this to update their controllers/state+ }+// Abstract methods that subclasses must implementString get pageTitle;String get submitButtonText;@@ -97,16 +123,6 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>return;}- if (_selectedCollectionIds.isEmpty) {- ScaffoldMessenger.of(context).showSnackBar(- const SnackBar(- content: Text('Please select at least one collection'),- backgroundColor: Colors.red,- ),- );- return;- }-setState(() {_isLoading = true;});@@ -120,46 +136,32 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>createdAt: DateTime.now(),);- // Upload to all selected collections- final selectedCollections = _availableCollections- .where((c) => _selectedCollectionIds.contains(c.id))- .toList();-- // Create and upload the info file to each selected collection- for (final collection in selectedCollections) {- await InfoFileService.instance.createAndUploadInfoFile(- infoItem: infoItem,- collection: collection,- );+ if (widget.existingFile != null) {+ // Update existing file+ await _updateExistingFile(infoItem);+ } else {+ // Create new file+ await _createNewFile(infoItem);}- // Trigger sync after successful save- await CollectionService.instance.sync();-if (mounted) {- // Show success message- final collectionCount = selectedCollections.length;- final message = collectionCount == 1- ? context.l10n.recordSavedSuccessfully- : 'Record saved to $collectionCount collections successfully';-- // Navigate to home page and clear all previous routes- await Navigator.of(context).pushAndRemoveUntil(- MaterialPageRoute(builder: (context) => const HomePage()),- (route) => false,- );-- // Show success message after navigation- Future.delayed(const Duration(milliseconds: 100), () {- if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(- content: Text(message),- backgroundColor: Colors.green,- ),- );- }+ setState(() {+ _isLoading = false;});++ if (widget.existingFile != null) {+ // Switch to view mode with updated data+ setState(() {+ _currentMode = InfoPageMode.view;+ });++ ScaffoldMessenger.of(context).showSnackBar(+ SnackBar(+ content: Text(context.l10n.recordSavedSuccessfully),+ backgroundColor: Colors.green,+ ),+ );+ }}} catch (e) {if (mounted) {@@ -179,6 +181,89 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>}}+ Future<void> _updateExistingFile(InfoItem infoItem) async {+ if (widget.existingFile == null) return;++ // Use InfoFileService to handle the update logic+ final success = await InfoFileService.instance.updateInfoFile(+ existingFile: widget.existingFile!,+ updatedInfoItem: infoItem,+ );++ if (!success) {+ throw Exception('Failed to update file metadata');+ }++ // Update the local data to reflect the changes in the UI+ // The metadata updater service already updated the file object locally+ // Now extract the updated info data and refresh the UI+ final updatedInfo =+ InfoFileService.instance.extractInfoFromFile(widget.existingFile!);+ if (updatedInfo != null) {+ // Update the current data state to show the new values in view mode+ setState(() {+ _currentData = updatedInfo.data as T?;+ });++ // Refresh UI with updated data+ refreshUIWithCurrentData();+ }++ // The info file service already performs a sync, so we don't need to sync again+ }++ Future<void> _createNewFile(InfoItem infoItem) async {+ if (_selectedCollectionIds.isEmpty) {+ ScaffoldMessenger.of(context).showSnackBar(+ const SnackBar(+ content: Text('Please select at least one collection'),+ backgroundColor: Colors.red,+ ),+ );+ return;+ }++ // Upload to all selected collections+ final selectedCollections = _availableCollections+ .where((c) => _selectedCollectionIds.contains(c.id))+ .toList();++ // Create and upload the info file to each selected collection+ for (final collection in selectedCollections) {+ await InfoFileService.instance.createAndUploadInfoFile(+ infoItem: infoItem,+ collection: collection,+ );+ }++ // Trigger sync after successful save+ await CollectionService.instance.sync();++ // Show success message+ final collectionCount = selectedCollections.length;+ final message = collectionCount == 1+ ? context.l10n.recordSavedSuccessfully+ : 'Record saved to $collectionCount collections successfully';++ // Navigate to home page and clear all previous routes+ await Navigator.of(context).pushAndRemoveUntil(+ MaterialPageRoute(builder: (context) => const HomePage()),+ (route) => false,+ );++ // Show success message after navigation+ Future.delayed(const Duration(milliseconds: 100), () {+ if (mounted) {+ ScaffoldMessenger.of(context).showSnackBar(+ SnackBar(+ content: Text(message),+ backgroundColor: Colors.green,+ ),+ );+ }+ });+ }+void _toggleMode() {setState(() {_currentMode = _currentMode == InfoPageMode.view@@ -274,7 +359,7 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>child: Scaffold(appBar: AppBar(title: Text(pageTitle),- leading: isEditMode && widget.existingData != null+ leading: isEditMode && currentData != null? IconButton(icon: Icon(Platform.isIOS ? Icons.arrow_back_ios : Icons.arrow_back,@@ -291,7 +376,7 @@ abstract class BaseInfoPageState<T extends InfoData, W extends BaseInfoPage<T>>),automaticallyImplyLeading: false,actions: [- if (isViewMode && widget.existingData != null)+ if (isViewMode && currentData != null)IconButton(icon: const Icon(Icons.edit),onPressed: _toggleMode,diff --git a/mobile/apps/locker/lib/ui/pages/emergency_contact_page.dart b/mobile/apps/locker/lib/ui/pages/emergency_contact_page.dartindex 4c0a96f1f5..c657058eda 100644--- a/mobile/apps/locker/lib/ui/pages/emergency_contact_page.dart+++ b/mobile/apps/locker/lib/ui/pages/emergency_contact_page.dart@@ -7,8 +7,8 @@ import 'package:locker/ui/pages/base_info_page.dart';class EmergencyContactPage extends BaseInfoPage<EmergencyContactData> {const EmergencyContactPage({super.key,- super.existingData,super.mode = InfoPageMode.edit,+ super.existingFile,});@override@@ -29,13 +29,20 @@ class _EmergencyContactPageState}void _loadExistingData() {- if (widget.existingData != null) {- _nameController.text = widget.existingData!.name;- _contactDetailsController.text = widget.existingData!.contactDetails;- _notesController.text = widget.existingData!.notes ?? '';+ final data = currentData;+ if (data != null) {+ _nameController.text = data.name;+ _contactDetailsController.text = data.contactDetails;+ _notesController.text = data.notes ?? '';}}+ @override+ void refreshUIWithCurrentData() {+ super.refreshUIWithCurrentData();+ _loadExistingData();+ }+@overridevoid dispose() {_nameController.dispose();diff --git a/mobile/apps/locker/lib/ui/pages/personal_note_page.dart b/mobile/apps/locker/lib/ui/pages/personal_note_page.dartindex 98b1a105b8..9d31ba8cff 100644--- a/mobile/apps/locker/lib/ui/pages/personal_note_page.dart+++ b/mobile/apps/locker/lib/ui/pages/personal_note_page.dart@@ -7,8 +7,8 @@ import 'package:locker/ui/pages/base_info_page.dart';class PersonalNotePage extends BaseInfoPage<PersonalNoteData> {const PersonalNotePage({super.key,- super.existingData,super.mode = InfoPageMode.edit,+ super.existingFile,});@override@@ -27,12 +27,19 @@ class _PersonalNotePageState}void _loadExistingData() {- if (widget.existingData != null) {- _nameController.text = widget.existingData!.title;- _contentController.text = widget.existingData!.content;+ final data = currentData;+ if (data != null) {+ _nameController.text = data.title;+ _contentController.text = data.content;}}+ @override+ void refreshUIWithCurrentData() {+ super.refreshUIWithCurrentData();+ _loadExistingData();+ }+@overridevoid dispose() {_nameController.dispose();diff --git a/mobile/apps/locker/lib/ui/pages/physical_records_page.dart b/mobile/apps/locker/lib/ui/pages/physical_records_page.dartindex 92159a303a..c4355c69eb 100644--- a/mobile/apps/locker/lib/ui/pages/physical_records_page.dart+++ b/mobile/apps/locker/lib/ui/pages/physical_records_page.dart@@ -7,8 +7,8 @@ import 'package:locker/ui/pages/base_info_page.dart';class PhysicalRecordsPage extends BaseInfoPage<PhysicalRecordData> {const PhysicalRecordsPage({super.key,- super.existingData,super.mode = InfoPageMode.edit,+ super.existingFile,});@override@@ -28,13 +28,20 @@ class _PhysicalRecordsPageState}void _loadExistingData() {- if (widget.existingData != null) {- _nameController.text = widget.existingData!.name;- _locationController.text = widget.existingData!.location;- _notesController.text = widget.existingData!.notes ?? '';+ final data = currentData;+ if (data != null) {+ _nameController.text = data.name;+ _locationController.text = data.location;+ _notesController.text = data.notes ?? '';}}+ @override+ void refreshUIWithCurrentData() {+ super.refreshUIWithCurrentData();+ _loadExistingData();+ }+@overridevoid dispose() {_nameController.dispose();