π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Add support for letting user choose which collection-scope the like to a file should go to if the file exists in multiple shared collections
ashilkn2f40d7033e28
diff --git a/mobile/apps/photos/lib/db/social_db.dart b/mobile/apps/photos/lib/db/social_db.dartindex baa71206a5..53c0e513d5 100644--- a/mobile/apps/photos/lib/db/social_db.dart+++ b/mobile/apps/photos/lib/db/social_db.dart@@ -387,8 +387,9 @@ class SocialDB {where = 'user_id = ? AND comment_id = ?';whereArgs = [userID, commentID];} else if (fileID != null) {- where = 'user_id = ? AND file_id = ? AND comment_id IS NULL';- whereArgs = [userID, fileID];+ where =+ 'user_id = ? AND collection_id = ? AND file_id = ? AND comment_id IS NULL';+ whereArgs = [userID, collectionID, fileID];} else {where ='user_id = ? AND collection_id = ? AND file_id IS NULL AND comment_id IS NULL';diff --git a/mobile/apps/photos/lib/services/collections_service.dart b/mobile/apps/photos/lib/services/collections_service.dartindex 9f9deb7181..a9542c4583 100644--- a/mobile/apps/photos/lib/services/collections_service.dart+++ b/mobile/apps/photos/lib/services/collections_service.dart@@ -268,6 +268,49 @@ class CollectionsService {return false;}+ /// Returns the count of shared collections containing this file.+ /// Uses early exit optimization - stops counting at 2.+ ///+ /// Returns:+ /// - 0: File not in any shared collection+ /// - 1: File in exactly one shared collection+ /// - 2: File in multiple shared collections (early exit)+ Future<int> getSharedCollectionCountForFile(int uploadedFileID) async {+ final Set<int> collectionIDs =+ await _filesDB.getAllCollectionIDsOfFile(uploadedFileID);++ if (collectionIDs.isEmpty) {+ return 0;+ }++ final int? currentUserID = _config.getUserID();+ if (currentUserID == null) {+ return 0;+ }++ int sharedCount = 0;+ for (final int collectionID in collectionIDs) {+ final Collection? collection = _collectionIDToCollections[collectionID];++ if (collection == null || collection.isDeleted) {+ continue;+ }++ // Same logic as isFileInSharedCollection+ if (collection.hasSharees ||+ collection.hasLink ||+ !collection.isOwner(currentUserID)) {+ sharedCount++;+ // Early exit: we only need to distinguish between 0, 1, and >1+ if (sharedCount > 1) {+ return 2;+ }+ }+ }++ return sharedCount;+ }+Future<List<Collection>> getArchivedCollection() async {final allCollections = getCollectionsForUI();return allCollectionsdiff --git a/mobile/apps/photos/lib/ui/social/like_collection_selector_sheet.dart b/mobile/apps/photos/lib/ui/social/like_collection_selector_sheet.dartnew file mode 100644index 0000000000..c3bc7ffdfd--- /dev/null+++ b/mobile/apps/photos/lib/ui/social/like_collection_selector_sheet.dart@@ -0,0 +1,486 @@+import "package:flutter/material.dart";+import "package:photos/core/constants.dart";+import "package:photos/db/files_db.dart";+import "package:photos/models/collection/collection.dart";+import "package:photos/models/file/extensions/file_props.dart";+import "package:photos/models/file/file.dart";+import "package:photos/models/social/social_data_provider.dart";+import "package:photos/services/collections_service.dart";+import "package:photos/theme/colors.dart";+import "package:photos/theme/ente_theme.dart";+import "package:photos/ui/components/buttons/icon_button_widget.dart";+import "package:photos/ui/notification/toast.dart";+import "package:photos/ui/viewer/file/thumbnail_widget.dart";++const _greenHeartColor = Color(0xFF08C225);++/// Holds collection info with mutable like state for the selector+class _CollectionLikeState {+ final Collection collection;+ final EnteFile? thumbnail;+ bool isLiked;++ _CollectionLikeState({+ required this.collection,+ this.thumbnail,+ required this.isLiked,+ });+}++/// Shows the like collection selector bottom sheet+///+/// Parameters:+/// - [fileID]: The uploaded file ID to like+/// - [currentUserID]: Current user's ID for checking existing likes+/// - [file]: The EnteFile for displaying thumbnail (optional, will fetch if null)+Future<void> showLikeCollectionSelectorSheet(+ BuildContext context, {+ required int fileID,+ required int currentUserID,+ EnteFile? file,+}) {+ return showModalBottomSheet(+ context: context,+ isScrollControlled: true,+ backgroundColor: Colors.transparent,+ builder: (_) => LikeCollectionSelectorSheet(+ fileID: fileID,+ currentUserID: currentUserID,+ file: file,+ ),+ );+}++class LikeCollectionSelectorSheet extends StatefulWidget {+ final int fileID;+ final int currentUserID;+ final EnteFile? file;++ const LikeCollectionSelectorSheet({+ required this.fileID,+ required this.currentUserID,+ this.file,+ super.key,+ });++ @override+ State<LikeCollectionSelectorSheet> createState() =>+ _LikeCollectionSelectorSheetState();+}++class _LikeCollectionSelectorSheetState+ extends State<LikeCollectionSelectorSheet> {+ static const _maxHeightFraction = 0.7;++ List<_CollectionLikeState> _collections = [];+ EnteFile? _file;+ bool _isLoading = true;+ bool _hasError = false;++ @override+ void initState() {+ super.initState();+ _file = widget.file;+ _loadData();+ }++ Future<void> _loadData() async {+ try {+ // Load file if not provided (for thumbnail)+ _file ??= await FilesDB.instance.getAnyUploadedFile(widget.fileID);++ // Get all collections containing this file+ final collectionIDs = await FilesDB.instance.getAllCollectionIDsOfFile(+ widget.fileID,+ );++ // Filter to shared collections only+ final sharedCollections = collectionIDs+ .map((id) => CollectionsService.instance.getCollectionByID(id))+ .whereType<Collection>()+ .where(+ (c) =>+ c.hasSharees || c.hasLink || !c.isOwner(widget.currentUserID),+ )+ .toList();++ // If no shared collections, close the sheet+ if (sharedCollections.isEmpty) {+ if (mounted) Navigator.of(context).pop();+ return;+ }++ // Fetch thumbnails and like states in parallel+ final collectionStates = await Future.wait(+ sharedCollections.map((collection) async {+ final thumbnail =+ await CollectionsService.instance.getCover(collection);+ final reactions = await SocialDataProvider.instance+ .getReactionsForFileInCollection(widget.fileID, collection.id);+ final isLiked = reactions.any(+ (r) => r.userID == widget.currentUserID && !r.isDeleted,+ );+ return _CollectionLikeState(+ collection: collection,+ thumbnail: thumbnail,+ isLiked: isLiked,+ );+ }),+ );++ if (!mounted) return;++ setState(() {+ _collections = collectionStates;+ _isLoading = false;+ });+ } catch (e, s) {+ debugPrint("Error loading like selector data: $e\n$s");+ if (mounted) {+ setState(() {+ _hasError = true;+ _isLoading = false;+ });+ }+ }+ }++ Future<void> _toggleLike(_CollectionLikeState state) async {+ final previousState = state.isLiked;+ // Optimistic UI update+ setState(() => state.isLiked = !state.isLiked);++ try {+ await SocialDataProvider.instance.toggleReaction(+ userID: widget.currentUserID,+ collectionID: state.collection.id,+ fileID: widget.fileID,+ );+ } catch (e) {+ // Revert on error+ if (mounted) {+ setState(() => state.isLiked = previousState);+ }+ debugPrint("Failed to toggle like: $e");+ }+ }++ Future<void> _likeAll() async {+ // Get collections that aren't already liked+ final toLike = _collections.where((c) => !c.isLiked).toList();++ if (toLike.isEmpty) {+ // All already liked, just close+ Navigator.of(context).pop();+ return;+ }++ // Optimistic UI update+ setState(() {+ for (final c in toLike) {+ c.isLiked = true;+ }+ });++ // Track failures for rollback+ final failed = <_CollectionLikeState>[];++ // Perform all likes in parallel+ await Future.wait(+ toLike.map((c) async {+ try {+ await SocialDataProvider.instance.toggleReaction(+ userID: widget.currentUserID,+ collectionID: c.collection.id,+ fileID: widget.fileID,+ );+ } catch (e) {+ failed.add(c);+ debugPrint("Failed to like ${c.collection.displayName}: $e");+ }+ }),+ );++ if (!mounted) return;++ // Rollback failed items and show toast+ if (failed.isNotEmpty) {+ setState(() {+ for (final c in failed) {+ c.isLiked = false;+ }+ });+ final msg = failed.length == 1+ ? "Failed to like 1 album"+ : "Failed to like ${failed.length} albums";+ showShortToast(context, msg);+ // Don't close sheet - let user retry+ return;+ }++ // Close sheet after successful "Like all"+ Navigator.of(context).pop();+ }++ bool get _isVideo => _file?.isVideo ?? false;++ String get _subtitle => _isVideo+ ? "Select the album to like this video"+ : "Select the album to like this photo";++ bool get _allLiked => _collections.every((c) => c.isLiked);++ @override+ Widget build(BuildContext context) {+ final colorScheme = getEnteColorScheme(context);+ final mediaQuery = MediaQuery.of(context);++ return Container(+ constraints: BoxConstraints(+ maxHeight: mediaQuery.size.height * _maxHeightFraction,+ ),+ decoration: BoxDecoration(+ color: colorScheme.backgroundBase,+ borderRadius: const BorderRadius.vertical(+ top: Radius.circular(24),+ ),+ ),+ child: SafeArea(+ top: false,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ _buildDragHandle(colorScheme),+ _buildHeader(),+ if (_isLoading)+ const Padding(+ padding: EdgeInsets.symmetric(vertical: 48),+ child: CircularProgressIndicator(),+ )+ else if (_hasError)+ _buildErrorState()+ else ...[+ _buildFileThumbnail(colorScheme),+ _buildTitleSection(),+ _buildAlbumsHeader(),+ Flexible(child: _buildAlbumsList()),+ ],+ ],+ ),+ ),+ );+ }++ Widget _buildDragHandle(EnteColorScheme colorScheme) {+ return Padding(+ padding: const EdgeInsets.only(top: 12),+ child: Container(+ width: 36,+ height: 4,+ decoration: BoxDecoration(+ color: colorScheme.strokeMuted,+ borderRadius: BorderRadius.circular(2),+ ),+ ),+ );+ }++ Widget _buildHeader() {+ return Padding(+ padding: const EdgeInsets.fromLTRB(16, 8, 12, 0),+ child: Row(+ mainAxisAlignment: MainAxisAlignment.end,+ children: [+ IconButtonWidget(+ iconButtonType: IconButtonType.rounded,+ icon: Icons.close_rounded,+ onTap: () => Navigator.of(context).pop(),+ ),+ ],+ ),+ );+ }++ Widget _buildFileThumbnail(EnteColorScheme colorScheme) {+ return Padding(+ padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),+ child: Center(+ child: SizedBox(+ width: 180,+ height: 180,+ child: Stack(+ clipBehavior: Clip.none,+ children: [+ ClipRRect(+ borderRadius: BorderRadius.circular(12),+ child: _file != null+ ? ThumbnailWidget(+ _file!,+ thumbnailSize: thumbnailLargeSize,+ rawThumbnail: true,+ )+ : Container(color: colorScheme.fillMuted),+ ),+ const Positioned(+ bottom: -8,+ right: -8,+ child: Icon(+ Icons.favorite,+ color: _greenHeartColor,+ size: 36,+ ),+ ),+ ],+ ),+ ),+ ),+ );+ }++ Widget _buildTitleSection() {+ final textTheme = getEnteTextTheme(context);+ final colorScheme = getEnteColorScheme(context);++ return Padding(+ padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),+ child: Column(+ children: [+ Text(+ "Like",+ style: textTheme.largeBold,+ ),+ const SizedBox(height: 4),+ Text(+ _subtitle,+ style: textTheme.small.copyWith(color: colorScheme.textMuted),+ ),+ ],+ ),+ );+ }++ Widget _buildAlbumsHeader() {+ final textTheme = getEnteTextTheme(context);+ final colorScheme = getEnteColorScheme(context);++ return Padding(+ padding: const EdgeInsets.fromLTRB(24, 8, 24, 8),+ child: Row(+ mainAxisAlignment: MainAxisAlignment.spaceBetween,+ children: [+ Text(+ "${_collections.length} ${_collections.length == 1 ? 'Album' : 'Albums'}",+ style: textTheme.bodyBold,+ ),+ GestureDetector(+ onTap: _likeAll,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),+ decoration: BoxDecoration(+ color: colorScheme.fillFaint,+ borderRadius: BorderRadius.circular(16),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ "Like all",+ style: textTheme.smallBold,+ ),+ const SizedBox(width: 4),+ Icon(+ _allLiked ? Icons.favorite : Icons.favorite_border,+ color: _allLiked ? _greenHeartColor : colorScheme.textBase,+ size: 16,+ ),+ ],+ ),+ ),+ ),+ ],+ ),+ );+ }++ Widget _buildAlbumsList() {+ return ListView.builder(+ shrinkWrap: _collections.length <= 10,+ padding: const EdgeInsets.fromLTRB(24, 0, 24, 16),+ itemCount: _collections.length,+ itemBuilder: (context, index) {+ final state = _collections[index];+ return _AlbumListItem(+ key: ValueKey(state.collection.id),+ state: state,+ onTap: () => _toggleLike(state),+ );+ },+ );+ }++ Widget _buildErrorState() {+ final textTheme = getEnteTextTheme(context);++ return Padding(+ padding: const EdgeInsets.symmetric(vertical: 48, horizontal: 24),+ child: Text(+ "Could not load albums",+ style: textTheme.smallMuted,+ textAlign: TextAlign.center,+ ),+ );+ }+}++class _AlbumListItem extends StatelessWidget {+ final _CollectionLikeState state;+ final VoidCallback onTap;++ const _AlbumListItem({+ required this.state,+ required this.onTap,+ super.key,+ });++ @override+ Widget build(BuildContext context) {+ final colorScheme = getEnteColorScheme(context);+ final textTheme = getEnteTextTheme(context);++ return GestureDetector(+ onTap: onTap,+ behavior: HitTestBehavior.opaque,+ child: Padding(+ padding: const EdgeInsets.symmetric(vertical: 8),+ child: Row(+ children: [+ SizedBox(+ width: 40,+ height: 40,+ child: ClipRRect(+ borderRadius: BorderRadius.circular(6),+ child: state.thumbnail != null+ ? ThumbnailWidget(state.thumbnail!)+ : Container(color: colorScheme.fillMuted),+ ),+ ),+ const SizedBox(width: 12),+ Expanded(+ child: Text(+ state.collection.displayName,+ style: textTheme.body,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ const SizedBox(width: 12),+ Icon(+ state.isLiked ? Icons.favorite : Icons.favorite_border,+ color: state.isLiked ? _greenHeartColor : colorScheme.textMuted,+ size: 24,+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/mobile/apps/photos/lib/ui/viewer/file/file_bottom_bar.dart b/mobile/apps/photos/lib/ui/viewer/file/file_bottom_bar.dartindex d2eee3c787..b205ef4ee7 100644--- a/mobile/apps/photos/lib/ui/viewer/file/file_bottom_bar.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/file_bottom_bar.dart@@ -1,13 +1,16 @@import "dart:async";import "dart:io";+import "package:collection/collection.dart";import "package:flutter/cupertino.dart";import "package:flutter/material.dart";import "package:hugeicons/hugeicons.dart";import "package:logging/logging.dart";import "package:photos/core/event_bus.dart";+import "package:photos/db/files_db.dart";import "package:photos/events/guest_view_event.dart";import "package:photos/generated/l10n.dart";+import "package:photos/models/collection/collection.dart";import "package:photos/models/file/extensions/file_props.dart";import "package:photos/models/file/file.dart";import "package:photos/models/file/trash_file.dart";@@ -16,7 +19,9 @@ import "package:photos/models/social/social_data_provider.dart";import "package:photos/services/collections_service.dart";import "package:photos/ui/actions/file/file_actions.dart";import "package:photos/ui/collections/collection_action_sheet.dart";+import "package:photos/ui/notification/toast.dart";import "package:photos/ui/social/comments_screen.dart";+import "package:photos/ui/social/like_collection_selector_sheet.dart";import "package:photos/ui/social/likes_bottom_sheet.dart";import "package:photos/utils/delete_file_util.dart";import "package:photos/utils/navigation_util.dart";@@ -331,14 +336,110 @@ class FileBottomBarState extends State<FileBottomBar> {return;}- await SocialDataProvider.instance.toggleReaction(- userID: widget.userID!,- collectionID: file.collectionID!,- fileID: file.uploadedFileID,- );+ // If already liked, unlike from ALL shared collections+ if (_hasLiked) {+ await _unlikeFromAllCollections();+ return;+ }++ // Check how many shared collections contain this file+ final sharedCount = await CollectionsService.instance+ .getSharedCollectionCountForFile(file.uploadedFileID!);++ if (sharedCount <= 1) {+ // Single shared collection: like directly (existing behavior)+ await SocialDataProvider.instance.toggleReaction(+ userID: widget.userID!,+ collectionID: file.collectionID!,+ fileID: file.uploadedFileID,+ );+ _hasLiked = true;+ safeRefresh();+ } else {+ // Multiple shared collections: show selector bottom sheet+ await showLikeCollectionSelectorSheet(+ context,+ fileID: file.uploadedFileID!,+ currentUserID: widget.userID!,+ file: file,+ );+ // Refresh state after sheet closes to sync heart icon+ await _updateSocialState();+ }+ }- _hasLiked = !_hasLiked;+ /// Removes the user's like from all shared collections containing this file+ Future<void> _unlikeFromAllCollections() async {+ final file = widget.file;+ if (file.uploadedFileID == null || widget.userID == null) return;++ final currentUserID = widget.userID!;+ final fileID = file.uploadedFileID!;++ // Optimistic UI update+ final previousState = _hasLiked;+ _hasLiked = false;safeRefresh();++ try {+ // Get all collections containing this file+ final collectionIDs = await FilesDB.instance.getAllCollectionIDsOfFile(+ fileID,+ );++ // Filter to shared collections+ final sharedCollections = collectionIDs+ .map((id) => CollectionsService.instance.getCollectionByID(id))+ .whereType<Collection>()+ .where(+ (c) => c.hasSharees || c.hasLink || !c.isOwner(currentUserID),+ )+ .toList();++ // Track failures+ int failedCount = 0;++ // Unlike from each collection where user has an active like+ for (final collection in sharedCollections) {+ try {+ final reactions = await SocialDataProvider.instance+ .getReactionsForFileInCollection(fileID, collection.id);++ final userReaction = reactions.firstWhereOrNull(+ (r) => r.userID == currentUserID && !r.isDeleted,+ );++ if (userReaction != null) {+ await SocialDataProvider.instance.toggleReaction(+ userID: currentUserID,+ collectionID: collection.id,+ fileID: fileID,+ );+ }+ } catch (e) {+ failedCount++;+ debugPrint("Failed to unlike from ${collection.displayName}: $e");+ }+ }++ // Show toast and rollback if any failed+ if (failedCount > 0 && mounted) {+ _hasLiked = previousState;+ safeRefresh();+ final msg = failedCount == 1+ ? "Failed to remove like from 1 album"+ : "Failed to remove like from $failedCount albums";+ showShortToast(context, msg);+ }+ } catch (e) {+ // Rollback on error (e.g., fetching collections failed)+ debugPrint("Failed to unlike from all collections: $e");+ if (mounted) {+ _hasLiked = previousState;+ safeRefresh();+ showShortToast(context, "Failed to remove like");+ }+ }}void _showLikesBottomSheet() {