Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Add to collection and download function

AmanRajSinghMourya96761b831219
diff --git a/mobile/apps/locker/lib/ui/components/add_to_collection_dialog.dart b/mobile/apps/locker/lib/ui/components/add_to_collection_dialog.dart
new file mode 100644
index 0000000000..76d7058943
--- /dev/null
+++ b/mobile/apps/locker/lib/ui/components/add_to_collection_dialog.dart
@@ -0,0 +1,159 @@
+import "package:ente_ui/components/buttons/gradient_button.dart";
+import "package:ente_ui/components/title_bar_title_widget.dart";
+import "package:ente_ui/theme/ente_theme.dart";
+import "package:flutter/material.dart";
+import "package:locker/l10n/l10n.dart";
+import "package:locker/services/collections/models/collection.dart";
+import "package:locker/ui/components/collection_selection_widget.dart";
+import "package:locker/utils/snack_bar_utils.dart";
+
+class AddToCollectionDialogResult {
+ final List<Collection> selectedCollections;
+
+ AddToCollectionDialogResult({
+ required this.selectedCollections,
+ });
+}
+
+class AddToCollectionDialog extends StatefulWidget {
+ final List<Collection> collections;
+
+ const AddToCollectionDialog({
+ super.key,
+ required this.collections,
+ });
+
+ @override
+ State<AddToCollectionDialog> createState() => _AddToCollectionDialogState();
+}
+
+class _AddToCollectionDialogState extends State<AddToCollectionDialog> {
+ final Set<int> _selectedCollectionIds = <int>{};
+ late List<Collection> _availableCollections;
+
+ @override
+ void initState() {
+ super.initState();
+ _availableCollections = List.from(widget.collections);
+ }
+
+ void _toggleCollection(int collectionId) {
+ setState(() {
+ if (_selectedCollectionIds.contains(collectionId)) {
+ _selectedCollectionIds.remove(collectionId);
+ } else {
+ _selectedCollectionIds.add(collectionId);
+ }
+ });
+ }
+
+ void _onCollectionsUpdated(List<Collection> updatedCollections) {
+ setState(() {
+ _availableCollections = updatedCollections;
+ });
+ }
+
+ Future<void> _onCancel() async {
+ Navigator.of(context).pop();
+ }
+
+ Future<void> _onSave() async {
+ final selectedCollections = _availableCollections
+ .where((c) => _selectedCollectionIds.contains(c.id))
+ .toList();
+
+ if (selectedCollections.isEmpty) {
+ SnackBarUtils.showWarningSnackBar(
+ context,
+ context.l10n.pleaseSelectAtLeastOneCollection,
+ );
+ return;
+ }
+
+ Navigator.of(context).pop(
+ AddToCollectionDialogResult(
+ selectedCollections: selectedCollections,
+ ),
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+
+ return Dialog(
+ backgroundColor: colorScheme.backgroundBase,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 360),
+ child: Container(
+ decoration: BoxDecoration(
+ color: colorScheme.backdropBase,
+ borderRadius: BorderRadius.circular(28),
+ boxShadow: [
+ BoxShadow(
+ color: Colors.black.withOpacity(0.08),
+ blurRadius: 24,
+ offset: const Offset(0, 12),
+ ),
+ ],
+ ),
+ padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 32),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ CollectionSelectionWidget(
+ collections: _availableCollections,
+ selectedCollectionIds: _selectedCollectionIds,
+ onToggleCollection: _toggleCollection,
+ onCollectionsUpdated: _onCollectionsUpdated,
+ titleWidget: TitleBarTitleWidget(
+ title: "Add to collection",
+ trailingWidgets: [
+ GestureDetector(
+ onTap: _onCancel,
+ child: Container(
+ height: 36,
+ width: 36,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: colorScheme.backgroundElevated,
+ ),
+ child: const Icon(
+ Icons.close_rounded,
+ size: 20,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(height: 28),
+ SizedBox(
+ width: double.infinity,
+ child: GradientButton(
+ onTap: () async {
+ await _onSave();
+ },
+ text: context.l10n.save,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+Future<AddToCollectionDialogResult?> showAddToCollectionDialog(
+ BuildContext context, {
+ required List<Collection> collections,
+}) async {
+ return showDialog<AddToCollectionDialogResult>(
+ context: context,
+ builder: (context) => AddToCollectionDialog(
+ collections: collections,
+ ),
+ );
+}
diff --git a/mobile/apps/locker/lib/ui/components/file_edit_dialog.dart b/mobile/apps/locker/lib/ui/components/file_edit_dialog.dart
index f1fa72e1fb..38dfc45582 100644
--- a/mobile/apps/locker/lib/ui/components/file_edit_dialog.dart
+++ b/mobile/apps/locker/lib/ui/components/file_edit_dialog.dart
@@ -109,120 +109,117 @@ class _FileEditDialogState extends State<FileEditDialog> {
return Dialog(
backgroundColor: colorScheme.backgroundBase,
- child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 360),
- child: Container(
- decoration: BoxDecoration(
- color: colorScheme.backdropBase,
- borderRadius: BorderRadius.circular(28),
- boxShadow: [
- BoxShadow(
- color: Colors.black.withOpacity(0.08),
- blurRadius: 24,
- offset: const Offset(0, 12),
- ),
- ],
- ),
- padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 32),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- "Rename your document",
- style: textTheme.largeBold,
- ),
- const SizedBox(height: 4),
- Text(
- _fileName,
- style: textTheme.small.copyWith(
- color: colorScheme.textMuted,
- ),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- ],
- ),
- ),
- GestureDetector(
- onTap: _onCancel,
- child: Container(
- height: 36,
- width: 36,
- decoration: BoxDecoration(
- shape: BoxShape.circle,
- color: colorScheme.backgroundElevated,
+ child: Container(
+ decoration: BoxDecoration(
+ color: colorScheme.backdropBase,
+ borderRadius: BorderRadius.circular(28),
+ boxShadow: [
+ BoxShadow(
+ color: Colors.black.withOpacity(0.08),
+ blurRadius: 24,
+ offset: const Offset(0, 12),
+ ),
+ ],
+ ),
+ padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 32),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ "Rename your document",
+ style: textTheme.largeBold,
),
- child: const Icon(
- Icons.close_rounded,
- size: 20,
+ const SizedBox(height: 4),
+ Text(
+ _fileName,
+ style: textTheme.small.copyWith(
+ color: colorScheme.textMuted,
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
),
- ),
- ),
- ],
- ),
- const SizedBox(height: 20),
- TextField(
- controller: _titleController,
- decoration: InputDecoration(
- hintText: "Enter a new name for your document",
- hintStyle: textTheme.body.copyWith(
- color: colorScheme.textMuted,
- ),
- filled: true,
- fillColor: colorScheme.fillFaint,
- contentPadding: const EdgeInsets.symmetric(
- horizontal: 16,
- vertical: 16,
+ ],
),
- border: OutlineInputBorder(
- borderRadius: BorderRadius.circular(8),
- borderSide: BorderSide.none,
- ),
- focusedBorder: OutlineInputBorder(
- borderRadius: BorderRadius.circular(8),
- borderSide: BorderSide(
- color: colorScheme.strokeFaint,
+ ),
+ GestureDetector(
+ onTap: _onCancel,
+ child: Container(
+ height: 36,
+ width: 36,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: colorScheme.backgroundElevated,
+ ),
+ child: const Icon(
+ Icons.close_rounded,
+ size: 20,
),
),
- counterText: "",
),
- maxLength: 200,
- style: textTheme.body.copyWith(
- color: colorScheme.textBase,
+ ],
+ ),
+ const SizedBox(height: 20),
+ TextField(
+ controller: _titleController,
+ decoration: InputDecoration(
+ hintText: "Enter a new name for your document",
+ hintStyle: textTheme.body.copyWith(
+ color: colorScheme.textMuted,
),
- ),
- const SizedBox(height: 24),
- CollectionSelectionWidget(
- collections: _availableCollections,
- selectedCollectionIds: _selectedCollectionIds,
- onToggleCollection: _toggleCollection,
- onCollectionsUpdated: _onCollectionsUpdated,
- singleSelectionMode: true,
- titleWidget: Text(
- "Move to collection",
- style: textTheme.largeBold,
+ filled: true,
+ fillColor: colorScheme.fillFaint,
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 16,
+ vertical: 16,
),
- ),
- const SizedBox(height: 28),
- SizedBox(
- width: double.infinity,
- child: GradientButton(
- onTap: () async {
- await _onSave();
- },
- text: context.l10n.save,
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(8),
+ borderSide: BorderSide.none,
),
+ focusedBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(8),
+ borderSide: BorderSide(
+ color: colorScheme.strokeFaint,
+ ),
+ ),
+ counterText: "",
+ ),
+ maxLength: 200,
+ style: textTheme.body.copyWith(
+ color: colorScheme.textBase,
+ ),
+ ),
+ const SizedBox(height: 24),
+ CollectionSelectionWidget(
+ collections: _availableCollections,
+ selectedCollectionIds: _selectedCollectionIds,
+ onToggleCollection: _toggleCollection,
+ onCollectionsUpdated: _onCollectionsUpdated,
+ singleSelectionMode: true,
+ titleWidget: Text(
+ "Move to collection",
+ style: textTheme.largeBold,
+ ),
+ ),
+ const SizedBox(height: 28),
+ SizedBox(
+ width: double.infinity,
+ child: GradientButton(
+ onTap: () async {
+ await _onSave();
+ },
+ text: context.l10n.save,
),
- ],
- ),
+ ),
+ ],
),
),
);
diff --git a/mobile/apps/locker/lib/ui/viewer/actions/file_selection_overlay_bar.dart b/mobile/apps/locker/lib/ui/viewer/actions/file_selection_overlay_bar.dart
index f5de5cd447..6c7daac8be 100644
--- a/mobile/apps/locker/lib/ui/viewer/actions/file_selection_overlay_bar.dart
+++ b/mobile/apps/locker/lib/ui/viewer/actions/file_selection_overlay_bar.dart
@@ -9,9 +9,11 @@ import "package:locker/services/favorites_service.dart";
import "package:locker/services/files/links/links_service.dart";
import "package:locker/services/files/sync/metadata_updater_service.dart";
import "package:locker/services/files/sync/models/file.dart";
+import "package:locker/ui/components/add_to_collection_dialog.dart";
import "package:locker/ui/components/file_edit_dialog.dart";
import "package:locker/ui/components/selection_action_button_widget.dart";
import "package:locker/ui/components/share_link_dialog.dart";
+import "package:locker/utils/file_util.dart";
import "package:locker/utils/snack_bar_utils.dart";
import "package:logging/logging.dart";
@@ -236,64 +238,85 @@ class _FileSelectionOverlayBarState extends State<FileSelectionOverlayBar> {
final isSingleSelection = selectedFiles.length == 1;
final file = isSingleSelection ? selectedFiles.first : null;
- return AnimatedSwitcher(
- duration: const Duration(milliseconds: 300),
- switchInCurve: Curves.easeInOut,
- switchOutCurve: Curves.easeInOut,
- transitionBuilder: (Widget child, Animation<double> animation) {
- return FadeTransition(
- opacity: animation,
- child: SizeTransition(
- sizeFactor: animation,
- child: child,
- ),
- );
- },
- child: isSingleSelection
- ? Column(
- key: const ValueKey('single_selection'),
- mainAxisSize: MainAxisSize.min,
- children: [
- Row(
- children: [
- Expanded(
- child: SelectionActionButton(
- icon: Icons.download_outlined,
- label: "Download",
- onTap: () => _downloadFile(context, file!),
- ),
- ),
- const SizedBox(width: 12),
- Expanded(
- child: SelectionActionButton(
- icon: Icons.share_outlined,
- label: context.l10n.share,
- onTap: () => _shareLink(context, file!),
- ),
- ),
- const SizedBox(width: 12),
- Expanded(
- child: SelectionActionButton(
- icon: Icons.delete_outline,
- label: context.l10n.delete,
- onTap: () => _deleteFile(context, file!),
- isDestructive: true,
- ),
- ),
- ],
- ),
- const SizedBox(height: 12),
- _buildContinuousActionRow(file!),
- ],
- )
- : _buildMultiSelectionActionRow(selectedFiles.toList()),
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ _buildPrimaryActionRow(selectedFiles.toList()),
+ const SizedBox(height: 12),
+ AnimatedSwitcher(
+ duration: const Duration(milliseconds: 300),
+ switchInCurve: Curves.easeInOut,
+ switchOutCurve: Curves.easeInOut,
+ transitionBuilder: (Widget child, Animation<double> animation) {
+ return FadeTransition(
+ opacity: animation,
+ child: SizeTransition(
+ sizeFactor: animation,
+ child: child,
+ ),
+ );
+ },
+ child: isSingleSelection
+ ? _buildSingleSelectionSecondaryRow(file!)
+ : _buildMultiSelectionSecondaryRow(selectedFiles.toList()),
+ ),
+ ],
);
}
- Widget _buildContinuousActionRow(EnteFile file) {
+ Widget _buildPrimaryActionRow(List<EnteFile> files) {
+ final isSingle = files.length == 1;
final colorScheme = getEnteColorScheme(context);
return Container(
+ decoration: BoxDecoration(
+ color: colorScheme.backgroundElevated2,
+ borderRadius: BorderRadius.circular(24.0),
+ ),
+ child: IntrinsicHeight(
+ child: Row(
+ children: [
+ Expanded(
+ child: SelectionActionButton(
+ icon: Icons.download_outlined,
+ label: "Download",
+ onTap: () => isSingle
+ ? _downloadFile(context, files.first)
+ : _downloadMultipleFiles(context, files),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: SelectionActionButton(
+ icon: Icons.share_outlined,
+ label: context.l10n.share,
+ onTap: () => isSingle
+ ? _shareLink(context, files.first)
+ : _shareMultipleFiles(context),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: SelectionActionButton(
+ icon: Icons.delete_outline,
+ label: context.l10n.delete,
+ onTap: () => isSingle
+ ? _deleteFile(context, files.first)
+ : _deleteMultipleFile(context, files),
+ isDestructive: true,
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _buildSingleSelectionSecondaryRow(EnteFile file) {
+ final colorScheme = getEnteColorScheme(context);
+
+ return Container(
+ key: const ValueKey('single_selection_secondary'),
decoration: BoxDecoration(
color: colorScheme.backgroundElevated2,
borderRadius: BorderRadius.circular(24.0),
@@ -316,17 +339,25 @@ class _FileSelectionOverlayBarState extends State<FileSelectionOverlayBar> {
onTap: () => _toggleImportant(context, file),
),
),
+ const SizedBox(width: 12),
+ Expanded(
+ child: SelectionActionButton(
+ icon: Icons.start_rounded,
+ label: "Add to",
+ onTap: () => _showAddToDialog(context, [file]),
+ ),
+ ),
],
),
),
);
}
- Widget _buildMultiSelectionActionRow(List<EnteFile> files) {
+ Widget _buildMultiSelectionSecondaryRow(List<EnteFile> files) {
final colorScheme = getEnteColorScheme(context);
return Container(
- key: const ValueKey('multi_selection'),
+ key: const ValueKey('multi_selection_secondary'),
decoration: BoxDecoration(
color: colorScheme.backgroundElevated2,
borderRadius: BorderRadius.circular(24.0),
@@ -344,10 +375,9 @@ class _FileSelectionOverlayBarState extends State<FileSelectionOverlayBar> {
const SizedBox(width: 12),
Expanded(
child: SelectionActionButton(
- icon: Icons.delete_outline,
- label: context.l10n.delete,
- onTap: () => _deleteMultipleFile(context, files),
- isDestructive: true,
+ icon: Icons.start_rounded,
+ label: "Add to",
+ onTap: () => _showAddToDialog(context, files),
),
),
],
@@ -356,6 +386,33 @@ class _FileSelectionOverlayBarState extends State<FileSelectionOverlayBar> {
);
}
+ Future<void> _downloadMultipleFiles(
+ BuildContext context,
+ List<EnteFile> files,
+ ) async {
+ try {
+ final success = await FileUtil.downloadFilesToDownloads(context, files);
+ if (success) {
+ widget.selectedFiles.clearAll();
+ }
+ } catch (e, stackTrace) {
+ _logger.severe("Failed to download files: $e", e, stackTrace);
+ if (context.mounted) {
+ SnackBarUtils.showWarningSnackBar(
+ context,
+ context.l10n.failedToDownloadOrDecrypt,
+ );
+ }
+ }
+ }
+
+ void _shareMultipleFiles(BuildContext context) {
+ SnackBarUtils.showWarningSnackBar(
+ context,
+ "Sharing multiple files is coming soon",
+ );
+ }
+
Future<void> _shareLink(BuildContext context, EnteFile file) async {
final dialog = createProgressDialog(
context,
@@ -490,6 +547,91 @@ class _FileSelectionOverlayBarState extends State<FileSelectionOverlayBar> {
}
}
+ Future<void> _showAddToDialog(
+ BuildContext context,
+ List<EnteFile> files,
+ ) async {
+ if (files.isEmpty) {
+ return;
+ }
+
+ final allCollections = await CollectionService.instance.getCollections();
+
+ final result = await showAddToCollectionDialog(
+ context,
+ collections: allCollections,
+ );
+
+ if (result != null && context.mounted) {
+ final dialog = createProgressDialog(
+ context,
+ context.l10n.pleaseWait,
+ isDismissible: false,
+ );
+
+ await dialog.show();
+
+ try {
+ final addFutures = <Future<void>>[];
+
+ for (final file in files) {
+ List<Collection> currentCollections;
+ try {
+ currentCollections =
+ await CollectionService.instance.getCollectionsForFile(file);
+ } catch (_) {
+ currentCollections = <Collection>[];
+ }
+
+ final currentCollectionIds =
+ currentCollections.map((collection) => collection.id).toSet();
+
+ final collectionsToAdd = result.selectedCollections.where(
+ (collection) => !currentCollectionIds.contains(collection.id),
+ );
+
+ for (final collection in collectionsToAdd) {
+ addFutures.add(
+ CollectionService.instance.addToCollection(
+ collection,
+ file,
+ runSync: false,
+ ),
+ );
+ }
+ }
+
+ if (addFutures.isEmpty) {
+ await dialog.hide();
+ SnackBarUtils.showInfoSnackBar(
+ context,
+ context.l10n.noChangesWereMade,
+ );
+ return;
+ }
+
+ await Future.wait(addFutures);
+ await CollectionService.instance.sync();
+
+ await dialog.hide();
+
+ widget.selectedFiles.clearAll();
+
+ SnackBarUtils.showInfoSnackBar(
+ context,
+ context.l10n.fileUpdatedSuccessfully,
+ );
+ } catch (e) {
+ await dialog.hide();
+
+ SnackBarUtils.showWarningSnackBar(
+ context,
+ context.l10n.failedToUpdateFile(e.toString()),
+ );
+ }
+ }
+ }
+
Future<void> _deleteFile(BuildContext context, EnteFile file) async {
final dialog = createProgressDialog(
context,
@@ -561,11 +703,21 @@ class _FileSelectionOverlayBarState extends State<FileSelectionOverlayBar> {
}
Future<void> _downloadFile(BuildContext context, EnteFile file) async {
- // TODO: Implemexnt file download functionality
- SnackBarUtils.showInfoSnackBar(
- context,
- "Download functionality coming soon",
- );
+ try {
+ final success =
+ await FileUtil.downloadFilesToDownloads(context, [file]);
+ if (success) {
+ widget.selectedFiles.clearAll();
+ }
+ } catch (e, stackTrace) {
+ _logger.severe("Failed to download file: $e", e, stackTrace);
+ if (context.mounted) {
+ SnackBarUtils.showWarningSnackBar(
+ context,
+ context.l10n.failedToDownloadOrDecrypt,
+ );
+ }
+ }
}
Future<void> _toggleImportant(BuildContext context, EnteFile file) async {
diff --git a/mobile/apps/locker/lib/utils/file_util.dart b/mobile/apps/locker/lib/utils/file_util.dart
index 7a7c74d315..03a2b04f82 100644
--- a/mobile/apps/locker/lib/utils/file_util.dart
+++ b/mobile/apps/locker/lib/utils/file_util.dart
@@ -1,5 +1,8 @@
+import "dart:convert";
import "dart:io";
+import "dart:typed_data";
+import "package:ente_ui/components/progress_dialog.dart";
import "package:ente_ui/utils/dialog_util.dart";
import "package:flutter/material.dart";
import "package:locker/l10n/l10n.dart";
@@ -14,9 +17,15 @@ import "package:locker/ui/pages/base_info_page.dart";
import "package:locker/ui/pages/emergency_contact_page.dart";
import "package:locker/ui/pages/personal_note_page.dart";
import "package:locker/ui/pages/physical_records_page.dart";
+import "package:locker/utils/snack_bar_utils.dart";
+import "package:logging/logging.dart";
import "package:open_file/open_file.dart";
+import "package:path/path.dart" as p;
+import "package:photo_manager/photo_manager.dart";
class FileUtil {
+ static final Logger _logger = Logger("FileUtil");
+
static Future<void> openFile(BuildContext context, EnteFile file) async {
if (InfoFileService.instance.isInfoFile(file)) {
return _openInfoFile(context, file);
@@ -85,6 +94,310 @@ class FileUtil {
}
}
+ static Future<bool> downloadFilesToDownloads(
+ BuildContext context,
+ List<EnteFile> files,
+ ) async {
+ if (files.isEmpty) {
+ return false;
+ }
+
+ if (!(Platform.isAndroid || Platform.isIOS)) {
+ SnackBarUtils.showWarningSnackBar(
+ context,
+ 'Downloads are only supported on Android and iOS',
+ );
+ return false;
+ }
+
+ final total = files.length;
+ final dialog = createProgressDialog(
+ context,
+ "${context.l10n.downloading} 0/$total",
+ isDismissible: false,
+ );
+
+ await dialog.show();
+
+ var index = 0;
+ final savedNames = <String>[];
+ final savedPaths = <String>[];
+
+ try {
+ for (final file in files) {
+ index += 1;
+ dialog.update(
+ message:
+ '${context.l10n.downloading} ${file.displayName} ($index/$total)',
+ );
+
+ final sanitizedName = _sanitizeFileName(file.displayName);
+ final baseName = _baseNameWithoutExtension(sanitizedName);
+
+ final extension = _extensionWithoutDot(sanitizedName);
+ if (InfoFileService.instance.isInfoFile(file)) {
+ final infoFileName =
+ baseName.endsWith('.json') ? baseName : "$baseName.json";
+ final savedPath = await _saveInfoFile(
+ file: file,
+ fileName: infoFileName,
+ context: context,
+ progressDialog: dialog,
+ currentIndex: index,
+ totalCount: total,
+ );
+ savedNames.add(file.displayName);
+ if (savedPath != null) {
+ savedPaths.add(savedPath);
+ }
+ continue;
+ }
+
+ if (!_isSupportedExtension(extension)) {
+ throw UnsupportedError('Unsupported file type for download');
+ }
+
+ final targetFileName =
+ extension.isEmpty ? baseName : "$baseName.$extension";
+
+ final savedPath = await _saveRegularFile(
+ file: file,
+ targetFileName: targetFileName,
+ context: context,
+ progressDialog: dialog,
+ currentIndex: index,
+ totalCount: total,
+ extension: extension,
+ );
+ savedNames.add(file.displayName);
+ if (savedPath != null) {
+ savedPaths.add(savedPath);
+ }
+ }
+
+ if (savedNames.isNotEmpty) {
+ final message = savedNames.length == 1
+ ? '${savedNames.first} saved to Downloads'
+ : '${savedNames.length} files saved to Downloads';
+ _logger.info('Files saved: $savedPaths');
+ SnackBarUtils.showInfoSnackBar(context, message);
+ }
+
+ return true;
+ } catch (e, s) {
+ _logger.severe('Failed to save files to Downloads', e, s);
+ if (e is UnsupportedError) {
+ SnackBarUtils.showWarningSnackBar(
+ context,
+ 'This file type is not supported for download',
+ );
+ } else {
+ SnackBarUtils.showWarningSnackBar(
+ context,
+ context.l10n.failedToDownloadOrDecrypt,
+ );
+ }
+ return false;
+ } finally {
+ await dialog.hide();
+ }
+ }
+
+ static Future<String?> _saveInfoFile({
+ required EnteFile file,
+ required String fileName,
+ required BuildContext context,
+ required ProgressDialog progressDialog,
+ required int currentIndex,
+ required int totalCount,
+ }) async {
+ final infoItem = InfoFileService.instance.extractInfoFromFile(file);
+ if (infoItem == null) {
+ throw Exception('Unable to extract information from ${file.displayName}');
+ }
+
+ final payload = <String, dynamic>{
+ 'title': file.displayName,
+ 'type': infoItem.type.name,
+ 'data': infoItem.data.toJson(),
+ };
+
+ if (file.creationTime != null) {
+ payload['createdAt'] =
+ DateTime.fromMillisecondsSinceEpoch(file.creationTime!)
+ .toUtc()
+ .toIso8601String();
+ }
+ if (file.modificationTime != null) {
+ payload['updatedAt'] =
+ DateTime.fromMillisecondsSinceEpoch(file.modificationTime!)
+ .toUtc()
+ .toIso8601String();
+ }
+
+ const encoder = JsonEncoder.withIndent(' ');
+ final bytes = Uint8List.fromList(utf8.encode(encoder.convert(payload)));
+
+ // Save JSON file to Downloads directory
+ final String? savedPath = await _saveFileToDownloads(
+ bytes: bytes,
+ fileName: fileName,
+ extension: 'json',
+ );
+
+ if (savedPath == null) {
+ throw Exception('Unable to save ${file.displayName}');
+ }
+
+ progressDialog.update(
+ message:
+ '${context.l10n.downloadingProgress(100)} ($currentIndex/$totalCount)',
+ );
+
+ return savedPath;
+ }
+
+ static Future<String?> _saveRegularFile({
+ required EnteFile file,
+ required String targetFileName,
+ required BuildContext context,
+ required ProgressDialog progressDialog,
+ required int currentIndex,
+ required int totalCount,
+ required String extension,
+ }) async {
+ final fileKey = await CollectionService.instance.getFileKey(file);
+
+ final decryptedFile = await downloadAndDecrypt(
+ file,
+ fileKey,
+ progressCallback: (downloaded, total) {
+ if (total > 0 && downloaded >= 0) {
+ final percentage = ((downloaded / total) * 100).clamp(0, 100).round();
+ progressDialog.update(
+ message:
+ '${context.l10n.downloadingProgress(percentage)} ($currentIndex/$totalCount)',
+ );
+ }
+ },
+ shouldUseCache: false,
+ );
+
+ if (decryptedFile == null) {
+ throw Exception('Failed to download ${file.displayName}');
+ }
+
+ try {
+ // Determine file type and use appropriate save method
+ final isImage = _isImageExtension(extension);
+ String? savedPath;
+
+ if (isImage) {
+ // Save images to gallery using PhotoManager
+ final assetEntity = await PhotoManager.editor.saveImageWithPath(
+ decryptedFile.path,
+ title: targetFileName,
+ );
+ savedPath = assetEntity.relativePath;
+ } else {
+ // For PDFs, text files, and other non-image files
+ final fileBytes = await decryptedFile.readAsBytes();
+ savedPath = await _saveFileToDownloads(
+ bytes: fileBytes,
+ fileName: targetFileName,
+ extension: extension,
+ );
+ if (savedPath == null) {
+ throw Exception('Failed to save file to Downloads');
+ }
+ }
+
+ progressDialog.update(
+ message:
+ '${context.l10n.downloadingProgress(100)} ($currentIndex/$totalCount)',
+ );
+ return savedPath;
+ } finally {
+ try {
+ await decryptedFile.delete();
+ } catch (e) {
+ _logger.fine(
+ 'Unable to delete temporary file ${decryptedFile.path}: $e',
+ );
+ }
+ }
+ }
+
+ static bool _isImageExtension(String extension) {
+ const imageExtensions = <String>{
+ 'png',
+ 'jpg',
+ 'jpeg',
+ 'gif',
+ 'heic',
+ 'heif',
+ 'webp',
+ 'svg',
+ };
+ return imageExtensions.contains(extension.toLowerCase());
+ }
+
+ /// Saves non-image files (PDF, TXT, JSON) to Downloads folder
+ /// Returns the path where the file was saved, or null if it failed
+ static Future<String?> _saveFileToDownloads({
+ required Uint8List bytes,
+ required String fileName,
+ required String extension,
+ }) async {
+ if (!Platform.isAndroid && !Platform.isIOS) {
+ _logger.warning('Downloads folder only supported on Android and iOS');
+ return null;
+ }
+
+ if (Platform.isAndroid) {
+ // For Android, use direct file write to Downloads
+ // This works for Android 10 and below with WRITE_EXTERNAL_STORAGE permission
+ // For Android 11+, we rely on the app having MANAGE_EXTERNAL_STORAGE or use SAF
+ try {
+ const downloadsPath = '/storage/emulated/0/Download';
+ final sanitizedName = _sanitizeFileName(fileName);
+ final fullFileName =
+ extension.isEmpty ? sanitizedName : '$sanitizedName.$extension';
+ final targetFile = File('$downloadsPath/$fullFileName');
+
+ await targetFile.writeAsBytes(bytes);
+ _logger.info('File saved to: ${targetFile.path}');
+ return targetFile.path;
+ } catch (e, s) {
+ _logger.severe('Failed to save file to Downloads on Android', e, s);
+ return null;
+ }
+ } else {
+ // iOS doesn't have a public Downloads folder accessible to apps
+ // Files must be saved to app-specific directories
+ _logger.warning('iOS does not support saving to public Downloads folder');
+ return null;
+ }
+ }
+
+ static String _sanitizeFileName(String name) {
+ final sanitized = name.replaceAll(RegExp(r'[\\/:*?"<>|]'), '_').trim();
+ return sanitized.isEmpty ? "file" : sanitized;
+ }
+
+ static String _baseNameWithoutExtension(String name) {
+ final base = p.basenameWithoutExtension(name).trim();
+ return base.isEmpty ? "file" : base;
+ }
+
+ static String _extensionWithoutDot(String name) {
+ final ext = p.extension(name);
+ if (ext.isEmpty) {
+ return '';
+ }
+ return ext.replaceAll('.', '').replaceAll(RegExp(r'[\\/:*?"<>|]'), '');
+ }
+
static Future<void> _openInfoFile(BuildContext context, EnteFile file) async {
try {
final infoItem = InfoFileService.instance.extractInfoFromFile(file);
@@ -152,4 +465,20 @@ class FileUtil {
);
}
}
+
+ static bool _isSupportedExtension(String extension) {
+ const supported = <String>{
+ 'png',
+ 'jpg',
+ 'jpeg',
+ 'gif',
+ 'heic',
+ 'heif',
+ 'webp',
+ 'svg',
+ 'pdf',
+ 'txt',
+ };
+ return supported.contains(extension.toLowerCase());
+ }
}