π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][photos] Add social actions to memories
ashilkn4bbc9ea92c9f
diff --git a/mobile/apps/photos/changes/memories-social-actions.md b/mobile/apps/photos/changes/memories-social-actions.mdnew file mode 100644index 0000000000..992a0406db--- /dev/null+++ b/mobile/apps/photos/changes/memories-social-actions.md@@ -0,0 +1 @@+- Added likes, comments, and latest comment previews to memories.diff --git a/mobile/apps/photos/lib/db/social_db.dart b/mobile/apps/photos/lib/db/social_db.dartindex 28ff6085e8..acfb9d0aea 100644--- a/mobile/apps/photos/lib/db/social_db.dart+++ b/mobile/apps/photos/lib/db/social_db.dart@@ -153,6 +153,28 @@ class SocialDB {return rows.map(_rowToComment).toList();}+ Future<Comment?> getLatestCommentForFile(+ int fileID, {+ required List<int> collectionIDs,+ }) async {+ if (collectionIDs.isEmpty) {+ return null;+ }++ final placeholders = List.filled(collectionIDs.length, '?').join(',');+ final db = await database;+ final rows = await db.query(+ _commentsTable,+ where:+ 'file_id = ? AND is_deleted = 0 '+ 'AND collection_id IN ($placeholders)',+ whereArgs: [fileID, ...collectionIDs],+ orderBy: 'created_at DESC',+ limit: 1,+ );+ return rows.isEmpty ? null : _rowToComment(rows.first);+ }+Future<int> getCommentCountForFile(int fileID) async {final db = await database;final result = await db.rawQuery(diff --git a/mobile/apps/photos/lib/models/social/social_data_provider.dart b/mobile/apps/photos/lib/models/social/social_data_provider.dartindex fdd45ae468..b2cc58d7bf 100644--- a/mobile/apps/photos/lib/models/social/social_data_provider.dart+++ b/mobile/apps/photos/lib/models/social/social_data_provider.dart@@ -24,6 +24,13 @@ class SocialDataProvider {return _db.getCommentsForFile(fileID);}+ Future<Comment?> getLatestCommentForFile(+ int fileID, {+ required List<int> collectionIDs,+ }) {+ return _db.getLatestCommentForFile(fileID, collectionIDs: collectionIDs);+ }+Future<int> getCommentCountForFile(int fileID) {return _db.getCommentCountForFile(fileID);}diff --git a/mobile/apps/photos/lib/services/collections_service.dart b/mobile/apps/photos/lib/services/collections_service.dartindex 9da6a0f411..41e9581e7c 100644--- a/mobile/apps/photos/lib/services/collections_service.dart+++ b/mobile/apps/photos/lib/services/collections_service.dart@@ -295,6 +295,43 @@ class CollectionsService {return false;}+ /// Returns the shared collections containing [uploadedFileID].+ ///+ /// A collection is considered shared if it has sharees, has a public link,+ /// or is owned by someone else (incoming share). Results are sorted by ID so+ /// callers have a deterministic primary collection.+ Future<List<Collection>> getSharedCollectionsForFile(+ int uploadedFileID, {+ bool includeHidden = false,+ }) async {+ final Set<int> collectionIDs = await _filesDB.getAllCollectionIDsOfFile(+ uploadedFileID,+ );+ final int? currentUserID = _config.getUserID();+ if (collectionIDs.isEmpty || currentUserID == null) {+ return [];+ }++ final hiddenCollectionIDs = includeHidden+ ? const <int>{}+ : getHiddenCollectionIds();+ final sharedCollections =+ collectionIDs+ .map((collectionID) => _collectionIDToCollections[collectionID])+ .whereType<Collection>()+ .where(+ (collection) =>+ !collection.isDeleted &&+ !hiddenCollectionIDs.contains(collection.id) &&+ (collection.hasSharees ||+ collection.hasLink ||+ !collection.isOwner(currentUserID)),+ )+ .toList()+ ..sort((first, second) => first.id.compareTo(second.id));+ return sharedCollections;+ }+/// Returns the count of shared collections containing this file./// Uses early exit optimization - stops counting at 2.///diff --git a/mobile/apps/photos/lib/ui/home/memories/full_screen_memory.dart b/mobile/apps/photos/lib/ui/home/memories/full_screen_memory.dartindex 1ce9b15a8a..455887b8e8 100644--- a/mobile/apps/photos/lib/ui/home/memories/full_screen_memory.dart+++ b/mobile/apps/photos/lib/ui/home/memories/full_screen_memory.dart@@ -35,6 +35,7 @@ import "package:photos/ui/components/base_bottom_sheet.dart";import "package:photos/ui/home/memories/custom_listener.dart";import "package:photos/ui/home/memories/memory_progress_indicator.dart";import "package:photos/ui/home/memories/memory_video_prefetcher.dart";+import "package:photos/ui/social/widgets/file_social_overlay.dart";import "package:photos/ui/viewer/file/file_widget.dart";import "package:photos/ui/viewer/file/thumbnail_widget.dart";import "package:photos/ui/viewer/file_details/favorite_widget.dart";@@ -874,6 +875,28 @@ class _FullScreenMemoryState extends State<FullScreenMemory> {const BottomIcons(),],),+ ValueListenableBuilder<int>(+ valueListenable: inheritedData.indexNotifier,+ builder: (context, index, _) {+ final safeIndex = _clampedMemoryIndex(+ index,+ inheritedData.memories.length,+ );+ if (safeIndex == null) return const SizedBox.shrink();+ return FileSocialOverlay(+ file: inheritedData.memories[safeIndex].file,+ currentUserID: Configuration.instance.getUserID(),+ onInteractionStart: () {+ _toggleAnimation(pause: true);+ Bus.instance.fire(PauseVideoEvent());+ },+ onInteractionEnd: () {+ Bus.instance.fire(ResumeVideoEvent());+ _toggleAnimation(pause: false);+ },+ );+ },+ ),],),),diff --git a/mobile/apps/photos/lib/ui/social/like_collection_selector_sheet.dart b/mobile/apps/photos/lib/ui/social/like_collection_selector_sheet.dartindex 9b8352c76d..acdad1bf3a 100644--- a/mobile/apps/photos/lib/ui/social/like_collection_selector_sheet.dart+++ b/mobile/apps/photos/lib/ui/social/like_collection_selector_sheet.dart@@ -38,6 +38,7 @@ Future<void> showLikeCollectionSelectorSheet(required int fileID,required int currentUserID,EnteFile? file,+ Set<int>? allowedCollectionIDs,}) {return showModalBottomSheet(context: context,@@ -47,6 +48,7 @@ Future<void> showLikeCollectionSelectorSheet(fileID: fileID,currentUserID: currentUserID,file: file,+ allowedCollectionIDs: allowedCollectionIDs,),);}@@ -55,11 +57,13 @@ class LikeCollectionSelectorSheet extends StatefulWidget {final int fileID;final int currentUserID;final EnteFile? file;+ final Set<int>? allowedCollectionIDs;const LikeCollectionSelectorSheet({required this.fileID,required this.currentUserID,this.file,+ this.allowedCollectionIDs,super.key,});@@ -100,7 +104,11 @@ class _LikeCollectionSelectorSheetState.whereType<Collection>().where((c) =>- c.hasSharees || c.hasLink || !c.isOwner(widget.currentUserID),+ (c.hasSharees ||+ c.hasLink ||+ !c.isOwner(widget.currentUserID)) &&+ (widget.allowedCollectionIDs == null ||+ widget.allowedCollectionIDs!.contains(c.id)),).toList();diff --git a/mobile/apps/photos/lib/ui/social/widgets/file_social_overlay.dart b/mobile/apps/photos/lib/ui/social/widgets/file_social_overlay.dartnew file mode 100644index 0000000000..be7bf552a6--- /dev/null+++ b/mobile/apps/photos/lib/ui/social/widgets/file_social_overlay.dart@@ -0,0 +1,445 @@+import "dart:async";++import "package:collection/collection.dart";+import "package:ente_icons/ente_icons.dart";+import "package:flutter/material.dart";+import "package:logging/logging.dart";+import "package:photos/core/event_bus.dart";+import "package:photos/events/social_data_updated_event.dart";+import "package:photos/generated/l10n.dart";+import "package:photos/models/api/collection/user.dart";+import "package:photos/models/collection/collection.dart";+import "package:photos/models/file/file.dart";+import "package:photos/models/social/comment.dart";+import "package:photos/models/social/comment_author_utils.dart";+import "package:photos/models/social/reaction.dart";+import "package:photos/models/social/social_data_provider.dart";+import "package:photos/services/collections_service.dart";+import "package:photos/ui/notification/toast.dart";+import "package:photos/ui/sharing/user_avator_widget.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";++final _logger = Logger("FileSocialOverlay");++const _likedColor = Color(0xFF08C225);++class FileSocialOverlay extends StatefulWidget {+ final EnteFile file;+ final int? currentUserID;+ final VoidCallback onInteractionStart;+ final VoidCallback onInteractionEnd;+ final bool includeHiddenCollections;++ const FileSocialOverlay({+ required this.file,+ required this.currentUserID,+ required this.onInteractionStart,+ required this.onInteractionEnd,+ this.includeHiddenCollections = false,+ super.key,+ });++ @override+ State<FileSocialOverlay> createState() => _FileSocialOverlayState();+}++class _FileSocialOverlayState extends State<FileSocialOverlay> {+ late final StreamSubscription<SocialDataUpdatedEvent>+ _socialDataUpdatedSubscription;++ List<Collection> _sharedCollections = const [];+ bool _hasLiked = false;+ int _commentCount = 0;+ Comment? _latestComment;+ User? _latestCommentAuthor;+ int _loadGeneration = 0;++ @override+ void initState() {+ super.initState();+ _socialDataUpdatedSubscription = Bus.instance+ .on<SocialDataUpdatedEvent>()+ .listen((_) => unawaited(_refreshSocialState()));+ unawaited(_refreshSocialState());+ }++ @override+ void didUpdateWidget(covariant FileSocialOverlay oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (oldWidget.file.uploadedFileID != widget.file.uploadedFileID ||+ oldWidget.currentUserID != widget.currentUserID ||+ oldWidget.includeHiddenCollections != widget.includeHiddenCollections) {+ _loadGeneration++;+ _clearSocialState();+ unawaited(_refreshSocialState());+ }+ }++ @override+ void dispose() {+ _loadGeneration++;+ _socialDataUpdatedSubscription.cancel();+ super.dispose();+ }++ void _clearSocialState() {+ _sharedCollections = const [];+ _hasLiked = false;+ _commentCount = 0;+ _latestComment = null;+ _latestCommentAuthor = null;+ }++ bool _isCurrentLoad(int fileID, int generation) {+ return mounted &&+ generation == _loadGeneration &&+ widget.file.uploadedFileID == fileID;+ }++ Future<void> _refreshSocialState() async {+ final fileID = widget.file.uploadedFileID;+ final currentUserID = widget.currentUserID;+ final generation = ++_loadGeneration;++ if (fileID == null || currentUserID == null) {+ _clearSocialState();+ return;+ }++ try {+ final sharedCollections = await CollectionsService.instance+ .getSharedCollectionsForFile(+ fileID,+ includeHidden: widget.includeHiddenCollections,+ );+ if (!_isCurrentLoad(fileID, generation)) return;++ if (sharedCollections.isEmpty) {+ setState(_clearSocialState);+ return;+ }++ final provider = SocialDataProvider.instance;+ final collectionIDs = sharedCollections+ .map((collection) => collection.id)+ .toList();+ final results = await Future.wait<Object?>([+ provider.getReactionsForFile(fileID),+ provider.getCommentCountForFile(fileID),+ provider.getLatestCommentForFile(fileID, collectionIDs: collectionIDs),+ ]);+ if (!_isCurrentLoad(fileID, generation)) return;++ final reactions = results[0] as List<Reaction>;+ final commentCount = results[1] as int;+ final latestComment = results[2] as Comment?;+ User? latestCommentAuthor;+ if (latestComment != null) {+ final anonDisplayNames = latestComment.isAnonymous+ ? await provider.getAnonDisplayNamesForCollection(+ latestComment.collectionID,+ )+ : const <String, String>{};+ if (!_isCurrentLoad(fileID, generation)) return;++ latestCommentAuthor = CommentAuthorResolver().resolve(+ comment: latestComment,+ anonDisplayNames: anonDisplayNames,+ registeredUserResolver: (userID) => CollectionsService.instance+ .getFileOwner(userID, latestComment.collectionID),+ );+ }++ if (!_isCurrentLoad(fileID, generation)) return;+ setState(() {+ _sharedCollections = sharedCollections;+ _hasLiked = reactions.any(+ (reaction) => reaction.userID == currentUserID && !reaction.isDeleted,+ );+ _commentCount = commentCount;+ _latestComment = latestComment;+ _latestCommentAuthor = latestCommentAuthor;+ });+ } catch (error, stackTrace) {+ _logger.warning(+ "Failed to refresh social overlay for file $fileID",+ error,+ stackTrace,+ );+ }+ }++ Future<void> _toggleReaction() async {+ final file = widget.file;+ final fileID = file.uploadedFileID;+ final currentUserID = widget.currentUserID;+ if (fileID == null || currentUserID == null || _sharedCollections.isEmpty) {+ return;+ }++ if (_hasLiked) {+ await _unlikeFromAllCollections(fileID, currentUserID);+ return;+ }++ if (_sharedCollections.length == 1) {+ final previousState = _hasLiked;+ setState(() => _hasLiked = true);+ try {+ await SocialDataProvider.instance.toggleReaction(+ userID: currentUserID,+ collectionID: _sharedCollections.single.id,+ fileID: fileID,+ );+ } catch (error, stackTrace) {+ _logger.severe("Failed to like photo", error, stackTrace);+ if (mounted && widget.file.uploadedFileID == fileID) {+ setState(() => _hasLiked = previousState);+ showShortToast(+ context,+ AppLocalizations.of(context).failedToUpdateLike,+ );+ }+ }+ return;+ }++ await _runSheetAndRefresh(+ () => showLikeCollectionSelectorSheet(+ context,+ fileID: fileID,+ currentUserID: currentUserID,+ file: file,+ allowedCollectionIDs: _sharedCollections+ .map((collection) => collection.id)+ .toSet(),+ ),+ );+ }++ Future<void> _unlikeFromAllCollections(int fileID, int currentUserID) async {+ final previousState = _hasLiked;+ setState(() => _hasLiked = false);++ try {+ final sharedCollections = await CollectionsService.instance+ .getSharedCollectionsForFile(fileID, includeHidden: true);+ var failedCount = 0;+ for (final collection in sharedCollections) {+ try {+ final reactions = await SocialDataProvider.instance+ .getReactionsForFileInCollection(fileID, collection.id);+ final userReaction = reactions.firstWhereOrNull(+ (reaction) =>+ reaction.userID == currentUserID && !reaction.isDeleted,+ );+ if (userReaction != null) {+ await SocialDataProvider.instance.toggleReaction(+ userID: currentUserID,+ collectionID: collection.id,+ fileID: fileID,+ );+ }+ } catch (error, stackTrace) {+ failedCount++;+ _logger.warning(+ "Failed to unlike from ${collection.displayName}",+ error,+ stackTrace,+ );+ }+ }++ if (failedCount > 0 && mounted && widget.file.uploadedFileID == fileID) {+ setState(() => _hasLiked = previousState);+ showShortToast(+ context,+ AppLocalizations.of(context).failedToUpdateLike,+ );+ }+ } catch (error, stackTrace) {+ _logger.severe(+ "Failed to unlike from all collections",+ error,+ stackTrace,+ );+ if (mounted && widget.file.uploadedFileID == fileID) {+ setState(() => _hasLiked = previousState);+ showShortToast(+ context,+ AppLocalizations.of(context).failedToUpdateLike,+ );+ }+ }+ }++ Future<void> _showLikes() async {+ final fileID = widget.file.uploadedFileID;+ if (fileID == null || _sharedCollections.isEmpty) return;+ final initialCollectionID = _sharedCollections.first.id;+ await _runSheetAndRefresh(+ () => showLikesBottomSheet(+ context,+ fileID: fileID,+ initialCollectionID: initialCollectionID,+ ),+ );+ }++ Future<void> _openComments({Comment? comment}) async {+ final fileID = widget.file.uploadedFileID;+ if (fileID == null || _sharedCollections.isEmpty) return;+ await _runSheetAndRefresh(+ () => showFileCommentsBottomSheet(+ context,+ collectionID: comment?.collectionID ?? _sharedCollections.first.id,+ fileID: fileID,+ highlightCommentID: comment?.id,+ ),+ );+ }++ Future<void> _runSheetAndRefresh(Future<void> Function() showSheet) async {+ widget.onInteractionStart();+ try {+ await showSheet();+ await _refreshSocialState();+ } finally {+ widget.onInteractionEnd();+ }+ }++ @override+ Widget build(BuildContext context) {+ if (_sharedCollections.isEmpty) {+ return const SizedBox.shrink();+ }++ return Positioned(+ right: 16,+ bottom: 80,+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.end,+ children: [+ if (_latestComment != null && _latestCommentAuthor != null)+ Padding(+ padding: const EdgeInsets.only(right: 8, bottom: 4),+ child: _buildLatestCommentPill(+ _latestComment!,+ _latestCommentAuthor!,+ ),+ ),+ Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Tooltip(+ message: AppLocalizations.of(context).like,+ child: GestureDetector(+ onLongPress: () => unawaited(_showLikes()),+ child: IconButton(+ style: IconButton.styleFrom(+ overlayColor: WidgetStateColor.transparent,+ ),+ onPressed: () => unawaited(_toggleReaction()),+ icon: Icon(+ _hasLiked ? EnteIcons.likeFilled : EnteIcons.likeStroke,+ color: _hasLiked ? _likedColor : Colors.white,+ ),+ ),+ ),+ ),+ Tooltip(+ message: AppLocalizations.of(context).comments,+ child: IconButton(+ onPressed: () => unawaited(_openComments()),+ icon: _buildCommentIcon(),+ ),+ ),+ ],+ ),+ ],+ ),+ );+ }++ Widget _buildLatestCommentPill(Comment comment, User author) {+ final currentUserID = widget.currentUserID;+ if (currentUserID == null) return const SizedBox.shrink();++ return GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () => unawaited(_openComments(comment: comment)),+ child: ConstrainedBox(+ constraints: BoxConstraints(+ maxWidth: MediaQuery.sizeOf(context).width * 0.55,+ ),+ child: DecoratedBox(+ decoration: BoxDecoration(+ color: Colors.black.withValues(alpha: 0.65),+ borderRadius: BorderRadius.circular(18),+ border: Border.all(color: Colors.white.withValues(alpha: 0.18)),+ ),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ UserAvatarWidget(+ author,+ type: AvatarType.small,+ currentUserID: currentUserID,+ ),+ const SizedBox(width: 6),+ Flexible(+ child: Text(+ comment.data,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(color: Colors.white, fontSize: 12),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ );+ }++ Widget _buildCommentIcon() {+ return Stack(+ clipBehavior: Clip.none,+ children: [+ const Icon(EnteIcons.commentBubbleStroke, color: Colors.white),+ if (_commentCount > 0)+ Positioned(+ right: -4,+ top: -4,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),+ decoration: BoxDecoration(+ color: Colors.white,+ borderRadius: const BorderRadius.all(Radius.circular(16)),+ border: Border.all(+ color: Colors.black,+ width: 2,+ strokeAlign: BorderSide.strokeAlignOutside,+ ),+ ),+ child: Text(+ _commentCount > 99 ? "99+" : _commentCount.toString(),+ style: const TextStyle(+ color: Colors.black,+ fontSize: 8,+ fontWeight: FontWeight.w500,+ ),+ textAlign: TextAlign.center,+ ),+ ),+ ),+ ],+ );+ }+}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 eefa128818..524fa4de1e 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@@ -397,9 +397,7 @@ class FileBottomBarState extends State<FileBottomBar> {Future<void> _toggleReaction() async {final file = widget.file;- if (file.uploadedFileID == null ||- file.collectionID == null ||- widget.userID == null) {+ if (file.uploadedFileID == null || widget.userID == null) {return;}@@ -409,11 +407,14 @@ class FileBottomBarState extends State<FileBottomBar> {return;}- // Check how many shared collections contain this file- final sharedCount = await CollectionsService.instance- .getSharedCollectionCountForFile(file.uploadedFileID!);+ final sharedCollections = await CollectionsService.instance+ .getSharedCollectionsForFile(file.uploadedFileID!, includeHidden: true);- if (sharedCount <= 1) {+ if (sharedCollections.isEmpty) {+ return;+ }++ if (sharedCollections.length == 1) {// Single shared collection: like directlyfinal previousState = _hasLiked;_hasLiked = true;@@ -422,7 +423,7 @@ class FileBottomBarState extends State<FileBottomBar> {try {await SocialDataProvider.instance.toggleReaction(userID: widget.userID!,- collectionID: file.collectionID!,+ collectionID: sharedCollections.single.id,fileID: file.uploadedFileID,);} catch (e) {