Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mobile][locker] rename files in file upload screen (#13059)

Aaqil Fazilf53a14751f7f
diff --git a/mobile/apps/locker/changes/rename-files-during-upload.md b/mobile/apps/locker/changes/rename-files-during-upload.md
new file mode 100644
index 0000000000..61f2709f52
--- /dev/null
+++ b/mobile/apps/locker/changes/rename-files-during-upload.md
@@ -0,0 +1 @@
+- Rename documents during the upload (@fosszil)
\ No newline at end of file
diff --git a/mobile/apps/locker/lib/services/files/download/file_downloader.dart b/mobile/apps/locker/lib/services/files/download/file_downloader.dart
index 351b9c3070..45b89ca24b 100644
--- a/mobile/apps/locker/lib/services/files/download/file_downloader.dart
+++ b/mobile/apps/locker/lib/services/files/download/file_downloader.dart
@@ -5,6 +5,7 @@ import 'package:dio/dio.dart';
import 'package:ente_crypto_api/ente_crypto_api.dart';
import 'package:ente_network/network.dart';
import 'package:ente_pure_utils/ente_pure_utils.dart';
+import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:locker/service_locator.dart';
import 'package:locker/services/configuration.dart';
import 'package:locker/services/db/locker_db.dart';
@@ -13,14 +14,13 @@ import 'package:locker/services/files/download/models/task.dart';
import 'package:locker/services/files/offline/offline_file_storage.dart';
import 'package:locker/services/files/sync/models/file.dart';
import 'package:logging/logging.dart';
-import 'package:path/path.dart' as p;
final _logger = Logger("FileDownloader");
-String _getTemporaryDecryptedFilePath(EnteFile file) {
+@visibleForTesting
+String getTemporaryDecryptedFilePath(EnteFile file) {
final String tempDir = Configuration.instance.getTempDirectory();
- final String safeDisplayName = p.basename(file.displayName);
- return "$tempDir${file.uploadedFileID}_$safeDisplayName";
+ return "$tempDir${file.uploadedFileID}.decrypted";
}
Future<File> ensureEncryptedOfflineCopy(
@@ -143,7 +143,7 @@ Future<File?> openFile(
final String logPrefix = 'File-${file.uploadedFileID}:';
final int startTime = DateTime.now().millisecondsSinceEpoch;
final String decryptedFilePath = useTemporaryDecryptedFile
- ? _getTemporaryDecryptedFilePath(file)
+ ? getTemporaryDecryptedFilePath(file)
: getCachedDecryptedFilePath(file);
final File decryptedFile = File(decryptedFilePath);
final int sizeInBytes =
@@ -221,7 +221,7 @@ Future<File?> downloadAndDecrypt(
final String decryptedFilePath = shouldUseCache
? cachedDecryptedFilePath
- : _getTemporaryDecryptedFilePath(file);
+ : getTemporaryDecryptedFilePath(file);
final File decryptedFile = File(decryptedFilePath);
final startTime = DateTime.now().millisecondsSinceEpoch;
diff --git a/mobile/apps/locker/lib/services/files/offline/offline_file_storage.dart b/mobile/apps/locker/lib/services/files/offline/offline_file_storage.dart
index bcae82d52c..c464513f9b 100644
--- a/mobile/apps/locker/lib/services/files/offline/offline_file_storage.dart
+++ b/mobile/apps/locker/lib/services/files/offline/offline_file_storage.dart
@@ -8,6 +8,7 @@ import 'package:path_provider/path_provider.dart';
const _offlineEncryptedDirName = 'offline_documents';
const _openHandoffDirName = 'open_handoff';
+const _decryptedCacheSuffix = '.decrypted';
final _logger = Logger('OfflineFileStorage');
String _safeExtension(String fileName) {
@@ -37,7 +38,16 @@ String getPreferredFileExtension(
return nameExtension;
}
- final pathExtension = _safeExtension(fallbackPath ?? '');
+ final path = fallbackPath ?? '';
+ final uploadedFileID = file?.uploadedFileID;
+ final isInternalDecryptedCache =
+ uploadedFileID != null &&
+ p.basename(path) == '$uploadedFileID$_decryptedCacheSuffix';
+ if (isInternalDecryptedCache) {
+ return '';
+ }
+
+ final pathExtension = _safeExtension(path);
if (pathExtension.isNotEmpty) {
return pathExtension;
}
@@ -48,7 +58,7 @@ String getPreferredFileExtension(
String getCachedDecryptedFilePath(EnteFile file) {
final String cacheDir = Configuration.instance.getCacheDirectory();
final String extension = getPreferredFileExtension(file);
- return "$cacheDir${file.uploadedFileID}.decrypted$extension";
+ return "$cacheDir${file.uploadedFileID}$_decryptedCacheSuffix$extension";
}
String getOpenHandoffDirectoryPath() {
diff --git a/mobile/apps/locker/lib/services/files/sync/models/file.dart b/mobile/apps/locker/lib/services/files/sync/models/file.dart
index 3ef631ae66..f8546efdd6 100644
--- a/mobile/apps/locker/lib/services/files/sync/models/file.dart
+++ b/mobile/apps/locker/lib/services/files/sync/models/file.dart
@@ -48,10 +48,10 @@ class EnteFile {
static final _logger = Logger('File');
- static EnteFile fromFile(File file) {
+ static EnteFile fromFile(File file, {String? fileName}) {
final enteFile = EnteFile();
enteFile.localPath = file.path;
- enteFile.title = file.path.split('/').last;
+ enteFile.title = fileName ?? file.path.split('/').last;
enteFile.creationTime = file.statSync().changed.millisecondsSinceEpoch;
enteFile.modificationTime = file.statSync().modified.millisecondsSinceEpoch;
enteFile.fileType = FileType.other;
diff --git a/mobile/apps/locker/lib/services/files/upload/file_upload_service.dart b/mobile/apps/locker/lib/services/files/upload/file_upload_service.dart
index 1a5dd99083..409b04acaf 100644
--- a/mobile/apps/locker/lib/services/files/upload/file_upload_service.dart
+++ b/mobile/apps/locker/lib/services/files/upload/file_upload_service.dart
@@ -72,11 +72,20 @@ class FileUploader {
}
}
- Future<EnteFile> upload(File file, Collection collection) {
+ Future<EnteFile> upload(
+ File file,
+ Collection collection, {
+ String? fileName,
+ }) {
_totalCountInUploadSession++;
final String path = file.path;
final completer = Completer<EnteFile>();
- _queue[path] = FileUploadItem(file, collection, completer);
+ _queue[path] = FileUploadItem(
+ file,
+ collection,
+ completer,
+ fileName: fileName,
+ );
_allBackups[path] = BackupItem(
status: BackupItemStatus.inQueue,
file: file,
@@ -213,6 +222,7 @@ class FileUploader {
_encryptAndUploadFileToCollection(
pendingEntry.file,
pendingEntry.collection,
+ fileName: pendingEntry.fileName,
);
}
}
@@ -222,12 +232,18 @@ class FileUploader {
File file,
Collection collection, {
bool forcedUpload = false,
+ String? fileName,
}) async {
_uploadCounter++;
final path = file.path;
try {
- final uploadedFile = await _tryToUpload(file, collection, forcedUpload)
- .timeout(
+ final uploadedFile =
+ await _tryToUpload(
+ file,
+ collection,
+ forcedUpload,
+ fileName: fileName,
+ ).timeout(
kFileUploadTimeout,
onTimeout: () {
const message = "Upload timed out for file";
@@ -281,8 +297,9 @@ class FileUploader {
Future<EnteFile> _tryToUpload(
File file,
Collection collection,
- bool forcedUpload,
- ) async {
+ bool forcedUpload, {
+ String? fileName,
+ }) async {
if (_allBackups[file.path] != null &&
_allBackups[file.path]!.status != BackupItemStatus.uploading) {
_allBackups[file.path] = _allBackups[file.path]!.copyWith(
@@ -384,7 +401,7 @@ class FileUploader {
fileMd5,
);
- final enteFile = EnteFile.fromFile(file);
+ final enteFile = EnteFile.fromFile(file, fileName: fileName);
final encryptedMetadataResult = await CryptoUtil.encryptData(
utf8.encode(jsonEncode(enteFile.metadata)),
@@ -809,6 +826,7 @@ class FileUploader {
class FileUploadItem {
final File file;
+ final String? fileName;
final Collection collection;
final Completer<EnteFile> completer;
UploadStatus status;
@@ -817,6 +835,7 @@ class FileUploadItem {
this.file,
this.collection,
this.completer, {
+ this.fileName,
this.status = UploadStatus.notStarted,
});
}
diff --git a/mobile/apps/locker/lib/ui/components/text_input_sheet.dart b/mobile/apps/locker/lib/ui/components/text_input_sheet.dart
index 3da04ca851..7fffdff59f 100644
--- a/mobile/apps/locker/lib/ui/components/text_input_sheet.dart
+++ b/mobile/apps/locker/lib/ui/components/text_input_sheet.dart
@@ -8,6 +8,7 @@ Future<dynamic> showTextInputSheet(
required String hintText,
required String submitButtonLabel,
required FutureVoidCallbackParamStr onSubmit,
+ String? Function(String)? validator,
String? initialValue,
TextCapitalization textCapitalization = TextCapitalization.words,
int? maxLength,
@@ -18,6 +19,7 @@ Future<dynamic> showTextInputSheet(
var isSubmitting = false;
final canSubmit = ValueNotifier<bool>(currentText.trim().isNotEmpty);
+ final validationError = ValueNotifier<String?>(null);
final controller = selectInitialValue
? TextEditingController.fromValue(
TextEditingValue(
@@ -36,6 +38,9 @@ Future<dynamic> showTextInputSheet(
return;
}
+ validationError.value = validator?.call(text);
+ if (validationError.value != null) return;
+
isSubmitting = true;
try {
@@ -56,19 +61,27 @@ Future<dynamic> showTextInputSheet(
builder: (sheetContext) => BottomSheetComponent(
title: title,
isKeyboardAware: true,
- content: TextInputComponent(
- controller: controller,
- initialValue: controller == null ? initialValue : null,
- hintText: hintText,
- autofocus: true,
- maxLength: maxLength,
- textCapitalization: textCapitalization,
- isPasswordInput: isPasswordInput,
- onChanged: (value) {
- currentText = value;
- canSubmit.value = value.trim().isNotEmpty;
- },
- onSubmit: (value) => submit(sheetContext, value),
+ content: ValueListenableBuilder<String?>(
+ valueListenable: validationError,
+ builder: (_, error, _) => TextInputComponent(
+ controller: controller,
+ initialValue: controller == null ? initialValue : null,
+ hintText: hintText,
+ autofocus: true,
+ maxLength: maxLength,
+ textCapitalization: textCapitalization,
+ isPasswordInput: isPasswordInput,
+ message: error,
+ messageType: error == null
+ ? TextInputComponentMessageType.helper
+ : TextInputComponentMessageType.error,
+ onChanged: (value) {
+ currentText = value;
+ canSubmit.value = value.trim().isNotEmpty;
+ validationError.value = null;
+ },
+ onSubmit: (value) => submit(sheetContext, value),
+ ),
),
actions: [
ValueListenableBuilder<bool>(
@@ -81,6 +94,7 @@ Future<dynamic> showTextInputSheet(
],
),
);
+ validationError.dispose();
controller?.dispose();
return result;
}
diff --git a/mobile/apps/locker/lib/ui/pages/file_upload_screen.dart b/mobile/apps/locker/lib/ui/pages/file_upload_screen.dart
index 16e27fdab9..ab6da8e2eb 100644
--- a/mobile/apps/locker/lib/ui/pages/file_upload_screen.dart
+++ b/mobile/apps/locker/lib/ui/pages/file_upload_screen.dart
@@ -1,3 +1,4 @@
+import 'dart:convert';
import 'dart:io';
import "package:ente_components/ente_components.dart";
@@ -7,16 +8,19 @@ import "package:hugeicons/hugeicons.dart";
import 'package:locker/services/collections/models/collection.dart';
import 'package:locker/services/configuration.dart';
import 'package:locker/ui/components/collection_selection_widget.dart';
+import 'package:locker/ui/components/text_input_sheet.dart';
import "package:locker/utils/file_icon_utils.dart";
import 'package:path/path.dart' as path;
class FileUploadScreenResult {
final List<File> files;
+ final Map<String, String> fileNames;
final String note;
final List<Collection> selectedCollections;
FileUploadScreenResult({
required this.files,
+ required this.fileNames,
required this.note,
required this.selectedCollections,
});
@@ -40,6 +44,7 @@ class FileUploadScreen extends StatefulWidget {
class _FileUploadScreenState extends State<FileUploadScreen> {
List<File> _files = [];
+ final Map<String, String> _fileNames = {};
List<Collection> _availableCollections = [];
final Set<int> _selectedCollectionIds = {};
@@ -78,6 +83,50 @@ class _FileUploadScreenState extends State<FileUploadScreen> {
});
}
+ Future<void> _renameFile(File file) async {
+ final currentName = _fileNames[file.path] ?? path.basename(file.path);
+ final extension = path.extension(file.path);
+ final baseName = currentName.substring(
+ 0,
+ currentName.length - extension.length,
+ );
+ final l10n = context.strings;
+
+ String? nameForUpload(String name) {
+ if (name == baseName) return currentName;
+ var cleaned = name.replaceAll(RegExp(r'[/\\\x00-\x1f]'), '').trim();
+ if (extension.isNotEmpty &&
+ cleaned.toLowerCase().endsWith(extension.toLowerCase())) {
+ cleaned = cleaned
+ .substring(0, cleaned.length - extension.length)
+ .trim();
+ }
+ if (cleaned.isEmpty || cleaned == '.' || cleaned == '..') return null;
+ return '$cleaned$extension';
+ }
+
+ await showTextInputSheet(
+ context,
+ title: l10n.renameFile,
+ initialValue: baseName,
+ hintText: l10n.enterFileName,
+ submitButtonLabel: l10n.save,
+ validator: (name) {
+ final fileName = nameForUpload(name);
+ if (fileName == null) return l10n.enterFileName;
+ // The title is also used as a filesystem name when opening the upload.
+ if (utf8.encode(fileName).length > 255) return l10n.fileNameTooLong;
+ return null;
+ },
+ onSubmit: (name) async {
+ if (!mounted) return;
+ final fileName = nameForUpload(name);
+ if (fileName == null) return;
+ setState(() => _fileNames[file.path] = fileName);
+ },
+ );
+ }
+
@override
Widget build(BuildContext context) {
final colors = context.componentColors;
@@ -211,6 +260,11 @@ class _FileUploadScreenState extends State<FileUploadScreen> {
.toList();
final result = FileUploadScreenResult(
files: List<File>.of(_files),
+ fileNames: {
+ for (final file in _files)
+ file.path:
+ _fileNames[file.path] ?? path.basename(file.path),
+ },
note: '',
selectedCollections: selectedCollections,
);
@@ -226,7 +280,7 @@ class _FileUploadScreenState extends State<FileUploadScreen> {
}
Widget _buildFileItem(File file, ColorTokens colors) {
- final fileName = path.basename(file.path);
+ final fileName = _fileNames[file.path] ?? path.basename(file.path);
return Container(
padding: const EdgeInsets.all(12),
@@ -247,6 +301,17 @@ class _FileUploadScreenState extends State<FileUploadScreen> {
),
),
const SizedBox(width: 12),
+ IconButtonComponent(
+ tooltip: context.strings.renameFile,
+ shouldSurfaceExecutionStates: false,
+ onTap: () => _renameFile(file),
+ icon: HugeIcon(
+ icon: HugeIcons.strokeRoundedEdit02,
+ color: colors.textBase,
+ size: 20,
+ ),
+ ),
+ const SizedBox(width: 8),
GestureDetector(
onTap: () {
setState(() {
diff --git a/mobile/apps/locker/lib/ui/pages/uploader_page.dart b/mobile/apps/locker/lib/ui/pages/uploader_page.dart
index 6c84d51e34..49dfb33d25 100644
--- a/mobile/apps/locker/lib/ui/pages/uploader_page.dart
+++ b/mobile/apps/locker/lib/ui/pages/uploader_page.dart
@@ -126,6 +126,7 @@ abstract class UploaderPageState<T extends UploaderPage> extends State<T> {
final fileUploadFuture = FileUploader.instance.upload(
file,
uploadResult.selectedCollections.first,
+ fileName: uploadResult.fileNames[file.path],
);
futures.add(
fileUploadFuture.then<void>(
diff --git a/mobile/apps/locker/lib/utils/file_util.dart b/mobile/apps/locker/lib/utils/file_util.dart
index b1cf45dd93..8793eae17f 100644
--- a/mobile/apps/locker/lib/utils/file_util.dart
+++ b/mobile/apps/locker/lib/utils/file_util.dart
@@ -318,6 +318,7 @@ class FileUtil {
name: baseName,
bytes: bytes,
fileExtension: fileExtension,
+ includeExtension: fileExtension.isNotEmpty,
mimeType: MimeType.other,
);
diff --git a/mobile/apps/locker/test/services/files/download/file_downloader_test.dart b/mobile/apps/locker/test/services/files/download/file_downloader_test.dart
index b19bbeae78..0c99a372c1 100644
--- a/mobile/apps/locker/test/services/files/download/file_downloader_test.dart
+++ b/mobile/apps/locker/test/services/files/download/file_downloader_test.dart
@@ -1,7 +1,9 @@
+import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
+import 'package:locker/services/configuration.dart';
import 'package:locker/services/files/download/file_downloader.dart'
as file_downloader;
import 'package:locker/services/files/offline/offline_file_storage.dart';
@@ -42,6 +44,40 @@ void main() {
}
});
+ for (final title in ['${'a' * 251}.pdf', '${'\u6587' * 83}ab.pdf']) {
+ test(
+ 'stages a 255-byte filename with ${title.length} characters',
+ () async {
+ expect(utf8.encode(title).length, 255);
+ final file = lockerFile(uploadedFileID: 904, title: title);
+ final temporaryPath = file_downloader.getTemporaryDecryptedFilePath(
+ file,
+ );
+
+ final temporaryFile = await writeFile(
+ temporaryPath,
+ 'downloaded bytes',
+ );
+
+ expect(await temporaryFile.readAsString(), 'downloaded bytes');
+ expect(file.displayName, title);
+ expect(
+ p.dirname(temporaryPath),
+ p.normalize(Configuration.instance.getTempDirectory()),
+ );
+ expect(temporaryPath, isNot(getCachedDecryptedFilePath(file)));
+ expect(
+ temporaryPath,
+ isNot(
+ file_downloader.getTemporaryDecryptedFilePath(
+ lockerFile(uploadedFileID: 905, title: title),
+ ),
+ ),
+ );
+ },
+ );
+ }
+
test(
'returns ID-keyed cached decrypted copy and ignores localPath',
() async {
diff --git a/mobile/apps/locker/test/utils/file_util_test.dart b/mobile/apps/locker/test/utils/file_util_test.dart
index 602047f94c..5c1ec4eb5b 100644
--- a/mobile/apps/locker/test/utils/file_util_test.dart
+++ b/mobile/apps/locker/test/utils/file_util_test.dart
@@ -199,6 +199,26 @@ void main() {
},
);
+ test(
+ 'opens a maximum-length extensionless name from the decrypted cache',
+ () async {
+ final displayName = 'a' * 255;
+ final file = lockerFile(uploadedFileID: 659, title: displayName);
+ final source = File(getCachedDecryptedFilePath(file));
+ await source.writeAsString('extensionless bytes');
+
+ final handoffFile = await FileUtil.prepareOpenFileForTest(
+ source,
+ displayName: displayName,
+ lockerFile: file,
+ );
+
+ expect(p.basename(source.path), '659.decrypted');
+ expect(p.basename(handoffFile.path), displayName);
+ expect(await handoffFile.readAsString(), 'extensionless bytes');
+ },
+ );
+
test('sanitizes display names before creating the handoff copy', () async {
final source = File(p.join(root.path, 'source.bin'));
await source.writeAsString('safe bytes');
diff --git a/mobile/packages/strings/lib/l10n/arb/strings_en.arb b/mobile/packages/strings/lib/l10n/arb/strings_en.arb
index a49f51231d..9cbfb6e6b2 100644
--- a/mobile/packages/strings/lib/l10n/arb/strings_en.arb
+++ b/mobile/packages/strings/lib/l10n/arb/strings_en.arb
@@ -1672,6 +1672,10 @@
"fileDeletedSuccessfully": "Item deleted successfully",
"fileInfoAddDescHint": "Add a description...",
"fileMarkedAsImportant": "Item marked as important",
+ "fileNameTooLong": "File name is too long. Try a shorter name.",
+ "@fileNameTooLong": {
+ "description": "Validation error when a renamed file exceeds the filesystem filename length limit"
+ },
"fileNotUploadedYet": "File not uploaded yet",
"fileRemovedFromImportant": "Item removed from important",
"files": "Files",