Skip to content

armgit / ente

Public Imported from GitHub
0

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

fixes [dart-only]

AmanRajSinghMourya284c4b9d841e
diff --git a/mobile/apps/photos/lib/db/memory_shares_db.dart b/mobile/apps/photos/lib/db/memory_shares_db.dart
index 4a0040404f..fc61cda403 100644
--- a/mobile/apps/photos/lib/db/memory_shares_db.dart
+++ b/mobile/apps/photos/lib/db/memory_shares_db.dart
@@ -22,6 +22,8 @@ class MemorySharesDB {
static const _columnCreatedAt = 'created_at';
static const _columnUpdatedAt = 'updated_at';
static const _columnUrl = 'url';
+ static const _columnPreviewUploadedFileID = 'preview_uploaded_file_id';
+ static const _columnFileCount = 'file_count';
MemorySharesDB._();
static final MemorySharesDB instance = MemorySharesDB._();
@@ -57,7 +59,9 @@ class MemorySharesDB {
$_columnIsDeleted INTEGER NOT NULL DEFAULT 0,
$_columnCreatedAt INTEGER NOT NULL,
$_columnUpdatedAt INTEGER,
- $_columnUrl TEXT NOT NULL
+ $_columnUrl TEXT NOT NULL,
+ $_columnPreviewUploadedFileID INTEGER,
+ $_columnFileCount INTEGER
)
''');
}
@@ -119,6 +123,8 @@ class MemorySharesDB {
_columnCreatedAt: share.createdAt,
_columnUpdatedAt: share.updatedAt,
_columnUrl: share.url,
+ _columnPreviewUploadedFileID: share.previewUploadedFileID,
+ _columnFileCount: share.fileCount,
};
}
@@ -135,6 +141,8 @@ class MemorySharesDB {
createdAt: row[_columnCreatedAt] as int,
updatedAt: row[_columnUpdatedAt] as int?,
url: row[_columnUrl] as String,
+ previewUploadedFileID: row[_columnPreviewUploadedFileID] as int?,
+ fileCount: row[_columnFileCount] as int?,
);
}
}
diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dart
index 30549ae1a4..a76d206d4b 100644
--- a/mobile/apps/photos/lib/main.dart
+++ b/mobile/apps/photos/lib/main.dart
@@ -37,6 +37,7 @@ import "package:photos/services/machine_learning/face_ml/person/person_service.d
import 'package:photos/services/machine_learning/ml_service.dart';
import 'package:photos/services/machine_learning/semantic_search/semantic_search_service.dart';
import 'package:photos/services/memory_lane/memory_lane_service.dart';
+import 'package:photos/services/memory_share_service.dart';
import "package:photos/services/notification_service.dart";
import 'package:photos/services/push_service.dart';
import 'package:photos/services/search_service.dart';
@@ -183,6 +184,7 @@ Future<void> _runMinimally(String taskId, TimeLogger tlog) async {
NetworkClient.instance.getDio(),
packageInfo,
);
+ await MemoryShareService.instance.init();
_logger.info("(for debugging) CollectionsService init $tlog");
await CollectionsService.instance.init(prefs);
@@ -278,6 +280,7 @@ Future<void> _init(bool isBackground, {String via = ''}) async {
NetworkClient.instance.getDio(),
packageInfo,
);
+ await MemoryShareService.instance.init();
_logger.info("UserService init $tlog");
await UserService.instance.init();
diff --git a/mobile/apps/photos/lib/models/api/memory_share/memory_share.dart b/mobile/apps/photos/lib/models/api/memory_share/memory_share.dart
index f43c44d611..4d73d4c21e 100644
--- a/mobile/apps/photos/lib/models/api/memory_share/memory_share.dart
+++ b/mobile/apps/photos/lib/models/api/memory_share/memory_share.dart
@@ -24,6 +24,8 @@ class MemoryShare {
final int createdAt;
final int? updatedAt;
final String url;
+ final int? previewUploadedFileID;
+ final int? fileCount;
MemoryShare({
required this.id,
@@ -37,6 +39,8 @@ class MemoryShare {
required this.createdAt,
this.updatedAt,
required this.url,
+ this.previewUploadedFileID,
+ this.fileCount,
});
factory MemoryShare.fromJson(Map<String, dynamic> json) {
@@ -52,6 +56,41 @@ class MemoryShare {
createdAt: json['createdAt'] as int,
updatedAt: json['updatedAt'] as int?,
url: json['url'] as String,
+ previewUploadedFileID: json['previewUploadedFileID'] as int?,
+ fileCount: json['fileCount'] as int?,
+ );
+ }
+
+ MemoryShare copyWith({
+ int? id,
+ MemoryShareType? type,
+ String? metadataCipher,
+ String? metadataNonce,
+ String? encryptedKey,
+ String? keyDecryptionNonce,
+ String? accessToken,
+ bool? isDeleted,
+ int? createdAt,
+ int? updatedAt,
+ String? url,
+ int? previewUploadedFileID,
+ int? fileCount,
+ }) {
+ return MemoryShare(
+ id: id ?? this.id,
+ type: type ?? this.type,
+ metadataCipher: metadataCipher ?? this.metadataCipher,
+ metadataNonce: metadataNonce ?? this.metadataNonce,
+ encryptedKey: encryptedKey ?? this.encryptedKey,
+ keyDecryptionNonce: keyDecryptionNonce ?? this.keyDecryptionNonce,
+ accessToken: accessToken ?? this.accessToken,
+ isDeleted: isDeleted ?? this.isDeleted,
+ createdAt: createdAt ?? this.createdAt,
+ updatedAt: updatedAt ?? this.updatedAt,
+ url: url ?? this.url,
+ previewUploadedFileID:
+ previewUploadedFileID ?? this.previewUploadedFileID,
+ fileCount: fileCount ?? this.fileCount,
);
}
@@ -68,6 +107,8 @@ class MemoryShare {
'createdAt': createdAt,
'updatedAt': updatedAt,
'url': url,
+ 'previewUploadedFileID': previewUploadedFileID,
+ 'fileCount': fileCount,
};
}
}
diff --git a/mobile/apps/photos/lib/services/memory_share_service.dart b/mobile/apps/photos/lib/services/memory_share_service.dart
index 11b68c346e..62ad007d22 100644
--- a/mobile/apps/photos/lib/services/memory_share_service.dart
+++ b/mobile/apps/photos/lib/services/memory_share_service.dart
@@ -1,23 +1,40 @@
import 'dart:convert';
+import 'dart:math';
import 'dart:typed_data';
+import 'package:crypto/crypto.dart';
+import 'package:dio/dio.dart';
import 'package:ente_crypto/ente_crypto.dart';
-import 'package:fast_base58/fast_base58.dart';
+import "package:flutter/foundation.dart" show kDebugMode;
+import "package:logging/logging.dart";
import 'package:photos/core/network/network.dart';
+import "package:photos/db/files_db.dart";
import 'package:photos/db/memory_shares_db.dart';
-import 'package:photos/models/api/entity/type.dart';
+import "package:photos/gateways/entity/models/type.dart";
import 'package:photos/models/api/memory_share/memory_share.dart';
import 'package:photos/models/file/file.dart';
import 'package:photos/models/memories/memory.dart';
+import "package:photos/models/metadata/file_magic.dart";
import 'package:photos/service_locator.dart' show entityService;
import 'package:photos/utils/file_key.dart';
class MemoryShareService {
- static final MemoryShareService instance = MemoryShareService._();
MemoryShareService._();
- final _enteDio = NetworkClient.instance.enteDio;
- final _db = MemorySharesDB.instance;
+ static final MemoryShareService instance = MemoryShareService._();
+
+ final Logger _logger = Logger("MemoryShareService");
+
+ static const int _shortFragmentSecretLength = 12;
+ static final RegExp _base62SecretPattern = RegExp(r'^[0-9A-Za-z]{12}$');
+
+ late final Dio _enteDio;
+ late final MemorySharesDB _db;
+
+ Future<void> init() async {
+ _enteDio = NetworkClient.instance.enteDio;
+ _db = MemorySharesDB.instance;
+ }
/// Creates a memory share and returns the shareable URL with key in fragment.
Future<String> createMemoryShare({
@@ -25,83 +42,479 @@ class MemoryShareService {
required String title,
String? memoryId,
}) async {
- final uploadedFiles = files.where((f) => f.uploadedFileID != null).toList();
-
- if (uploadedFiles.isEmpty) {
- throw Exception("No uploaded files to share");
- }
-
- final memoryEntityKey =
- await entityService.getOrCreateEntityKey(EntityType.memory);
- final shareKey = CryptoUtil.generateKey();
- final encryptedShareKey = CryptoUtil.encryptSync(
- shareKey,
- memoryEntityKey,
- );
-
- final metadataMap = <String, dynamic>{'name': title};
- if (memoryId != null) {
- metadataMap['memoryId'] = memoryId;
- }
- final metadata = jsonEncode(metadataMap);
- final metadataBytes = utf8.encode(metadata);
- final encryptedMetadata = CryptoUtil.encryptSync(
- Uint8List.fromList(metadataBytes),
- shareKey,
- );
-
- final fileItems = <Map<String, dynamic>>[];
- for (final file in uploadedFiles) {
- final fileKey = getFileKey(file);
- final reEncryptedKey = CryptoUtil.encryptSync(fileKey, shareKey);
- fileItems.add({
- 'fileID': file.uploadedFileID,
- 'encryptedKey': CryptoUtil.bin2base64(reEncryptedKey.encryptedData!),
- 'keyDecryptionNonce': CryptoUtil.bin2base64(reEncryptedKey.nonce!),
- });
- }
-
- final requestData = {
- 'metadataCipher': CryptoUtil.bin2base64(encryptedMetadata.encryptedData!),
- 'metadataNonce': CryptoUtil.bin2base64(encryptedMetadata.nonce!),
- 'encryptedKey': CryptoUtil.bin2base64(encryptedShareKey.encryptedData!),
- 'keyDecryptionNonce': CryptoUtil.bin2base64(encryptedShareKey.nonce!),
- 'files': fileItems,
- };
+ try {
+ final uploadedFiles =
+ files.where((f) => f.uploadedFileID != null).toList();
+
+ if (uploadedFiles.isEmpty) {
+ throw Exception("No uploaded files to share");
+ }
+
+ final secretPayload = await _prepareShareSecret();
+ final shareKey = secretPayload.shareKey;
- final response = await _enteDio.post('/memory-share', data: requestData);
- final memoryShare = MemoryShare.fromJson(response.data['memoryShare']);
+ final metadataMap = <String, dynamic>{'name': title};
+ if (memoryId != null) {
+ metadataMap['memoryId'] = memoryId;
+ }
+ final metadata = jsonEncode(metadataMap);
+ final metadataBytes = utf8.encode(metadata);
+ final encryptedMetadata = CryptoUtil.encryptSync(
+ Uint8List.fromList(metadataBytes),
+ shareKey,
+ );
- await _db.upsert(memoryShare);
+ final fileItems = <Map<String, dynamic>>[];
+ for (final file in uploadedFiles) {
+ final fileKey = getFileKey(file);
+ final reEncryptedKey = CryptoUtil.encryptSync(fileKey, shareKey);
+ fileItems.add({
+ 'fileID': file.uploadedFileID,
+ 'encryptedKey': CryptoUtil.bin2base64(reEncryptedKey.encryptedData!),
+ 'keyDecryptionNonce': CryptoUtil.bin2base64(reEncryptedKey.nonce!),
+ });
+ }
- // Key in URL fragment is never sent to server (E2E encryption)
- final keyBase58 = Base58Encode(shareKey);
- final shareUrl = "${memoryShare.url}#$keyBase58";
+ final requestData = {
+ 'metadataCipher':
+ CryptoUtil.bin2base64(encryptedMetadata.encryptedData!),
+ 'metadataNonce': CryptoUtil.bin2base64(encryptedMetadata.nonce!),
+ ...secretPayload.metadata(),
+ 'files': fileItems,
+ };
- return shareUrl;
+ final response = await _enteDio.post('/memory-share', data: requestData);
+ final memoryShare = MemoryShare.fromJson(response.data['memoryShare']);
+
+ final shareUrl = "${memoryShare.url}#${secretPayload.secret}";
+ await _db.upsert(
+ MemoryShare(
+ id: memoryShare.id,
+ type: memoryShare.type,
+ metadataCipher: memoryShare.metadataCipher,
+ metadataNonce: memoryShare.metadataNonce,
+ encryptedKey: memoryShare.encryptedKey,
+ keyDecryptionNonce: memoryShare.keyDecryptionNonce,
+ accessToken: memoryShare.accessToken,
+ isDeleted: memoryShare.isDeleted,
+ createdAt: memoryShare.createdAt,
+ updatedAt: memoryShare.updatedAt,
+ url: shareUrl,
+ previewUploadedFileID: uploadedFiles.first.uploadedFileID,
+ fileCount: uploadedFiles.length,
+ ),
+ );
+
+ return shareUrl;
+ } catch (e, s) {
+ _logger.severe("Failed to create memory share", e, s);
+ rethrow;
+ }
}
Future<List<MemoryShare>> listMemoryShares() async {
- final response = await _enteDio.get('/memory-share');
- final List<dynamic> shares = response.data['memoryShares'] ?? [];
- final result = shares
- .map((s) => MemoryShare.fromJson(s as Map<String, dynamic>))
- .toList();
+ try {
+ final response = await _enteDio.get('/memory-share');
+ final List<dynamic> shares = response.data['memoryShares'] ?? [];
+ Uint8List? memoryEntityKey;
+ try {
+ memoryEntityKey = await entityService.getOrCreateEntityKey(
+ EntityType.memory,
+ );
+ } catch (e, s) {
+ _logger.severe(
+ "Failed to get memory entity key while listing memory shares",
+ e,
+ s,
+ );
+ memoryEntityKey = null;
+ }
+ final result = shares.map((s) {
+ var share = MemoryShare.fromJson(s as Map<String, dynamic>);
+ final entityKey = memoryEntityKey;
+ if (entityKey != null) {
+ final fragment = Uri.parse(share.url).fragment;
+ if (fragment.isEmpty) {
+ final resolvedFragment = _resolveFragmentSecret(share, entityKey);
+ if (resolvedFragment != null && resolvedFragment.isNotEmpty) {
+ share = share.copyWith(url: "${share.url}#$resolvedFragment");
+ }
+ }
+ }
+ return share;
+ }).toList();
- for (final share in result) {
- await _db.upsert(share);
- }
+ for (final share in result) {
+ final localShare = await _db.getById(share.id);
+ await _db.upsert(
+ share.copyWith(
+ previewUploadedFileID: localShare?.previewUploadedFileID,
+ fileCount: localShare?.fileCount,
+ ),
+ );
+ }
- return result;
+ return result;
+ } catch (e, s) {
+ _logger.severe("Failed to list memory shares", e, s);
+ rethrow;
+ }
}
Future<List<MemoryShare>> getLocalMemoryShares() async {
return _db.getAll();
}
+ Future<List<EnteFile>> getPublicMemoryFiles(String shareUrl) async {
+ try {
+ final uri = Uri.parse(shareUrl);
+ final accessToken = _extractAccessToken(uri);
+ final shareKey = _resolveShareKeyFromUrlFragment(uri.fragment);
+ final response = await _enteDio.get(
+ '/public-memory/files',
+ options: Options(
+ headers: {'X-Auth-Access-Token': accessToken},
+ ),
+ );
+ final rawFiles = response.data['files'] as List<dynamic>? ?? const [];
+ final files = <EnteFile>[];
+ for (final rawFile in rawFiles) {
+ final localFile = await _resolveLocalFileFromShareItem(rawFile);
+ if (localFile != null) {
+ files.add(localFile);
+ continue;
+ }
+ final file = await _parsePublicMemoryFile(rawFile, shareKey);
+ if (file != null) {
+ files.add(file);
+ }
+ }
+ if (files.isEmpty && kDebugMode) {
+ _logger.info(
+ "Public memory files response was empty, using debug dummy files",
+ );
+ return _buildDebugDummyMemoryFiles();
+ }
+ return files;
+ } catch (e, s) {
+ _logger.severe("Failed to fetch public memory files", e, s);
+ if (kDebugMode) {
+ _logger.info("Using debug dummy files after fetch failure");
+ return _buildDebugDummyMemoryFiles();
+ }
+ rethrow;
+ }
+ }
+
+ Future<EnteFile?> _resolveLocalFileFromShareItem(dynamic rawFile) async {
+ final item = _toMap(rawFile);
+ final remoteFile = _toMap(item?['file']);
+ if (remoteFile == null) {
+ return null;
+ }
+ final fileID = _toInt(remoteFile['id']);
+ if (fileID == null) {
+ return null;
+ }
+ return FilesDB.instance.getAnyUploadedFile(fileID);
+ }
+
+ String? getMemoryShareTitle(MemoryShare share) {
+ try {
+ final metadataCipher = share.metadataCipher;
+ final metadataNonce = share.metadataNonce;
+ if (metadataCipher == null || metadataNonce == null) {
+ return null;
+ }
+ final fragment = Uri.parse(share.url).fragment;
+ if (fragment.isEmpty) {
+ return null;
+ }
+ final shareKey = _resolveShareKeyFromUrlFragment(fragment);
+ final decryptedMetadata = CryptoUtil.decryptSync(
+ CryptoUtil.base642bin(metadataCipher),
+ shareKey,
+ CryptoUtil.base642bin(metadataNonce),
+ );
+ final parsed = jsonDecode(utf8.decode(decryptedMetadata));
+ if (parsed is! Map<String, dynamic>) {
+ return null;
+ }
+ final name = parsed["name"];
+ if (name is String && name.trim().isNotEmpty) {
+ return name;
+ }
+ return null;
+ } catch (e, s) {
+ _logger.severe(
+ "Failed to read memory share title for share ${share.id}",
+ e,
+ s,
+ );
+ return null;
+ }
+ }
+
Future<void> deleteMemoryShare(int id) async {
- await _enteDio.delete('/memory-share/$id');
- await _db.delete(id);
+ try {
+ await _enteDio.delete('/memory-share/$id');
+ await _db.delete(id);
+ } catch (e, s) {
+ _logger.severe("Failed to delete memory share $id", e, s);
+ rethrow;
+ }
+ }
+
+ Future<EnteFile?> _parsePublicMemoryFile(
+ dynamic rawFile,
+ Uint8List shareKey,
+ ) async {
+ final item = _toMap(rawFile);
+ final remoteFile = _toMap(item?['file']);
+ if (item == null || remoteFile == null) {
+ return null;
+ }
+ try {
+ final file = EnteFile();
+ file.uploadedFileID = _toInt(remoteFile['id']);
+ file.collectionID = _toInt(remoteFile['collectionID']);
+ file.ownerID = _toInt(remoteFile['ownerID']);
+ // /public-memory/files returns per-share re-encrypted key material at the
+ // top level. Fall back to nested fields for compatibility.
+ file.encryptedKey = item['encryptedKey'] as String? ??
+ remoteFile['encryptedKey'] as String?;
+ file.keyDecryptionNonce = item['keyDecryptionNonce'] as String? ??
+ remoteFile['keyDecryptionNonce'] as String?;
+ final collectionAddedAt = _toInt(remoteFile['collectionAddedAt']);
+ if (collectionAddedAt != null) {
+ file.addedTime = collectionAddedAt;
+ }
+
+ final fileData = _toMap(remoteFile['file']);
+ final thumbnailData = _toMap(remoteFile['thumbnail']);
+ final metadataData = _toMap(remoteFile['metadata']);
+ if (fileData == null || thumbnailData == null || metadataData == null) {
+ return null;
+ }
+
+ file.fileDecryptionHeader = fileData['decryptionHeader'] as String?;
+ file.thumbnailDecryptionHeader =
+ thumbnailData['decryptionHeader'] as String?;
+ file.metadataDecryptionHeader =
+ metadataData['decryptionHeader'] as String?;
+
+ final info = _toMap(remoteFile['info']);
+ if (info != null) {
+ file.fileSize = _toInt(info['fileSize']);
+ }
+
+ if (file.encryptedKey == null ||
+ file.keyDecryptionNonce == null ||
+ file.metadataDecryptionHeader == null) {
+ return null;
+ }
+
+ final encryptedMetadata = metadataData['encryptedData'] as String?;
+ if (encryptedMetadata == null) {
+ return null;
+ }
+
+ final fileKey = CryptoUtil.decryptSync(
+ CryptoUtil.base642bin(file.encryptedKey!),
+ shareKey,
+ CryptoUtil.base642bin(file.keyDecryptionNonce!),
+ );
+ final encodedMetadata = await CryptoUtil.decryptChaCha(
+ CryptoUtil.base642bin(encryptedMetadata),
+ fileKey,
+ CryptoUtil.base642bin(file.metadataDecryptionHeader!),
+ );
+ final decodedMetadata = jsonDecode(utf8.decode(encodedMetadata));
+ if (decodedMetadata is! Map) {
+ return null;
+ }
+ file.applyMetadata(Map<String, dynamic>.from(decodedMetadata));
+
+ final pubMagicMetadata = _toMap(remoteFile['pubMagicMetadata']);
+ if (pubMagicMetadata != null) {
+ final data = pubMagicMetadata['data'] as String?;
+ final header = pubMagicMetadata['header'] as String?;
+ if (data != null && header != null) {
+ final utfEncodedMmd = await CryptoUtil.decryptChaCha(
+ CryptoUtil.base642bin(data),
+ fileKey,
+ CryptoUtil.base642bin(header),
+ );
+ file.pubMmdEncodedJson = utf8.decode(utfEncodedMmd);
+ file.pubMmdVersion = _toInt(pubMagicMetadata['version']) ?? 0;
+ file.pubMagicMetadata =
+ PubMagicMetadata.fromEncodedJson(file.pubMmdEncodedJson!);
+ }
+ }
+
+ file.localID = null;
+ if ((file.collectionID ?? 0) <= 0) {
+ return null;
+ }
+ return file;
+ } catch (e, s) {
+ _logger.warning("Failed to parse public memory file", e, s);
+ return null;
+ }
+ }
+
+ Future<_MemoryShareSecretPayload> _prepareShareSecret() async {
+ try {
+ final memoryEntityKey =
+ await entityService.getOrCreateEntityKey(EntityType.memory);
+ final secret = _generateBase62Secret(_shortFragmentSecretLength);
+ final shareKey = _deriveShareKeyFromSecret(secret);
+ final encryptedSecret = CryptoUtil.encryptSync(
+ Uint8List.fromList(utf8.encode(secret)),
+ memoryEntityKey,
+ );
+ return _MemoryShareSecretPayload(
+ secret: secret,
+ shareKey: shareKey,
+ encryptedShareSecret:
+ CryptoUtil.bin2base64(encryptedSecret.encryptedData!),
+ encryptedShareSecretNonce:
+ CryptoUtil.bin2base64(encryptedSecret.nonce!),
+ );
+ } catch (e, s) {
+ _logger.severe("Failed to prepare memory share secret", e, s);
+ rethrow;
+ }
+ }
+
+ String? _resolveFragmentSecret(
+ MemoryShare share,
+ Uint8List memoryEntityKey,
+ ) {
+ try {
+ final decrypted = CryptoUtil.decryptSync(
+ CryptoUtil.base642bin(share.encryptedKey),
+ memoryEntityKey,
+ CryptoUtil.base642bin(share.keyDecryptionNonce),
+ );
+ return _tryDecodeShortFragmentSecret(decrypted);
+ } catch (e, s) {
+ _logger.severe(
+ "Failed to resolve memory share fragment secret for share ${share.id}",
+ e,
+ s,
+ );
+ return null;
+ }
+ }
+
+ String? _tryDecodeShortFragmentSecret(Uint8List value) {
+ if (value.length != _shortFragmentSecretLength) {
+ return null;
+ }
+ try {
+ final secret = utf8.decode(value);
+ if (_base62SecretPattern.hasMatch(secret)) {
+ return secret;
+ }
+ } catch (e, s) {
+ _logger.severe("Failed to decode memory share fragment secret", e, s);
+ return null;
+ }
+ return null;
+ }
+
+ Uint8List _resolveShareKeyFromUrlFragment(String fragment) {
+ if (!_base62SecretPattern.hasMatch(fragment)) {
+ throw const FormatException("Invalid memory share fragment");
+ }
+ return _deriveShareKeyFromSecret(fragment);
+ }
+
+ Uint8List _deriveShareKeyFromSecret(String secret) {
+ final digest = sha256.convert(utf8.encode(secret));
+ return Uint8List.fromList(digest.bytes);
+ }
+
+ String _generateBase62Secret(int length) {
+ const charset =
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+ final random = Random.secure();
+ final buffer = StringBuffer();
+ for (var i = 0; i < length; i++) {
+ buffer.write(charset[random.nextInt(charset.length)]);
+ }
+ return buffer.toString();
+ }
+
+ String _extractAccessToken(Uri uri) {
+ final tokenFromQuery = uri.queryParameters["t"];
+ if (tokenFromQuery != null && tokenFromQuery.isNotEmpty) {
+ return tokenFromQuery;
+ }
+ for (final segment in uri.pathSegments) {
+ if (segment.isNotEmpty && segment != "memory") {
+ return segment;
+ }
+ }
+ throw const FormatException("Invalid memory share URL");
+ }
+
+ Map<String, dynamic>? _toMap(dynamic value) {
+ if (value is Map<String, dynamic>) {
+ return value;
+ }
+ if (value is Map) {
+ return Map<String, dynamic>.from(value);
+ }
+ return null;
+ }
+
+ int? _toInt(dynamic value) {
+ if (value is int) {
+ return value;
+ }
+ if (value is num) {
+ return value.toInt();
+ }
+ if (value is String) {
+ return int.tryParse(value);
+ }
+ return null;
+ }
+
+ Future<List<EnteFile>> _buildDebugDummyMemoryFiles({
+ int limit = 12,
+ }) async {
+ try {
+ final localFiles = await FilesDB.instance.getAllFilesFromDB(
+ const {},
+ );
+ if (localFiles.isEmpty) {
+ return [];
+ }
+ final usableFiles = localFiles
+ .where(
+ (file) =>
+ file.generatedID != null &&
+ file.creationTime != null &&
+ file.creationTime! > 0,
+ )
+ .take(limit)
+ .toList();
+ if (usableFiles.isEmpty) {
+ return [];
+ }
+ return List<EnteFile>.generate(
+ usableFiles.length,
+ (index) => usableFiles[index].copyWith(
+ title: "Dummy Memory File ${index + 1}",
+ ),
+ );
+ } catch (e, s) {
+ _logger.warning("Failed to build debug dummy memory files", e, s);
+ return [];
+ }
}
Future<String> shareMemories({
@@ -113,3 +526,24 @@ class MemoryShareService {
return createMemoryShare(files: files, title: title, memoryId: memoryId);
}
}
+
+class _MemoryShareSecretPayload {
+ final String secret;
+ final Uint8List shareKey;
+ final String encryptedShareSecret;
+ final String encryptedShareSecretNonce;
+
+ const _MemoryShareSecretPayload({
+ required this.secret,
+ required this.shareKey,
+ required this.encryptedShareSecret,
+ required this.encryptedShareSecretNonce,
+ });
+
+ Map<String, dynamic> metadata() {
+ return {
+ 'encryptedKey': encryptedShareSecret,
+ 'keyDecryptionNonce': encryptedShareSecretNonce,
+ };
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/tabs/shared/memory_link_item.dart b/mobile/apps/photos/lib/ui/tabs/shared/memory_link_item.dart
new file mode 100644
index 0000000000..4e967f1b8d
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/tabs/shared/memory_link_item.dart
@@ -0,0 +1,115 @@
+import "package:flutter/material.dart";
+import "package:photos/db/files_db.dart";
+import 'package:photos/models/file/file.dart';
+import "package:photos/theme/ente_theme.dart";
+import "package:photos/ui/components/buttons/icon_button_widget.dart";
+import "package:photos/ui/viewer/file/no_thumbnail_widget.dart";
+import "package:photos/ui/viewer/file/thumbnail_widget.dart";
+
+class MemoryLinkAlbumItem extends StatelessWidget {
+ static const heroTagPrefix = "memory_link";
+ final String title;
+ final int? fileCount;
+ final int? previewUploadedFileID;
+
+ const MemoryLinkAlbumItem({
+ super.key,
+ required this.title,
+ this.fileCount,
+ this.previewUploadedFileID,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+
+ return Container(
+ decoration: BoxDecoration(
+ border: Border.all(color: colorScheme.strokeFainter),
+ borderRadius: const BorderRadius.all(
+ Radius.circular(6),
+ ),
+ ),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Flexible(
+ flex: 6,
+ child: Row(
+ children: [
+ SizedBox(
+ width: 60,
+ height: 60,
+ child: FutureBuilder<EnteFile?>(
+ future: () {
+ final uploadedID = previewUploadedFileID;
+ if (uploadedID == null) {
+ return Future.value(null);
+ }
+ return FilesDB.instance.getAnyUploadedFile(uploadedID);
+ }(),
+ builder: (context, snapshot) {
+ if (snapshot.hasData && snapshot.data != null) {
+ final String heroTag =
+ heroTagPrefix + snapshot.data!.tag;
+ return Hero(
+ tag: heroTag,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(4),
+ child: ThumbnailWidget(
+ snapshot.data!,
+ key: ValueKey(heroTag),
+ ),
+ ),
+ );
+ }
+ return const NoThumbnailWidget();
+ },
+ ),
+ ),
+ const SizedBox(width: 12),
+ Flexible(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 4),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ title,
+ overflow: TextOverflow.ellipsis,
+ ),
+ const SizedBox(height: 2),
+ Row(
+ children: [
+ Text(
+ (fileCount ?? 0).toString() + " \u2022 ",
+ style: textTheme.smallMuted,
+ ),
+ Icon(
+ Icons.link_outlined,
+ color: colorScheme.strokeMuted,
+ size: 22,
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ Flexible(
+ flex: 1,
+ child: IconButtonWidget(
+ icon: Icons.chevron_right_outlined,
+ iconButtonType: IconButtonType.secondary,
+ iconColor: colorScheme.blurStrokePressed,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/tabs/shared_collections_tab.dart b/mobile/apps/photos/lib/ui/tabs/shared_collections_tab.dart
index 695da827bf..a4faf6be17 100644
--- a/mobile/apps/photos/lib/ui/tabs/shared_collections_tab.dart
+++ b/mobile/apps/photos/lib/ui/tabs/shared_collections_tab.dart
@@ -13,10 +13,14 @@ import "package:photos/events/local_photos_updated_event.dart";
import "package:photos/events/tab_changed_event.dart";
import "package:photos/events/user_logged_out_event.dart";
import "package:photos/generated/l10n.dart";
+import "package:photos/models/api/collection/user.dart";
+import "package:photos/models/api/memory_share/memory_share.dart";
+import "package:photos/models/collection/collection.dart";
import "package:photos/models/collection/collection_items.dart";
import "package:photos/models/search/generic_search_result.dart";
import "package:photos/service_locator.dart";
import "package:photos/services/collections_service.dart";
+import "package:photos/services/memory_share_service.dart";
import "package:photos/services/search_service.dart";
import "package:photos/theme/ente_theme.dart";
import "package:photos/ui/collections/album/row_item.dart";
@@ -28,10 +32,13 @@ import "package:photos/ui/social/widgets/feed_preview_widget.dart";
import "package:photos/ui/tabs/section_title.dart";
import "package:photos/ui/tabs/shared/all_quick_links_page.dart";
import "package:photos/ui/tabs/shared/empty_state.dart";
+import "package:photos/ui/tabs/shared/memory_link_item.dart";
import "package:photos/ui/tabs/shared/quick_link_album_item.dart";
import "package:photos/ui/viewer/gallery/collect_photos_card_widget.dart";
import "package:photos/ui/viewer/gallery/collection_page.dart";
+import "package:photos/ui/viewer/gallery/shared_public_collection_page.dart";
import "package:photos/ui/viewer/search_tab/contacts_section.dart";
+import "package:photos/utils/dialog_util.dart";
class SharedCollectionsTab extends StatefulWidget {
const SharedCollectionsTab({super.key});
@@ -182,7 +189,9 @@ class _SharedCollectionsTabState extends State<SharedCollectionsTab>
return FutureBuilder<SharedCollections>(
future: offlineUiMode
? Future.value(SharedCollections.empty())
- : Future.value(CollectionsService.instance.getSharedCollections()),
+ : Future.value(
+ CollectionsService.instance.getSharedCollections(),
+ ),
builder: (context, snapshot) {
if (snapshot.hasData) {
if (offlineUiMode) {
@@ -190,12 +199,18 @@ class _SharedCollectionsTabState extends State<SharedCollectionsTab>
child: SharedEmptyOfflineStateWidget(),
);
}
- if ((snapshot.data?.incoming.length ?? 0) == 0 &&
- (snapshot.data?.quickLinks.length ?? 0) == 0 &&
- (snapshot.data?.outgoing.length ?? 0) == 0) {
- return const Center(child: SharedEmptyStateWidget());
+ final collections = snapshot.data!;
+ final hasSharedCollections = collections.incoming.isNotEmpty ||
+ collections.quickLinks.isNotEmpty ||
+ collections.outgoing.isNotEmpty;
+ if (!hasSharedCollections) {
+ return SafeArea(
+ child: _buildMemoryLinksOrEmptyState(),
+ );
}
- return SafeArea(child: _getSharedCollectionsGallery(snapshot.data!));
+ return SafeArea(
+ child: _getSharedCollectionsGallery(collections),
+ );
} else if (snapshot.hasError) {
_logger.severe(
"critical: failed to load share gallery",
@@ -212,6 +227,174 @@ class _SharedCollectionsTabState extends State<SharedCollectionsTab>
);
}
+ Widget _buildMemoryLinksOrEmptyState() {
+ return FutureBuilder<List<MemoryShare>>(
+ future: _loadMemoryQuickLinks(),
+ builder: (context, snapshot) {
+ if (snapshot.connectionState != ConnectionState.done &&
+ !snapshot.hasData) {
+ return const EnteLoadingWidget();
+ }
+ final memoryLinks = snapshot.data ?? const [];
+ if (memoryLinks.isEmpty) {
+ return const Center(
+ child: SharedEmptyStateWidget(),
+ );
+ }
+ return SingleChildScrollView(
+ physics: const BouncingScrollPhysics(),
+ child: Container(
+ margin: const EdgeInsets.only(bottom: 50),
+ child: Column(
+ children: [
+ SectionOptions(
+ SectionTitle(
+ title: AppLocalizations.of(context).memories,
+ ),
+ ),
+ const SizedBox(height: 2),
+ ListView.separated(
+ shrinkWrap: true,
+ padding: const EdgeInsets.only(
+ bottom: 12,
+ left: 12,
+ right: 12,
+ ),
+ physics: const NeverScrollableScrollPhysics(),
+ itemBuilder: (context, index) {
+ final memoryLink = memoryLinks[index];
+ final memoryTitle = MemoryShareService.instance
+ .getMemoryShareTitle(memoryLink) ??
+ AppLocalizations.of(context).memories;
+ return GestureDetector(
+ onTap: () async {
+ await _openMemoryQuickLink(memoryLink, memoryTitle);
+ },
+ child: MemoryLinkAlbumItem(
+ title: memoryTitle,
+ fileCount: memoryLink.fileCount,
+ previewUploadedFileID: memoryLink.previewUploadedFileID,
+ ),
+ );
+ },
+ separatorBuilder: (context, index) {
+ return const SizedBox(height: 4);
+ },
+ itemCount: memoryLinks.length,
+ ),
+ ],
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ Future<List<MemoryShare>> _loadMemoryQuickLinks() async {
+ List<MemoryShare> memoryLinks = const [];
+ try {
+ memoryLinks = await MemoryShareService.instance.getLocalMemoryShares();
+ } catch (e, s) {
+ _logger.warning("failed to load memory links for shared tab", e, s);
+ }
+ return memoryLinks;
+ }
+
+ Future<void> _openMemoryQuickLink(
+ MemoryShare memoryLink,
+ String memoryTitle,
+ ) async {
+ try {
+ final files = await MemoryShareService.instance
+ .getPublicMemoryFiles(memoryLink.url);
+ if (!mounted) {
+ return;
+ }
+ final id = -(memoryLink.url.hashCode.abs() + 1);
+ final collection = Collection(
+ id,
+ User(email: ""),
+ "",
+ null,
+ memoryTitle,
+ null,
+ null,
+ CollectionType.album,
+ CollectionAttributes(),
+ const [],
+ const [],
+ DateTime.now().microsecondsSinceEpoch,
+ );
+ collection.setName(memoryTitle);
+ await routeToPage(
+ context,
+ SharedPublicCollectionPage(
+ CollectionWithThumbnail(collection, null),
+ files: files,
+ ),
+ );
+ } catch (e, s) {
+ _logger.severe("failed to open memory quick link", e, s);
+ if (mounted) {
+ await showGenericErrorDialog(context: context, error: e);
+ }
+ }
+ }
+
+ Widget _buildMemoryLinksSection({
+ required bool hasQuickLinks,
+ }) {
+ return FutureBuilder<List<MemoryShare>>(
+ future: _loadMemoryQuickLinks(),
+ builder: (context, snapshot) {
+ final memoryLinks = snapshot.data ?? const [];
+ if (memoryLinks.isEmpty) {
+ return const SizedBox.shrink();
+ }
+ return Column(
+ children: [
+ SectionOptions(
+ SectionTitle(
+ title: AppLocalizations.of(context).memories,
+ ),
+ ),
+ const SizedBox(height: 2),
+ ListView.separated(
+ shrinkWrap: true,
+ padding: EdgeInsets.only(
+ bottom: 12,
+ left: 12,
+ right: 12,
+ top: hasQuickLinks ? 0 : 12,
+ ),
+ physics: const NeverScrollableScrollPhysics(),
+ itemBuilder: (context, index) {
+ final memoryLink = memoryLinks[index];
+ final memoryTitle = MemoryShareService.instance
+ .getMemoryShareTitle(memoryLink) ??
+ AppLocalizations.of(context).memories;
+ return GestureDetector(
+ onTap: () async {
+ await _openMemoryQuickLink(memoryLink, memoryTitle);
+ },
+ child: MemoryLinkAlbumItem(
+ title: memoryTitle,
+ fileCount: memoryLink.fileCount,
+ previewUploadedFileID: memoryLink.previewUploadedFileID,
+ ),
+ );
+ },
+ separatorBuilder: (context, index) {
+ return const SizedBox(height: 4);
+ },
+ itemCount: memoryLinks.length,
+ ),
+ ],
+ );
+ },
+ );
+ }
+
Widget _getSharedCollectionsGallery(SharedCollections collections) {
const maxQuickLinks = 4;
final numberOfQuickLinks = collections.quickLinks.length;
@@ -441,43 +624,45 @@ class _SharedCollectionsTabState extends State<SharedCollectionsTab>
: null,
),
const SizedBox(height: 2),
- ListView.separated(
- shrinkWrap: true,
- padding: const EdgeInsets.only(
- bottom: 12,
- left: 12,
- right: 12,
+ if (numberOfQuickLinks > 0)
+ ListView.separated(
+ shrinkWrap: true,
+ padding: const EdgeInsets.only(
+ bottom: 12,
+ left: 12,
+ right: 12,
+ ),
+ physics: const NeverScrollableScrollPhysics(),
+ itemBuilder: (context, index) {
+ return GestureDetector(
+ onTap: () async {
+ final thumbnail = await CollectionsService
+ .instance
+ .getCover(collections.quickLinks[index]);
+ final page = CollectionPage(
+ CollectionWithThumbnail(
+ collections.quickLinks[index],
+ thumbnail,
+ ),
+ tagPrefix: heroTagPrefix,
+ );
+ // ignore: unawaited_futures
+ routeToPage(context, page);
+ },
+ child: QuickLinkAlbumItem(
+ c: collections.quickLinks[index],
+ ),
+ );
+ },
+ separatorBuilder: (context, index) {
+ return const SizedBox(height: 4);
+ },
+ itemCount: min(numberOfQuickLinks, maxQuickLinks),
),
- physics: const NeverScrollableScrollPhysics(),
- itemBuilder: (context, index) {
- return GestureDetector(
- onTap: () async {
- final thumbnail = await CollectionsService
- .instance
- .getCover(collections.quickLinks[index]);
- final page = CollectionPage(
- CollectionWithThumbnail(
- collections.quickLinks[index],
- thumbnail,
- ),
- tagPrefix: heroTagPrefix,
- );
- // ignore: unawaited_futures
- routeToPage(context, page);
- },
- child: QuickLinkAlbumItem(
- c: collections.quickLinks[index],
- ),
- );
- },
- separatorBuilder: (context, index) {
- return const SizedBox(height: 4);
- },
- itemCount: min(numberOfQuickLinks, maxQuickLinks),
- ),
],
)
: const SizedBox.shrink(),
+ _buildMemoryLinksSection(hasQuickLinks: numberOfQuickLinks > 0),
const SizedBox(height: 2),
ValueListenableBuilder(
valueListenable: _canLoadDeferredWidgets,