Skip to content

armgit / ente

Public Imported from GitHub
0

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

initial integration for server api

Neeraj Gupta693da3d027fa
diff --git a/mobile/apps/photos/lib/db/social_db.dart b/mobile/apps/photos/lib/db/social_db.dart
index 53c0e513d5..ac75d5ff99 100644
--- a/mobile/apps/photos/lib/db/social_db.dart
+++ b/mobile/apps/photos/lib/db/social_db.dart
@@ -5,23 +5,26 @@ import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
+import 'package:photos/models/social/anon_profile.dart';
import 'package:photos/models/social/comment.dart';
import 'package:photos/models/social/reaction.dart';
import 'package:sqflite/sqflite.dart';
-import 'package:uuid/uuid.dart';
class SocialDB {
static final Logger _logger = Logger("SocialDB");
static const _databaseName = "ente.social.db";
static const _databaseVersion = 1;
- static const commentsTable = 'comments';
- static const reactionsTable = 'reactions';
+ static const _commentsTable = 'comments';
+ static const _reactionsTable = 'reactions';
+ static const _syncTimeTable = 'sync_time';
+ static const _anonProfilesTable = 'anon_profiles';
- SocialDB._privateConstructor();
- static final SocialDB instance = SocialDB._privateConstructor();
+ SocialDB._();
+ static final SocialDB instance = SocialDB._();
static Future<Database>? _dbFuture;
+
Future<Database> get database async {
_dbFuture ??= _initDatabase();
return _dbFuture!;
@@ -39,14 +42,15 @@ class SocialDB {
);
}
- Future _onCreate(Database db, int version) async {
+ Future<void> _onCreate(Database db, int version) async {
await db.execute('''
- CREATE TABLE $commentsTable (
+ CREATE TABLE $_commentsTable (
id TEXT PRIMARY KEY NOT NULL,
collection_id INTEGER NOT NULL,
file_id INTEGER,
data TEXT NOT NULL,
parent_comment_id TEXT,
+ parent_comment_user_id INTEGER,
is_deleted INTEGER NOT NULL DEFAULT 0,
user_id INTEGER NOT NULL,
anon_user_id TEXT,
@@ -56,7 +60,7 @@ class SocialDB {
''');
await db.execute('''
- CREATE TABLE $reactionsTable (
+ CREATE TABLE $_reactionsTable (
id TEXT PRIMARY KEY NOT NULL,
collection_id INTEGER NOT NULL,
file_id INTEGER,
@@ -69,39 +73,51 @@ class SocialDB {
updated_at INTEGER NOT NULL
)
''');
- }
- // Comment methods
+ await db.execute('''
+ CREATE TABLE $_syncTimeTable (
+ collection_id INTEGER PRIMARY KEY NOT NULL,
+ comments_sync_time INTEGER NOT NULL DEFAULT 0,
+ reactions_sync_time INTEGER NOT NULL DEFAULT 0,
+ anon_profiles_sync_time INTEGER NOT NULL DEFAULT 0
+ )
+ ''');
- Future<Comment?> addComment(Comment comment) async {
- if (comment.data.trim().isEmpty) {
- debugPrint('addComment: Cannot add comment with empty data');
- return null;
- }
+ await db.execute('''
+ CREATE TABLE $_anonProfilesTable (
+ anon_user_id TEXT NOT NULL,
+ collection_id INTEGER NOT NULL,
+ display_name TEXT NOT NULL,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL,
+ PRIMARY KEY (anon_user_id, collection_id)
+ )
+ ''');
- if (comment.parentCommentID != null) {
- final parentExists = await _commentExists(comment.parentCommentID!);
- if (!parentExists) {
- debugPrint(
- 'addComment: Parent comment ${comment.parentCommentID} does not exist',
- );
- return null;
- }
- }
+ // Create indexes for common queries
+ await db.execute(
+ 'CREATE INDEX idx_comments_file_collection ON $_commentsTable(file_id, collection_id)',
+ );
+ await db.execute(
+ 'CREATE INDEX idx_reactions_file_collection ON $_reactionsTable(file_id, collection_id)',
+ );
+ }
+ // ============ Comment Methods ============
+
+ Future<void> addComment(Comment comment) async {
final db = await database;
await db.insert(
- commentsTable,
+ _commentsTable,
_commentToRow(comment),
conflictAlgorithm: ConflictAlgorithm.replace,
);
- return comment;
}
Future<Comment?> deleteComment(String id) async {
final db = await database;
final rows = await db.query(
- commentsTable,
+ _commentsTable,
where: 'id = ?',
whereArgs: [id],
);
@@ -111,16 +127,16 @@ class SocialDB {
return null;
}
- final updatedAt = DateTime.now().millisecondsSinceEpoch;
+ final updatedAt = DateTime.now().microsecondsSinceEpoch;
await db.update(
- commentsTable,
+ _commentsTable,
{'is_deleted': 1, 'updated_at': updatedAt},
where: 'id = ?',
whereArgs: [id],
);
final updatedRows = await db.query(
- commentsTable,
+ _commentsTable,
where: 'id = ?',
whereArgs: [id],
);
@@ -130,7 +146,7 @@ class SocialDB {
Future<List<Comment>> getCommentsForFile(int fileID) async {
final db = await database;
final rows = await db.query(
- commentsTable,
+ _commentsTable,
where: 'file_id = ? AND is_deleted = 0',
whereArgs: [fileID],
);
@@ -138,18 +154,22 @@ class SocialDB {
}
Future<int> getCommentCountForFile(int fileID) async {
- final comments = await getCommentsForFile(fileID);
- return comments.length;
+ final db = await database;
+ final result = await db.rawQuery(
+ 'SELECT COUNT(*) as count FROM $_commentsTable '
+ 'WHERE file_id = ? AND is_deleted = 0',
+ [fileID],
+ );
+ return Sqflite.firstIntValue(result) ?? 0;
}
- /// Get comment count for a specific file within a specific collection
Future<int> getCommentCountForFileInCollection(
int fileID,
int collectionID,
) async {
final db = await database;
final result = await db.rawQuery(
- 'SELECT COUNT(*) as count FROM $commentsTable '
+ 'SELECT COUNT(*) as count FROM $_commentsTable '
'WHERE file_id = ? AND collection_id = ? AND is_deleted = 0',
[fileID, collectionID],
);
@@ -159,7 +179,7 @@ class SocialDB {
Future<List<Comment>> getCommentsForCollection(int collectionID) async {
final db = await database;
final rows = await db.query(
- commentsTable,
+ _commentsTable,
where: 'collection_id = ? AND file_id IS NULL AND is_deleted = 0',
whereArgs: [collectionID],
);
@@ -169,18 +189,17 @@ class SocialDB {
Future<List<Comment>> getRepliesForComment(String commentID) async {
final db = await database;
final rows = await db.query(
- commentsTable,
+ _commentsTable,
where: 'parent_comment_id = ? AND is_deleted = 0',
whereArgs: [commentID],
);
return rows.map(_rowToComment).toList();
}
- /// Fetch a single comment by ID (for parent lookup)
Future<Comment?> getCommentById(String id) async {
final db = await database;
final rows = await db.query(
- commentsTable,
+ _commentsTable,
where: 'id = ? AND is_deleted = 0',
whereArgs: [id],
);
@@ -188,7 +207,6 @@ class SocialDB {
return _rowToComment(rows.first);
}
- /// Paginated fetch for file comments within a specific collection
Future<List<Comment>> getCommentsForFilePaginated(
int fileID, {
required int collectionID,
@@ -197,7 +215,7 @@ class SocialDB {
}) async {
final db = await database;
final rows = await db.query(
- commentsTable,
+ _commentsTable,
where: 'file_id = ? AND collection_id = ? AND is_deleted = 0',
whereArgs: [fileID, collectionID],
orderBy: 'created_at DESC',
@@ -207,7 +225,6 @@ class SocialDB {
return rows.map(_rowToComment).toList();
}
- /// Paginated fetch for collection comments
Future<List<Comment>> getCommentsForCollectionPaginated(
int collectionID, {
int limit = 20,
@@ -215,7 +232,7 @@ class SocialDB {
}) async {
final db = await database;
final rows = await db.query(
- commentsTable,
+ _commentsTable,
where: 'collection_id = ? AND file_id IS NULL AND is_deleted = 0',
whereArgs: [collectionID],
orderBy: 'created_at DESC',
@@ -225,114 +242,25 @@ class SocialDB {
return rows.map(_rowToComment).toList();
}
- /// Delete all comments from the database
- Future<int> deleteAllComments() async {
- final db = await database;
- final deletedCount = await db.delete(commentsTable);
- _logger.info('Deleted $deletedCount comments');
- return deletedCount;
- }
-
- /// Delete all reactions from the database
- Future<int> deleteAllReactions() async {
- final db = await database;
- final deletedCount = await db.delete(reactionsTable);
- _logger.info('Deleted $deletedCount reactions');
- return deletedCount;
- }
-
- /// Seeds the database with example comments and reactions for testing.
- Future<void> seedExampleData() async {}
-
- // Reaction methods
-
- Future<Reaction?> addReaction(Reaction reaction) async {
- if (reaction.commentID != null) {
- final commentExists = await _commentExists(reaction.commentID!);
- if (!commentExists) {
- debugPrint(
- 'addReaction: Comment ${reaction.commentID} does not exist',
- );
- return null;
- }
- }
-
- final db = await database;
- await db.insert(
- reactionsTable,
- _reactionToRow(reaction),
- conflictAlgorithm: ConflictAlgorithm.replace,
- );
- return reaction;
- }
-
- Future<Reaction?> toggleReaction({
- required int userID,
- required int collectionID,
- int? fileID,
- String? commentID,
- }) async {
- final existingReaction = await _findExistingReaction(
- userID: userID,
- collectionID: collectionID,
- fileID: fileID,
- commentID: commentID,
- );
-
- if (existingReaction != null) {
- // Toggle is_deleted on existing reaction
- final db = await database;
- final updatedAt = DateTime.now().millisecondsSinceEpoch;
- final newIsDeleted = existingReaction.isDeleted ? 0 : 1;
-
- await db.update(
- reactionsTable,
- {'is_deleted': newIsDeleted, 'updated_at': updatedAt},
- where: 'id = ?',
- whereArgs: [existingReaction.id],
- );
-
- final updatedRows = await db.query(
- reactionsTable,
- where: 'id = ?',
- whereArgs: [existingReaction.id],
- );
- return _rowToReaction(updatedRows.first);
- } else {
- // Create new reaction
- final now = DateTime.now().millisecondsSinceEpoch;
- final reaction = Reaction(
- id: const Uuid().v4(),
- collectionID: collectionID,
- fileID: fileID,
- commentID: commentID,
- data: '',
- userID: userID,
- createdAt: now,
- updatedAt: now,
- );
- return addReaction(reaction);
- }
- }
+ // ============ Reaction Methods ============
Future<List<Reaction>> getReactionsForFile(int fileID) async {
final db = await database;
final rows = await db.query(
- reactionsTable,
+ _reactionsTable,
where: 'file_id = ? AND comment_id IS NULL AND is_deleted = 0',
whereArgs: [fileID],
);
return rows.map(_rowToReaction).toList();
}
- /// Get reactions for a file within a specific collection (file-level likes only)
Future<List<Reaction>> getReactionsForFileInCollection(
int fileID,
int collectionID,
) async {
final db = await database;
final rows = await db.query(
- reactionsTable,
+ _reactionsTable,
where:
'file_id = ? AND collection_id = ? AND comment_id IS NULL AND is_deleted = 0',
whereArgs: [fileID, collectionID],
@@ -343,7 +271,7 @@ class SocialDB {
Future<List<Reaction>> getReactionsForComment(String commentID) async {
final db = await database;
final rows = await db.query(
- reactionsTable,
+ _reactionsTable,
where: 'comment_id = ? AND is_deleted = 0',
whereArgs: [commentID],
);
@@ -353,7 +281,7 @@ class SocialDB {
Future<List<Reaction>> getReactionsForCollection(int collectionID) async {
final db = await database;
final rows = await db.query(
- reactionsTable,
+ _reactionsTable,
where:
'collection_id = ? AND file_id IS NULL AND comment_id IS NULL AND is_deleted = 0',
whereArgs: [collectionID],
@@ -361,110 +289,274 @@ class SocialDB {
return rows.map(_rowToReaction).toList();
}
- // Helper methods
+ // ============ Sync Time Methods ============
- Future<bool> _commentExists(String id) async {
+ Future<int> getCommentsSyncTime(int collectionID) async {
final db = await database;
final rows = await db.query(
- commentsTable,
- where: 'id = ?',
- whereArgs: [id],
+ _syncTimeTable,
+ where: 'collection_id = ?',
+ whereArgs: [collectionID],
);
- return rows.isNotEmpty;
+ if (rows.isEmpty) return 0;
+ return rows.first['comments_sync_time'] as int? ?? 0;
}
- Future<Reaction?> _findExistingReaction({
- required int userID,
- required int collectionID,
- int? fileID,
- String? commentID,
- }) async {
+ Future<int> getReactionsSyncTime(int collectionID) async {
+ final db = await database;
+ final rows = await db.query(
+ _syncTimeTable,
+ where: 'collection_id = ?',
+ whereArgs: [collectionID],
+ );
+ if (rows.isEmpty) return 0;
+ return rows.first['reactions_sync_time'] as int? ?? 0;
+ }
+
+ Future<void> setCommentsSyncTime(int collectionID, int syncTime) async {
+ final db = await database;
+ await db.insert(
+ _syncTimeTable,
+ {'collection_id': collectionID, 'comments_sync_time': syncTime},
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
+ }
+
+ Future<void> setReactionsSyncTime(int collectionID, int syncTime) async {
+ final db = await database;
+ await db.insert(
+ _syncTimeTable,
+ {'collection_id': collectionID, 'reactions_sync_time': syncTime},
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
+ }
+
+ Future<void> clearSyncTime(int collectionID) async {
+ final db = await database;
+ await db.delete(
+ _syncTimeTable,
+ where: 'collection_id = ?',
+ whereArgs: [collectionID],
+ );
+ }
+
+ Future<int> getAnonProfilesSyncTime(int collectionID) async {
+ final db = await database;
+ final rows = await db.query(
+ _syncTimeTable,
+ where: 'collection_id = ?',
+ whereArgs: [collectionID],
+ );
+ if (rows.isEmpty) return 0;
+ return rows.first['anon_profiles_sync_time'] as int? ?? 0;
+ }
+
+ Future<void> setAnonProfilesSyncTime(int collectionID, int syncTime) async {
final db = await database;
- String where;
- List<Object?> whereArgs;
-
- if (commentID != null) {
- where = 'user_id = ? AND comment_id = ?';
- whereArgs = [userID, commentID];
- } else if (fileID != null) {
- where =
- 'user_id = ? AND collection_id = ? AND file_id = ? AND comment_id IS NULL';
- whereArgs = [userID, collectionID, fileID];
+ // First check if the row exists
+ final rows = await db.query(
+ _syncTimeTable,
+ where: 'collection_id = ?',
+ whereArgs: [collectionID],
+ );
+ if (rows.isEmpty) {
+ await db.insert(
+ _syncTimeTable,
+ {'collection_id': collectionID, 'anon_profiles_sync_time': syncTime},
+ );
} else {
- where =
- 'user_id = ? AND collection_id = ? AND file_id IS NULL AND comment_id IS NULL';
- whereArgs = [userID, collectionID];
+ await db.update(
+ _syncTimeTable,
+ {'anon_profiles_sync_time': syncTime},
+ where: 'collection_id = ?',
+ whereArgs: [collectionID],
+ );
+ }
+ }
+
+ // ============ Bulk Upsert Methods ============
+
+ Future<void> upsertComments(List<Comment> comments) async {
+ if (comments.isEmpty) return;
+ final db = await database;
+ final batch = db.batch();
+ for (final comment in comments) {
+ batch.insert(
+ _commentsTable,
+ _commentToRow(comment),
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
+ }
+ await batch.commit(noResult: true);
+ }
+
+ Future<void> upsertReactions(List<Reaction> reactions) async {
+ if (reactions.isEmpty) return;
+ final db = await database;
+ final batch = db.batch();
+ for (final reaction in reactions) {
+ batch.insert(
+ _reactionsTable,
+ _reactionToRow(reaction),
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
}
+ await batch.commit(noResult: true);
+ }
+ // ============ Anon Profile Methods ============
+
+ Future<void> upsertAnonProfiles(List<AnonProfile> profiles) async {
+ if (profiles.isEmpty) return;
+ final db = await database;
+ final batch = db.batch();
+ for (final profile in profiles) {
+ batch.insert(
+ _anonProfilesTable,
+ _anonProfileToRow(profile),
+ conflictAlgorithm: ConflictAlgorithm.replace,
+ );
+ }
+ await batch.commit(noResult: true);
+ }
+
+ Future<List<AnonProfile>> getAnonProfilesForCollection(
+ int collectionID,
+ ) async {
+ final db = await database;
final rows = await db.query(
- reactionsTable,
- where: where,
- whereArgs: whereArgs,
+ _anonProfilesTable,
+ where: 'collection_id = ?',
+ whereArgs: [collectionID],
);
+ return rows.map(_rowToAnonProfile).toList();
+ }
+ Future<AnonProfile?> getAnonProfile(
+ String anonUserID,
+ int collectionID,
+ ) async {
+ final db = await database;
+ final rows = await db.query(
+ _anonProfilesTable,
+ where: 'anon_user_id = ? AND collection_id = ?',
+ whereArgs: [anonUserID, collectionID],
+ );
if (rows.isEmpty) return null;
- return _rowToReaction(rows.first);
+ return _rowToAnonProfile(rows.first);
}
+ // ============ Cleanup Methods ============
+
+ Future<void> deleteCollectionData(int collectionID) async {
+ final db = await database;
+ await db.delete(
+ _commentsTable,
+ where: 'collection_id = ?',
+ whereArgs: [collectionID],
+ );
+ await db.delete(
+ _reactionsTable,
+ where: 'collection_id = ?',
+ whereArgs: [collectionID],
+ );
+ await db.delete(
+ _anonProfilesTable,
+ where: 'collection_id = ?',
+ whereArgs: [collectionID],
+ );
+ await clearSyncTime(collectionID);
+ }
+
+ Future<void> clearAllData() async {
+ final db = await database;
+ await db.delete(_commentsTable);
+ await db.delete(_reactionsTable);
+ await db.delete(_anonProfilesTable);
+ await db.delete(_syncTimeTable);
+ }
+
+ // ============ Row Mappers ============
+
Map<String, dynamic> _commentToRow(Comment comment) {
- final map = comment.toMap();
return {
- 'id': map['id'],
- 'collection_id': map['collectionID'],
- 'file_id': map['fileID'],
- 'data': map['data'],
- 'parent_comment_id': map['parentCommentID'],
- 'is_deleted': map['isDeleted'] == true ? 1 : 0,
- 'user_id': map['userID'],
- 'anon_user_id': map['anonUserID'],
- 'created_at': map['createdAt'],
- 'updated_at': map['updatedAt'],
+ 'id': comment.id,
+ 'collection_id': comment.collectionID,
+ 'file_id': comment.fileID,
+ 'data': comment.data,
+ 'parent_comment_id': comment.parentCommentID,
+ 'parent_comment_user_id': comment.parentCommentUserID,
+ 'is_deleted': comment.isDeleted ? 1 : 0,
+ 'user_id': comment.userID,
+ 'anon_user_id': comment.anonUserID,
+ 'created_at': comment.createdAt,
+ 'updated_at': comment.updatedAt,
};
}
Comment _rowToComment(Map<String, dynamic> row) {
- return Comment.fromMap({
- 'id': row['id'],
- 'collectionID': row['collection_id'],
- 'fileID': row['file_id'],
- 'data': row['data'],
- 'parentCommentID': row['parent_comment_id'],
- 'isDeleted': row['is_deleted'] == 1,
- 'userID': row['user_id'],
- 'anonUserID': row['anon_user_id'],
- 'createdAt': row['created_at'],
- 'updatedAt': row['updated_at'],
- });
+ return Comment(
+ id: row['id'] as String,
+ collectionID: row['collection_id'] as int,
+ fileID: row['file_id'] as int?,
+ data: row['data'] as String,
+ parentCommentID: row['parent_comment_id'] as String?,
+ parentCommentUserID: row['parent_comment_user_id'] as int?,
+ isDeleted: row['is_deleted'] == 1,
+ userID: row['user_id'] as int,
+ anonUserID: row['anon_user_id'] as String?,
+ createdAt: row['created_at'] as int,
+ updatedAt: row['updated_at'] as int,
+ );
}
Map<String, dynamic> _reactionToRow(Reaction reaction) {
- final map = reaction.toMap();
return {
- 'id': map['id'],
- 'collection_id': map['collectionID'],
- 'file_id': map['fileID'],
- 'comment_id': map['commentID'],
- 'data': map['data'],
- 'is_deleted': map['isDeleted'] == true ? 1 : 0,
- 'user_id': map['userID'],
- 'anon_user_id': map['anonUserID'],
- 'created_at': map['createdAt'],
- 'updated_at': map['updatedAt'],
+ 'id': reaction.id,
+ 'collection_id': reaction.collectionID,
+ 'file_id': reaction.fileID,
+ 'comment_id': reaction.commentID,
+ 'data': reaction.data,
+ 'is_deleted': reaction.isDeleted ? 1 : 0,
+ 'user_id': reaction.userID,
+ 'anon_user_id': reaction.anonUserID,
+ 'created_at': reaction.createdAt,
+ 'updated_at': reaction.updatedAt,
};
}
Reaction _rowToReaction(Map<String, dynamic> row) {
- return Reaction.fromMap({
- 'id': row['id'],
- 'collectionID': row['collection_id'],
- 'fileID': row['file_id'],
- 'commentID': row['comment_id'],
- 'data': row['data'],
- 'isDeleted': row['is_deleted'] == 1,
- 'userID': row['user_id'],
- 'anonUserID': row['anon_user_id'],
- 'createdAt': row['created_at'],
- 'updatedAt': row['updated_at'],
- });
+ return Reaction(
+ id: row['id'] as String,
+ collectionID: row['collection_id'] as int,
+ fileID: row['file_id'] as int?,
+ commentID: row['comment_id'] as String?,
+ data: row['data'] as String,
+ isDeleted: row['is_deleted'] == 1,
+ userID: row['user_id'] as int,
+ anonUserID: row['anon_user_id'] as String?,
+ createdAt: row['created_at'] as int,
+ updatedAt: row['updated_at'] as int,
+ );
+ }
+
+ Map<String, dynamic> _anonProfileToRow(AnonProfile profile) {
+ return {
+ 'anon_user_id': profile.anonUserID,
+ 'collection_id': profile.collectionID,
+ 'display_name': profile.displayName,
+ 'created_at': profile.createdAt,
+ 'updated_at': profile.updatedAt,
+ };
+ }
+
+ AnonProfile _rowToAnonProfile(Map<String, dynamic> row) {
+ return AnonProfile(
+ anonUserID: row['anon_user_id'] as String,
+ collectionID: row['collection_id'] as int,
+ displayName: row['display_name'] as String,
+ createdAt: row['created_at'] as int,
+ updatedAt: row['updated_at'] as int,
+ );
}
}
diff --git a/mobile/apps/photos/lib/models/social/anon_profile.dart b/mobile/apps/photos/lib/models/social/anon_profile.dart
new file mode 100644
index 0000000000..01641bf529
--- /dev/null
+++ b/mobile/apps/photos/lib/models/social/anon_profile.dart
@@ -0,0 +1,28 @@
+/// Decrypted anonymous user profile stored locally.
+///
+/// Stores the decrypted display name for anonymous users who interact
+/// via shared album links.
+class AnonProfile {
+ /// The anonymous user ID (e.g., "anon_abc123")
+ final String anonUserID;
+
+ /// The collection this profile belongs to
+ final int collectionID;
+
+ /// The decrypted display name
+ final String displayName;
+
+ /// When the profile was created (microseconds since epoch)
+ final int createdAt;
+
+ /// When the profile was last updated (microseconds since epoch)
+ final int updatedAt;
+
+ AnonProfile({
+ required this.anonUserID,
+ required this.collectionID,
+ required this.displayName,
+ required this.createdAt,
+ required this.updatedAt,
+ });
+}
diff --git a/mobile/apps/photos/lib/models/social/api_responses.dart b/mobile/apps/photos/lib/models/social/api_responses.dart
new file mode 100644
index 0000000000..42639ebdef
--- /dev/null
+++ b/mobile/apps/photos/lib/models/social/api_responses.dart
@@ -0,0 +1,263 @@
+/// Raw comment data from the API (encrypted).
+///
+/// This represents the wire format from the server with cipher/nonce pairs.
+/// Decryption happens in the sync service before storing locally.
+class CommentApiResponse {
+ final String id;
+ final int collectionID;
+ final int? fileID;
+ final String? parentCommentID;
+ final int? parentCommentUserID;
+ final int userID;
+ final String? anonUserID;
+ final String? cipher;
+ final String? nonce;
+ final bool isDeleted;
+ final int createdAt;
+ final int updatedAt;
+
+ CommentApiResponse({
+ required this.id,
+ required this.collectionID,
+ this.fileID,
+ this.parentCommentID,
+ this.parentCommentUserID,
+ required this.userID,
+ this.anonUserID,
+ this.cipher,
+ this.nonce,
+ required this.isDeleted,
+ required this.createdAt,
+ required this.updatedAt,
+ });
+
+ factory CommentApiResponse.fromJson(Map<String, dynamic> json) {
+ return CommentApiResponse(
+ id: json['id'] as String,
+ collectionID: json['collectionID'] as int,
+ fileID: json['fileID'] as int?,
+ parentCommentID: json['parentCommentID'] as String?,
+ parentCommentUserID: json['parentCommentUserID'] as int?,
+ userID: json['userID'] as int,
+ anonUserID: json['anonUserID'] as String?,
+ cipher: json['cipher'] as String?,
+ nonce: json['nonce'] as String?,
+ isDeleted: json['isDeleted'] as bool? ?? false,
+ createdAt: json['createdAt'] as int,
+ updatedAt: json['updatedAt'] as int,
+ );
+ }
+}
+
+/// Raw reaction data from the API (encrypted).
+///
+/// This represents the wire format from the server with cipher/nonce pairs.
+/// Decryption happens in the sync service before storing locally.
+class ReactionApiResponse {
+ final String id;
+ final int collectionID;
+ final int? fileID;
+ final String? commentID;
+ final bool? isCommentReply;
+ final int userID;
+ final String? anonUserID;
+ final String? cipher;
+ final String? nonce;
+ final bool isDeleted;
+ final int createdAt;
+ final int updatedAt;
+
+ ReactionApiResponse({
+ required this.id,
+ required this.collectionID,
+ this.fileID,
+ this.commentID,
+ this.isCommentReply,
+ required this.userID,
+ this.anonUserID,
+ this.cipher,
+ this.nonce,
+ required this.isDeleted,
+ required this.createdAt,
+ required this.updatedAt,
+ });
+
+ factory ReactionApiResponse.fromJson(Map<String, dynamic> json) {
+ return ReactionApiResponse(
+ id: json['id'] as String,
+ collectionID: json['collectionID'] as int,
+ fileID: json['fileID'] as int?,
+ commentID: json['commentID'] as String?,
+ isCommentReply: json['isCommentReply'] as bool?,
+ userID: json['userID'] as int,
+ anonUserID: json['anonUserID'] as String?,
+ cipher: json['cipher'] as String?,
+ nonce: json['nonce'] as String?,
+ isDeleted: json['isDeleted'] as bool? ?? false,
+ createdAt: json['createdAt'] as int,
+ updatedAt: json['updatedAt'] as int,
+ );
+ }
+}
+
+/// Response from GET /comments/diff
+class CommentsDiffResponse {
+ final List<CommentApiResponse> comments;
+ final bool hasMore;
+
+ CommentsDiffResponse({
+ required this.comments,
+ required this.hasMore,
+ });
+
+ factory CommentsDiffResponse.fromJson(Map<String, dynamic> json) {
+ final commentsList = json['comments'] as List<dynamic>? ?? [];
+ return CommentsDiffResponse(
+ comments: commentsList
+ .map((e) => CommentApiResponse.fromJson(e as Map<String, dynamic>))
+ .toList(),
+ hasMore: json['hasMore'] as bool? ?? false,
+ );
+ }
+}
+
+/// Response from GET /reactions/diff
+class ReactionsDiffResponse {
+ final List<ReactionApiResponse> reactions;
+ final bool hasMore;
+
+ ReactionsDiffResponse({
+ required this.reactions,
+ required this.hasMore,
+ });
+
+ factory ReactionsDiffResponse.fromJson(Map<String, dynamic> json) {
+ final reactionsList = json['reactions'] as List<dynamic>? ?? [];
+ return ReactionsDiffResponse(
+ reactions: reactionsList
+ .map((e) => ReactionApiResponse.fromJson(e as Map<String, dynamic>))
+ .toList(),
+ hasMore: json['hasMore'] as bool? ?? false,
+ );
+ }
+}
+
+/// Response from GET /social/diff (unified endpoint)
+class SocialDiffResponse {
+ final List<CommentApiResponse> comments;
+ final List<ReactionApiResponse> reactions;
+ final bool hasMoreComments;
+ final bool hasMoreReactions;
+
+ SocialDiffResponse({
+ required this.comments,
+ required this.reactions,
+ required this.hasMoreComments,
+ required this.hasMoreReactions,
+ });
+
+ factory SocialDiffResponse.fromJson(Map<String, dynamic> json) {
+ final commentsList = json['comments'] as List<dynamic>? ?? [];
+ final reactionsList = json['reactions'] as List<dynamic>? ?? [];
+ return SocialDiffResponse(
+ comments: commentsList
+ .map((e) => CommentApiResponse.fromJson(e as Map<String, dynamic>))
+ .toList(),
+ reactions: reactionsList
+ .map((e) => ReactionApiResponse.fromJson(e as Map<String, dynamic>))
+ .toList(),
+ hasMoreComments: json['hasMoreComments'] as bool? ?? false,
+ hasMoreReactions: json['hasMoreReactions'] as bool? ?? false,
+ );
+ }
+}
+
+/// Per-collection latest update timestamps from GET /comments-reactions/updated-at
+class CollectionLatestUpdate {
+ final int collectionID;
+ final int? commentsUpdatedAt;
+ final int? reactionsUpdatedAt;
+ final int? anonProfilesUpdatedAt;
+
+ CollectionLatestUpdate({
+ required this.collectionID,
+ this.commentsUpdatedAt,
+ this.reactionsUpdatedAt,
+ this.anonProfilesUpdatedAt,
+ });
+
+ factory CollectionLatestUpdate.fromJson(Map<String, dynamic> json) {
+ return CollectionLatestUpdate(
+ collectionID: json['collectionID'] as int,
+ commentsUpdatedAt: json['commentsUpdatedAt'] as int?,
+ reactionsUpdatedAt: json['reactionsUpdatedAt'] as int?,
+ anonProfilesUpdatedAt: json['anonProfilesUpdatedAt'] as int?,
+ );
+ }
+}
+
+/// Response from GET /comments-reactions/updated-at
+class LatestUpdatesResponse {
+ final List<CollectionLatestUpdate> updates;
+
+ LatestUpdatesResponse({required this.updates});
+
+ factory LatestUpdatesResponse.fromJson(Map<String, dynamic> json) {
+ final updatesList = json['updates'] as List<dynamic>? ?? [];
+ return LatestUpdatesResponse(
+ updates: updatesList
+ .map(
+ (e) => CollectionLatestUpdate.fromJson(e as Map<String, dynamic>),
+ )
+ .toList(),
+ );
+ }
+}
+
+/// Anonymous user profile from GET /social/anon-profiles (encrypted)
+class AnonProfileApiResponse {
+ final String anonUserID;
+ final int collectionID;
+ final String cipher;
+ final String nonce;
+ final int createdAt;
+ final int updatedAt;
+
+ AnonProfileApiResponse({
+ required this.anonUserID,
+ required this.collectionID,
+ required this.cipher,
+ required this.nonce,
+ required this.createdAt,
+ required this.updatedAt,
+ });
+
+ factory AnonProfileApiResponse.fromJson(Map<String, dynamic> json) {
+ return AnonProfileApiResponse(
+ anonUserID: json['anonUserID'] as String,
+ collectionID: json['collectionID'] as int,
+ cipher: json['cipher'] as String,
+ nonce: json['nonce'] as String,
+ createdAt: json['createdAt'] as int,
+ updatedAt: json['updatedAt'] as int,
+ );
+ }
+}
+
+/// Response from GET /social/anon-profiles
+class AnonProfilesResponse {
+ final List<AnonProfileApiResponse> profiles;
+
+ AnonProfilesResponse({required this.profiles});
+
+ factory AnonProfilesResponse.fromJson(Map<String, dynamic> json) {
+ final profilesList = json['profiles'] as List<dynamic>? ?? [];
+ return AnonProfilesResponse(
+ profiles: profilesList
+ .map(
+ (e) => AnonProfileApiResponse.fromJson(e as Map<String, dynamic>),
+ )
+ .toList(),
+ );
+ }
+}
diff --git a/mobile/apps/photos/lib/models/social/comment.dart b/mobile/apps/photos/lib/models/social/comment.dart
index fc46b7b2fe..aeeb02c074 100644
--- a/mobile/apps/photos/lib/models/social/comment.dart
+++ b/mobile/apps/photos/lib/models/social/comment.dart
@@ -4,6 +4,7 @@ class Comment {
final int? fileID;
final String data;
final String? parentCommentID;
+ final int? parentCommentUserID;
final bool isDeleted;
final int userID;
final String? anonUserID;
@@ -16,6 +17,7 @@ class Comment {
this.fileID,
required this.data,
this.parentCommentID,
+ this.parentCommentUserID,
this.isDeleted = false,
required this.userID,
this.anonUserID,
@@ -35,6 +37,7 @@ class Comment {
int? fileID,
String? data,
String? parentCommentID,
+ int? parentCommentUserID,
bool? isDeleted,
int? userID,
String? anonUserID,
@@ -47,6 +50,7 @@ class Comment {
fileID: fileID ?? this.fileID,
data: data ?? this.data,
parentCommentID: parentCommentID ?? this.parentCommentID,
+ parentCommentUserID: parentCommentUserID ?? this.parentCommentUserID,
isDeleted: isDeleted ?? this.isDeleted,
userID: userID ?? this.userID,
anonUserID: anonUserID ?? this.anonUserID,
@@ -62,6 +66,7 @@ class Comment {
'fileID': fileID,
'data': data,
'parentCommentID': parentCommentID,
+ 'parentCommentUserID': parentCommentUserID,
'isDeleted': isDeleted,
'userID': userID,
'anonUserID': anonUserID,
@@ -77,6 +82,7 @@ class Comment {
fileID: map['fileID'] as int?,
data: map['data'] as String,
parentCommentID: map['parentCommentID'] as String?,
+ parentCommentUserID: map['parentCommentUserID'] as int?,
isDeleted: map['isDeleted'] as bool? ?? false,
userID: map['userID'] as int,
anonUserID: map['anonUserID'] as String?,
diff --git a/mobile/apps/photos/lib/models/social/social_data_provider.dart b/mobile/apps/photos/lib/models/social/social_data_provider.dart
index 2ee9eb815a..09f2f282c7 100644
--- a/mobile/apps/photos/lib/models/social/social_data_provider.dart
+++ b/mobile/apps/photos/lib/models/social/social_data_provider.dart
@@ -1,14 +1,24 @@
+import "package:logging/logging.dart";
+import "package:photos/core/configuration.dart";
import "package:photos/db/social_db.dart";
import "package:photos/models/social/comment.dart";
import "package:photos/models/social/reaction.dart";
+import "package:photos/services/social_service.dart";
+import "package:photos/services/social_sync_service.dart";
+/// Provider for social data (comments and reactions).
+///
+/// Orchestrates between local database and remote API.
+/// Query methods read from local DB, mutation methods call API then update DB.
class SocialDataProvider {
SocialDataProvider._();
static final instance = SocialDataProvider._();
+ final _logger = Logger('SocialDataProvider');
final _db = SocialDB.instance;
+ final _api = SocialService.instance;
- // Query methods
+ // ============ Query methods (read from local DB) ============
Future<List<Comment>> getCommentsForFile(int fileID) {
return _db.getCommentsForFile(fileID);
@@ -71,8 +81,6 @@ class SocialDataProvider {
);
}
- // Collection-level queries
-
Future<List<Comment>> getCommentsForCollection(int collectionID) {
return _db.getCommentsForCollection(collectionID);
}
@@ -81,29 +89,209 @@ class SocialDataProvider {
return _db.getReactionsForCollection(collectionID);
}
- // Comment mutation methods
+ // ============ Sync methods ============
+
+ /// Syncs reactions for a specific file.
+ /// Call this before displaying reactions for a file to ensure data is fresh.
+ Future<void> syncFileReactions(int collectionID, int fileID) {
+ return SocialSyncService.instance.syncFileReactions(collectionID, fileID);
+ }
+
+ /// Syncs both comments and reactions for a specific file.
+ /// Call this before displaying comments screen to ensure data is fresh.
+ Future<void> syncFileSocialData(int collectionID, int fileID) {
+ return SocialSyncService.instance.syncFileSocialData(collectionID, fileID);
+ }
+
+ // ============ Comment mutation methods ============
+
+ /// Adds a comment via API, then stores locally.
+ ///
+ /// Returns the created Comment on success, null on failure.
+ Future<Comment?> addComment({
+ required int collectionID,
+ required String text,
+ int? fileID,
+ String? parentCommentID,
+ }) async {
+ try {
+ // Encrypt the comment text
+ final encrypted = _api.encryptComment(text, collectionID);
+
+ // Call API
+ final commentID = await _api.createComment(
+ collectionID: collectionID,
+ cipher: encrypted.cipher,
+ nonce: encrypted.nonce,
+ fileID: fileID,
+ parentCommentID: parentCommentID,
+ );
+
+ // Create local comment object (timestamps in microseconds to match server)
+ final now = DateTime.now().microsecondsSinceEpoch;
+ final userID = Configuration.instance.getUserID() ?? 0;
+ final comment = Comment(
+ id: commentID,
+ collectionID: collectionID,
+ fileID: fileID,
+ data: text,
+ parentCommentID: parentCommentID,
+ userID: userID,
+ createdAt: now,
+ updatedAt: now,
+ );
- Future<Comment?> addComment(Comment comment) {
- return _db.addComment(comment);
+ // Store locally
+ await _db.addComment(comment);
+ return comment;
+ } catch (e) {
+ _logger.severe('Failed to add comment', e);
+ return null;
+ }
}
- Future<Comment?> deleteComment(String id) {
- return _db.deleteComment(id);
+ /// Deletes a comment via API, then marks as deleted locally.
+ ///
+ /// Returns the deleted Comment on success, null on failure.
+ Future<Comment?> deleteComment(String id) async {
+ try {
+ // Call API
+ await _api.deleteComment(id);
+
+ // Mark as deleted locally
+ return _db.deleteComment(id);
+ } catch (e) {
+ _logger.severe('Failed to delete comment $id', e);
+ return null;
+ }
}
- // Reaction mutation methods
+ // ============ Reaction mutation methods ============
+ /// Toggles a reaction (like) on a file or comment.
+ ///
+ /// If the user hasn't reacted, creates a new reaction.
+ /// If the user has already reacted, deletes the existing reaction.
+ ///
+ /// Returns the new reaction state (Reaction with isDeleted flag).
Future<Reaction?> toggleReaction({
required int userID,
required int collectionID,
int? fileID,
String? commentID,
- }) {
- return _db.toggleReaction(
- userID: userID,
- collectionID: collectionID,
- fileID: fileID,
- commentID: commentID,
+ String reactionType = 'green_like',
+ }) async {
+ try {
+ // Check if user already has a reaction
+ final existingReaction = await _findExistingReaction(
+ userID: userID,
+ collectionID: collectionID,
+ fileID: fileID,
+ commentID: commentID,
+ );
+
+ if (existingReaction != null && !existingReaction.isDeleted) {
+ // User has an active reaction - delete it
+ await _api.deleteReaction(existingReaction.id);
+
+ // Mark as deleted locally (timestamps in microseconds to match server)
+ final now = DateTime.now().microsecondsSinceEpoch;
+ final deletedReaction = existingReaction.copyWith(
+ isDeleted: true,
+ updatedAt: now,
+ );
+ await _db.upsertReactions([deletedReaction]);
+ return deletedReaction;
+ } else {
+ // User doesn't have a reaction or it's deleted - create/upsert one
+ final encrypted =
+ _api.encryptReaction(reactionType, collectionID);
+
+ final reactionID = await _api.upsertReaction(
+ collectionID: collectionID,
+ cipher: encrypted.cipher,
+ nonce: encrypted.nonce,
+ fileID: fileID,
+ commentID: commentID,
+ );
+
+ // Create local reaction object (timestamps in microseconds to match server)
+ final now = DateTime.now().microsecondsSinceEpoch;
+ final reaction = Reaction(
+ id: reactionID,
+ collectionID: collectionID,
+ fileID: fileID,
+ commentID: commentID,
+ data: reactionType,
+ isDeleted: false,
+ userID: userID,
+ createdAt: existingReaction?.createdAt ?? now,
+ updatedAt: now,
+ );
+
+ // Store locally
+ await _db.upsertReactions([reaction]);
+ return reaction;
+ }
+ } catch (e) {
+ _logger.severe('Failed to toggle reaction', e);
+ return null;
+ }
+ }
+
+ /// Finds an existing reaction for the user on the given target.
+ Future<Reaction?> _findExistingReaction({
+ required int userID,
+ required int collectionID,
+ int? fileID,
+ String? commentID,
+ }) async {
+ if (commentID != null) {
+ final reactions = await _db.getReactionsForComment(commentID);
+ for (final r in reactions) {
+ if (r.userID == userID) return r;
+ }
+ } else if (fileID != null) {
+ final reactions = await _db.getReactionsForFileInCollection(
+ fileID,
+ collectionID,
+ );
+ for (final r in reactions) {
+ if (r.userID == userID) return r;
+ }
+ } else {
+ final reactions = await _db.getReactionsForCollection(collectionID);
+ for (final r in reactions) {
+ if (r.userID == userID) return r;
+ }
+ }
+ return null;
+ }
+
+ /// Checks if the current user has liked a file in a collection.
+ Future<bool> hasUserLikedFile(int fileID, int collectionID) async {
+ final userID = Configuration.instance.getUserID();
+ if (userID == null) return false;
+
+ final reactions = await _db.getReactionsForFileInCollection(
+ fileID,
+ collectionID,
+ );
+ return reactions.any((r) => r.userID == userID && !r.isDeleted);
+ }
+
+ /// Gets the current user's reaction on a file in a collection (if any).
+ Future<Reaction?> getUserReactionForFile(int fileID, int collectionID) async {
+ final userID = Configuration.instance.getUserID();
+ if (userID == null) return null;
+
+ final reactions = await _db.getReactionsForFileInCollection(
+ fileID,
+ collectionID,
);
+ for (final r in reactions) {
+ if (r.userID == userID && !r.isDeleted) return r;
+ }
+ return null;
}
}
diff --git a/mobile/apps/photos/lib/services/social_service.dart b/mobile/apps/photos/lib/services/social_service.dart
new file mode 100644
index 0000000000..9b7039f269
--- /dev/null
+++ b/mobile/apps/photos/lib/services/social_service.dart
@@ -0,0 +1,529 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:dio/dio.dart';
+import 'package:ente_crypto/ente_crypto.dart';
+import 'package:logging/logging.dart';
+import 'package:nanoid/nanoid.dart';
+import 'package:photos/core/network/network.dart';
+import 'package:photos/models/social/api_responses.dart';
+import 'package:photos/services/collections_service.dart';
+
+/// Service for social features (comments and reactions).
+///
+/// Handles API calls and encryption/decryption using collection keys.
+class SocialService {
+ SocialService._();
+ static final instance = SocialService._();
+
+ final _logger = Logger('SocialService');
+ final _enteDio = NetworkClient.instance.enteDio;
+
+ static const _commentIDLength = 21;
+ static const _reactionIDLength = 21;
+ static const _commentPrefix = 'cmt_';
+ static const _reactionPrefix = 'rct_';
+ static const _alphabet =
+ '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
+
+ /// Reaction type padding length before encryption.
+ /// Ensures all encrypted reactions have the same ciphertext length.
+ static const _reactionPadLength = 100;
+
+ /// Generates a new comment ID in the format: cmt_ + 21 char nanoid
+ String generateCommentID() {
+ return '$_commentPrefix${customAlphabet(_alphabet, _commentIDLength)}';
+ }
+
+ /// Generates a new reaction ID in the format: rct_ + 21 char nanoid
+ String generateReactionID() {
+ return '$_reactionPrefix${customAlphabet(_alphabet, _reactionIDLength)}';
+ }
+
+ // ============ Comments API ============
+
+ /// Creates a new comment on the server.
+ ///
+ /// [collectionID] - The collection this comment belongs to
+ /// [cipher] - The encrypted comment text (base64)
+ /// [nonce] - The encryption nonce (base64)
+ /// [fileID] - Optional file ID if commenting on a file
+ /// [parentCommentID] - Optional parent comment ID for replies
+ /// [id] - Optional comment ID; generated if not provided
+ ///
+ /// Returns the comment ID (server-assigned or the provided one)
+ Future<String> createComment({
+ required int collectionID,
+ required String cipher,
+ required String nonce,
+ int? fileID,
+ String? parentCommentID,
+ String? id,
+ }) async {
+ final commentID = id ?? generateCommentID();
+
+ final data = <String, dynamic>{
+ 'id': commentID,
+ 'collectionID': collectionID,
+ 'cipher': cipher,
+ 'nonce': nonce,
+ };
+
+ if (fileID != null) {
+ data['fileID'] = fileID;
+ }
+ if (parentCommentID != null) {
+ data['parentCommentID'] = parentCommentID;
+ }
+
+ try {
+ final response = await _enteDio.post('/comments', data: data);
+ return response.data['id'] as String;
+ } on DioException catch (e) {
+ _logger.severe('Failed to create comment', e);
+ rethrow;
+ }
+ }
+
+ /// Updates an existing comment.
+ ///
+ /// [commentID] - The comment ID to update
+ /// [cipher] - The new encrypted comment text (base64)
+ /// [nonce] - The new encryption nonce (base64)
+ Future<void> updateComment({
+ required String commentID,
+ required String cipher,
+ required String nonce,
+ }) async {
+ try {
+ await _enteDio.put(
+ '/comments/$commentID',
+ data: {'cipher': cipher, 'nonce': nonce},
+ );
+ } on DioException catch (e) {
+ _logger.severe('Failed to update comment $commentID', e);
+ rethrow;
+ }
+ }
+
+ /// Deletes a comment (soft delete on server).
+ Future<void> deleteComment(String commentID) async {
+ try {
+ await _enteDio.delete('/comments/$commentID');
+ } on DioException catch (e) {
+ _logger.severe('Failed to delete comment $commentID', e);
+ rethrow;
+ }
+ }
+
+ /// Fetches comments diff for a collection.
+ ///
+ /// [collectionID] - The collection to fetch comments from
+ /// [sinceTime] - Only fetch comments updated after this timestamp
+ /// [limit] - Maximum number of comments to fetch (default 1000, max 2000)
+ /// [fileID] - Optional filter for comments on a specific file
+ ///
+ /// Returns [CommentsDiffResponse] with comments and hasMore flag
+ Future<CommentsDiffResponse> fetchCommentsDiff({
+ required int collectionID,
+ int? sinceTime,
+ int? limit,
+ int? fileID,
+ }) async {
+ final queryParams = <String, dynamic>{
+ 'collectionID': collectionID,
+ };
+
+ if (sinceTime != null) {
+ queryParams['sinceTime'] = sinceTime;
+ }
+ if (limit != null) {
+ queryParams['limit'] = limit;
+ }
+ if (fileID != null) {
+ queryParams['fileID'] = fileID;
+ }
+
+ try {
+ final response = await _enteDio.get(
+ '/comments/diff',
+ queryParameters: queryParams,
+ );
+ return CommentsDiffResponse.fromJson(
+ response.data as Map<String, dynamic>,
+ );
+ } on DioException catch (e) {
+ _logger.severe(
+ 'Failed to fetch comments diff for collection $collectionID',
+ e,
+ );
+ rethrow;
+ }
+ }
+
+ // ============ Reactions API ============
+
+ /// Creates or updates a reaction (upsert).
+ ///
+ /// [collectionID] - The collection this reaction belongs to
+ /// [cipher] - The encrypted reaction type (base64, exactly 156 bytes)
+ /// [nonce] - The encryption nonce (base64)
+ /// [fileID] - Optional file ID if reacting to a file
+ /// [commentID] - Optional comment ID if reacting to a comment
+ /// [id] - Optional reaction ID; generated if not provided
+ ///
+ /// Returns the reaction ID
+ Future<String> upsertReaction({
+ required int collectionID,
+ required String cipher,
+ required String nonce,
+ int? fileID,
+ String? commentID,
+ String? id,
+ }) async {
+ final reactionID = id ?? generateReactionID();
+
+ final data = <String, dynamic>{
+ 'id': reactionID,
+ 'collectionID': collectionID,
+ 'cipher': cipher,
+ 'nonce': nonce,
+ };
+
+ if (fileID != null) {
+ data['fileID'] = fileID;
+ }
+ if (commentID != null) {
+ data['commentID'] = commentID;
+ }
+
+ try {
+ final response = await _enteDio.put('/reactions', data: data);
+ return response.data['id'] as String;
+ } on DioException catch (e) {
+ _logger.severe('Failed to upsert reaction', e);
+ rethrow;
+ }
+ }
+
+ /// Deletes a reaction (soft delete on server).
+ Future<void> deleteReaction(String reactionID) async {
+ try {
+ await _enteDio.delete('/reactions/$reactionID');
+ } on DioException catch (e) {
+ _logger.severe('Failed to delete reaction $reactionID', e);
+ rethrow;
+ }
+ }
+
+ /// Fetches reactions diff for a collection.
+ ///
+ /// [collectionID] - The collection to fetch reactions from
+ /// [sinceTime] - Only fetch reactions updated after this timestamp
+ /// [limit] - Maximum number of reactions to fetch (default 1000, max 2000)
+ /// [fileID] - Optional filter for reactions on a specific file
+ /// [commentID] - Optional filter for reactions on a specific comment
+ ///
+ /// Returns [ReactionsDiffResponse] with reactions and hasMore flag
+ Future<ReactionsDiffResponse> fetchReactionsDiff({
+ required int collectionID,
+ int? sinceTime,
+ int? limit,
+ int? fileID,
+ String? commentID,
+ }) async {
+ final queryParams = <String, dynamic>{
+ 'collectionID': collectionID,
+ };
+
+ if (sinceTime != null) {
+ queryParams['sinceTime'] = sinceTime;
+ }
+ if (limit != null) {
+ queryParams['limit'] = limit;
+ }
+ if (fileID != null) {
+ queryParams['fileID'] = fileID;
+ }
+ if (commentID != null) {
+ queryParams['commentID'] = commentID;
+ }
+
+ try {
+ final response = await _enteDio.get(
+ '/reactions/diff',
+ queryParameters: queryParams,
+ );
+ return ReactionsDiffResponse.fromJson(
+ response.data as Map<String, dynamic>,
+ );
+ } on DioException catch (e) {
+ _logger.severe(
+ 'Failed to fetch reactions diff for collection $collectionID',
+ e,
+ );
+ rethrow;
+ }
+ }
+
+ // ============ Latest Updates API ============
+
+ /// Fetches latest update timestamps for all collections accessible to the user.
+ ///
+ /// Returns per-collection timestamps for comments, reactions, and anonymous profiles.
+ /// Use this to determine which collections need syncing.
+ Future<LatestUpdatesResponse> fetchLatestUpdates() async {
+ try {
+ final response = await _enteDio.get('/comments-reactions/updated-at');
+ return LatestUpdatesResponse.fromJson(
+ response.data as Map<String, dynamic>,
+ );
+ } on DioException catch (e) {
+ _logger.severe('Failed to fetch latest updates', e);
+ rethrow;
+ }
+ }
+
+ /// Fetches anonymous profiles for a collection.
+ ///
+ /// Returns encrypted profile data that needs to be decrypted with the collection key.
+ Future<AnonProfilesResponse> fetchAnonProfiles(int collectionID) async {
+ try {
+ final response = await _enteDio.get(
+ '/social/anon-profiles',
+ queryParameters: {'collectionID': collectionID},
+ );
+ return AnonProfilesResponse.fromJson(
+ response.data as Map<String, dynamic>,
+ );
+ } on DioException catch (e) {
+ _logger.severe(
+ 'Failed to fetch anon profiles for collection $collectionID',
+ e,
+ );
+ rethrow;
+ }
+ }
+
+ // ============ Unified/Social API ============
+
+ /// Fetches both comments and reactions in a single call.
+ ///
+ /// [collectionID] - The collection to fetch social data from
+ /// [commentsSinceTime] - Only fetch comments updated after this timestamp
+ /// [reactionsSinceTime] - Only fetch reactions updated after this timestamp
+ /// [limit] - Maximum number of items per type (default 1000, max 2000)
+ /// [fileID] - Optional filter for items on a specific file
+ ///
+ /// Returns [SocialDiffResponse] with comments, reactions, and hasMore flags
+ Future<SocialDiffResponse> fetchSocialDiff({
+ required int collectionID,
+ int? commentsSinceTime,
+ int? reactionsSinceTime,
+ int? limit,
+ int? fileID,
+ }) async {
+ final queryParams = <String, dynamic>{
+ 'collectionID': collectionID,
+ };
+
+ if (commentsSinceTime != null) {
+ queryParams['commentsSinceTime'] = commentsSinceTime;
+ }
+ if (reactionsSinceTime != null) {
+ queryParams['reactionsSinceTime'] = reactionsSinceTime;
+ }
+ if (limit != null) {
+ queryParams['limit'] = limit;
+ }
+ if (fileID != null) {
+ queryParams['fileID'] = fileID;
+ }
+
+ try {
+ final response = await _enteDio.get(
+ '/social/diff',
+ queryParameters: queryParams,
+ );
+ return SocialDiffResponse.fromJson(
+ response.data as Map<String, dynamic>,
+ );
+ } on DioException catch (e) {
+ _logger.severe(
+ 'Failed to fetch social diff for collection $collectionID',
+ e,
+ );
+ rethrow;
+ }
+ }
+
+ /// Fetches comment and reaction counts for all collections.
+ ///
+ /// Returns a map of collectionID -> count
+ Future<Map<int, int>> fetchCounts() async {
+ try {
+ final response = await _enteDio.get('/comments-reactions/counts');
+ final countsData = response.data['counts'] as Map<String, dynamic>?;
+ if (countsData == null) {
+ return {};
+ }
+ return countsData.map(
+ (key, value) => MapEntry(int.parse(key), value as int),
+ );
+ } on DioException catch (e) {
+ _logger.severe('Failed to fetch counts', e);
+ rethrow;
+ }
+ }
+
+ // ============ Encryption/Decryption ============
+
+ /// Encrypts comment text with the collection key.
+ ///
+ /// Returns a record of (cipher, nonce) as base64 strings.
+ ({String cipher, String nonce}) encryptComment(
+ String text,
+ int collectionID,
+ ) {
+ final collectionKey =
+ CollectionsService.instance.getCollectionKey(collectionID);
+ final textBytes = utf8.encode(text);
+
+ final encrypted = CryptoUtil.encryptSync(
+ Uint8List.fromList(textBytes),
+ collectionKey,
+ );
+
+ return (
+ cipher: CryptoUtil.bin2base64(encrypted.encryptedData!),
+ nonce: CryptoUtil.bin2base64(encrypted.nonce!),
+ );
+ }
+
+ /// Decrypts comment cipher to plaintext.
+ ///
+ /// Returns the decrypted text, or empty string if decryption fails.
+ String decryptComment(String? cipher, String? nonce, int collectionID) {
+ if (cipher == null || nonce == null || cipher.isEmpty || nonce.isEmpty) {
+ return '';
+ }
+
+ try {
+ final collectionKey =
+ CollectionsService.instance.getCollectionKey(collectionID);
+ final cipherBytes = CryptoUtil.base642bin(cipher);
+ final nonceBytes = CryptoUtil.base642bin(nonce);
+
+ final decrypted = CryptoUtil.decryptSync(
+ cipherBytes,
+ collectionKey,
+ nonceBytes,
+ );
+
+ return utf8.decode(decrypted);
+ } catch (e) {
+ _logger.warning('Failed to decrypt comment', e);
+ return '';
+ }
+ }
+
+ /// Encrypts reaction type with the collection key.
+ ///
+ /// The reaction type is padded to fixed length before encryption,
+ /// ensuring consistent ciphertext length.
+ ({String cipher, String nonce}) encryptReaction(
+ String reactionType,
+ int collectionID,
+ ) {
+ final collectionKey =
+ CollectionsService.instance.getCollectionKey(collectionID);
+
+ // Pad reaction type to fixed length
+ final padded = _padReactionType(reactionType);
+ final paddedBytes = utf8.encode(padded);
+
+ final encrypted = CryptoUtil.encryptSync(
+ Uint8List.fromList(paddedBytes),
+ collectionKey,
+ );
+
+ return (
+ cipher: CryptoUtil.bin2base64(encrypted.encryptedData!),
+ nonce: CryptoUtil.bin2base64(encrypted.nonce!),
+ );
+ }
+
+ /// Decrypts reaction cipher to reaction type.
+ ///
+ /// Returns the decrypted reaction type (with padding removed),
+ /// or empty string if decryption fails.
+ String decryptReaction(String? cipher, String? nonce, int collectionID) {
+ if (cipher == null || nonce == null || cipher.isEmpty || nonce.isEmpty) {
+ return '';
+ }
+
+ try {
+ final collectionKey =
+ CollectionsService.instance.getCollectionKey(collectionID);
+ final cipherBytes = CryptoUtil.base642bin(cipher);
+ final nonceBytes = CryptoUtil.base642bin(nonce);
+
+ final decrypted = CryptoUtil.decryptSync(
+ cipherBytes,
+ collectionKey,
+ nonceBytes,
+ );
+
+ // Remove null byte padding
+ final decoded = utf8.decode(decrypted);
+ return _unpadReactionType(decoded);
+ } catch (e) {
+ _logger.warning('Failed to decrypt reaction', e);
+ return '';
+ }
+ }
+
+ /// Pads a reaction type to fixed length with null bytes.
+ String _padReactionType(String reactionType) {
+ if (reactionType.length >= _reactionPadLength) {
+ return reactionType.substring(0, _reactionPadLength);
+ }
+ return reactionType.padRight(_reactionPadLength, '\x00');
+ }
+
+ /// Removes null byte padding from reaction type.
+ String _unpadReactionType(String padded) {
+ final nullIndex = padded.indexOf('\x00');
+ if (nullIndex == -1) {
+ return padded;
+ }
+ return padded.substring(0, nullIndex);
+ }
+
+ /// Decrypts anonymous profile name.
+ ///
+ /// Returns the decrypted display name, or empty string if decryption fails.
+ String decryptAnonProfile(String? cipher, String? nonce, int collectionID) {
+ if (cipher == null || nonce == null || cipher.isEmpty || nonce.isEmpty) {
+ return '';
+ }
+
+ try {
+ final collectionKey =
+ CollectionsService.instance.getCollectionKey(collectionID);
+ final cipherBytes = CryptoUtil.base642bin(cipher);
+ final nonceBytes = CryptoUtil.base642bin(nonce);
+
+ final decrypted = CryptoUtil.decryptSync(
+ cipherBytes,
+ collectionKey,
+ nonceBytes,
+ );
+
+ return utf8.decode(decrypted);
+ } catch (e) {
+ _logger.warning('Failed to decrypt anon profile', e);
+ return '';
+ }
+ }
+}
diff --git a/mobile/apps/photos/lib/services/social_sync_service.dart b/mobile/apps/photos/lib/services/social_sync_service.dart
new file mode 100644
index 0000000000..cdd1c782a8
--- /dev/null
+++ b/mobile/apps/photos/lib/services/social_sync_service.dart
@@ -0,0 +1,345 @@
+import 'package:logging/logging.dart';
+import 'package:photos/core/configuration.dart';
+import 'package:photos/db/social_db.dart';
+import 'package:photos/models/social/anon_profile.dart';
+import 'package:photos/models/social/api_responses.dart';
+import 'package:photos/models/social/comment.dart';
+import 'package:photos/models/social/reaction.dart';
+import 'package:photos/services/social_service.dart';
+
+/// Service for syncing social data (comments and reactions) with the server.
+///
+/// Handles diff-based sync, encryption/decryption, and local storage.
+class SocialSyncService {
+ SocialSyncService._();
+ static final instance = SocialSyncService._();
+
+ final _logger = Logger('SocialSyncService');
+ final _db = SocialDB.instance;
+ final _api = SocialService.instance;
+
+ bool _isSyncing = false;
+
+ /// Syncs social data for a single collection.
+ ///
+ /// Uses diff-based sync with separate sinceTime for comments and reactions.
+ Future<void> syncCollection(int collectionID) async {
+ int commentsSinceTime = await _db.getCommentsSyncTime(collectionID);
+ int reactionsSinceTime = await _db.getReactionsSyncTime(collectionID);
+
+ int maxCommentsUpdatedAt = commentsSinceTime;
+ int maxReactionsUpdatedAt = reactionsSinceTime;
+
+ try {
+ bool hasMoreComments = true;
+ bool hasMoreReactions = true;
+
+ // Sync using unified endpoint with separate since times
+ while (hasMoreComments || hasMoreReactions) {
+ final response = await _api.fetchSocialDiff(
+ collectionID: collectionID,
+ commentsSinceTime: commentsSinceTime,
+ reactionsSinceTime: reactionsSinceTime,
+ );
+
+ // Process comments
+ if (response.comments.isNotEmpty) {
+ final comments = _decryptComments(response.comments, collectionID);
+ await _db.upsertComments(comments);
+
+ for (final comment in response.comments) {
+ if (comment.updatedAt > maxCommentsUpdatedAt) {
+ maxCommentsUpdatedAt = comment.updatedAt;
+ }
+ }
+ }
+
+ // Process reactions
+ if (response.reactions.isNotEmpty) {
+ final reactions = _decryptReactions(response.reactions, collectionID);
+ await _db.upsertReactions(reactions);
+
+ for (final reaction in response.reactions) {
+ if (reaction.updatedAt > maxReactionsUpdatedAt) {
+ maxReactionsUpdatedAt = reaction.updatedAt;
+ }
+ }
+ }
+
+ hasMoreComments = response.hasMoreComments;
+ hasMoreReactions = response.hasMoreReactions;
+
+ if (!hasMoreComments && !hasMoreReactions) {
+ break;
+ }
+
+ // Update since times for pagination
+ commentsSinceTime = maxCommentsUpdatedAt;
+ reactionsSinceTime = maxReactionsUpdatedAt;
+ }
+
+ // Update sync times
+ if (maxCommentsUpdatedAt > await _db.getCommentsSyncTime(collectionID)) {
+ await _db.setCommentsSyncTime(collectionID, maxCommentsUpdatedAt);
+ }
+ if (maxReactionsUpdatedAt >
+ await _db.getReactionsSyncTime(collectionID)) {
+ await _db.setReactionsSyncTime(collectionID, maxReactionsUpdatedAt);
+ }
+ } catch (e) {
+ _logger.severe('Failed to sync collection $collectionID', e);
+ rethrow;
+ }
+ }
+
+ /// Syncs reactions for a specific file in a collection.
+ ///
+ /// Useful for on-demand sync when viewing a file.
+ Future<void> syncFileReactions(int collectionID, int fileID) async {
+ try {
+ final response = await _api.fetchReactionsDiff(
+ collectionID: collectionID,
+ fileID: fileID,
+ sinceTime: 0, // Always get all reactions for the file
+ );
+
+ if (response.reactions.isNotEmpty) {
+ final reactions = _decryptReactions(response.reactions, collectionID);
+ await _db.upsertReactions(reactions);
+ }
+ } catch (e) {
+ _logger.warning('Failed to sync reactions for file $fileID', e);
+ // Don't rethrow - this is a non-critical operation
+ }
+ }
+
+ /// Syncs both comments and reactions for a specific file in a collection.
+ ///
+ /// Useful for on-demand sync when opening comments screen.
+ Future<void> syncFileSocialData(int collectionID, int fileID) async {
+ try {
+ final response = await _api.fetchSocialDiff(
+ collectionID: collectionID,
+ fileID: fileID,
+ // Always get all data for the file (no sinceTime = fetch all)
+ );
+
+ if (response.comments.isNotEmpty) {
+ final comments = _decryptComments(response.comments, collectionID);
+ await _db.upsertComments(comments);
+ }
+
+ if (response.reactions.isNotEmpty) {
+ final reactions = _decryptReactions(response.reactions, collectionID);
+ await _db.upsertReactions(reactions);
+ }
+ } catch (e) {
+ _logger.warning('Failed to sync reactions for file $fileID', e);
+ // Don't rethrow - this is a non-critical operation
+ }
+ }
+
+ /// Syncs social data for all collections that have new updates.
+ ///
+ /// Called during background sync to keep social data up to date.
+ /// Uses the /comments-reactions/updated-at endpoint to determine which
+ /// collections actually need syncing, avoiding unnecessary API calls.
+ Future<void> syncAllSharedCollections() async {
+ if (_isSyncing) {
+ _logger.info('Sync already in progress, skipping');
+ return;
+ }
+
+ _isSyncing = true;
+ try {
+ final userID = Configuration.instance.getUserID();
+ if (userID == null) {
+ _logger.info('User not logged in, skipping social sync');
+ return;
+ }
+
+ // Get latest update timestamps from server
+ final latestUpdates = await _api.fetchLatestUpdates();
+
+ if (latestUpdates.updates.isEmpty) {
+ _logger.info('No collections have social activity');
+ return;
+ }
+
+ _logger.info(
+ 'Checking ${latestUpdates.updates.length} collections for social updates',
+ );
+
+ int syncedCount = 0;
+ for (final update in latestUpdates.updates) {
+ try {
+ final needsSync = await _needsSync(update);
+ if (needsSync) {
+ await syncCollection(update.collectionID);
+ syncedCount++;
+ }
+
+ // Sync anon profiles if needed
+ if (update.anonProfilesUpdatedAt != null) {
+ final localAnonSyncTime =
+ await _db.getAnonProfilesSyncTime(update.collectionID);
+ if (update.anonProfilesUpdatedAt! > localAnonSyncTime) {
+ await syncAnonProfiles(update.collectionID);
+ }
+ }
+ } catch (e) {
+ _logger.warning(
+ 'Failed to sync collection ${update.collectionID}, continuing',
+ e,
+ );
+ }
+ }
+
+ _logger.info('Synced $syncedCount collections with new updates');
+ } catch (e) {
+ _logger.severe('Failed to fetch latest updates', e);
+ } finally {
+ _isSyncing = false;
+ }
+ }
+
+ /// Checks if a collection needs syncing based on server vs local timestamps.
+ Future<bool> _needsSync(CollectionLatestUpdate update) async {
+ final localCommentsSyncTime =
+ await _db.getCommentsSyncTime(update.collectionID);
+ final localReactionsSyncTime =
+ await _db.getReactionsSyncTime(update.collectionID);
+
+ // Check if comments need sync
+ if (update.commentsUpdatedAt != null &&
+ update.commentsUpdatedAt! > localCommentsSyncTime) {
+ return true;
+ }
+
+ // Check if reactions need sync
+ if (update.reactionsUpdatedAt != null &&
+ update.reactionsUpdatedAt! > localReactionsSyncTime) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /// Syncs anonymous profiles for a collection.
+ Future<void> syncAnonProfiles(int collectionID) async {
+ try {
+ final response = await _api.fetchAnonProfiles(collectionID);
+
+ if (response.profiles.isEmpty) {
+ return;
+ }
+
+ int maxUpdatedAt = 0;
+ final profiles = <AnonProfile>[];
+
+ for (final apiProfile in response.profiles) {
+ final displayName = _api.decryptAnonProfile(
+ apiProfile.cipher,
+ apiProfile.nonce,
+ collectionID,
+ );
+
+ profiles.add(
+ AnonProfile(
+ anonUserID: apiProfile.anonUserID,
+ collectionID: apiProfile.collectionID,
+ displayName: displayName,
+ createdAt: apiProfile.createdAt,
+ updatedAt: apiProfile.updatedAt,
+ ),
+ );
+
+ if (apiProfile.updatedAt > maxUpdatedAt) {
+ maxUpdatedAt = apiProfile.updatedAt;
+ }
+ }
+
+ await _db.upsertAnonProfiles(profiles);
+
+ if (maxUpdatedAt > 0) {
+ await _db.setAnonProfilesSyncTime(collectionID, maxUpdatedAt);
+ }
+
+ _logger.info(
+ 'Synced ${profiles.length} anon profiles for collection $collectionID',
+ );
+ } catch (e) {
+ _logger.warning(
+ 'Failed to sync anon profiles for collection $collectionID',
+ e,
+ );
+ }
+ }
+
+ /// Decrypts API comment responses to local Comment models.
+ List<Comment> _decryptComments(
+ List<CommentApiResponse> apiComments,
+ int collectionID,
+ ) {
+ final comments = <Comment>[];
+ for (final apiComment in apiComments) {
+ final decryptedText = apiComment.isDeleted
+ ? ''
+ : _api.decryptComment(
+ apiComment.cipher,
+ apiComment.nonce,
+ collectionID,
+ );
+
+ comments.add(
+ Comment(
+ id: apiComment.id,
+ collectionID: apiComment.collectionID,
+ fileID: apiComment.fileID,
+ data: decryptedText,
+ parentCommentID: apiComment.parentCommentID,
+ parentCommentUserID: apiComment.parentCommentUserID,
+ isDeleted: apiComment.isDeleted,
+ userID: apiComment.userID,
+ anonUserID: apiComment.anonUserID,
+ createdAt: apiComment.createdAt,
+ updatedAt: apiComment.updatedAt,
+ ),
+ );
+ }
+ return comments;
+ }
+
+ /// Decrypts API reaction responses to local Reaction models.
+ List<Reaction> _decryptReactions(
+ List<ReactionApiResponse> apiReactions,
+ int collectionID,
+ ) {
+ final reactions = <Reaction>[];
+ for (final apiReaction in apiReactions) {
+ final decryptedType = apiReaction.isDeleted
+ ? ''
+ : _api.decryptReaction(
+ apiReaction.cipher,
+ apiReaction.nonce,
+ collectionID,
+ );
+
+ reactions.add(
+ Reaction(
+ id: apiReaction.id,
+ collectionID: apiReaction.collectionID,
+ fileID: apiReaction.fileID,
+ commentID: apiReaction.commentID,
+ data: decryptedType,
+ isDeleted: apiReaction.isDeleted,
+ userID: apiReaction.userID,
+ anonUserID: apiReaction.anonUserID,
+ createdAt: apiReaction.createdAt,
+ updatedAt: apiReaction.updatedAt,
+ ),
+ );
+ }
+ return reactions;
+ }
+}
diff --git a/mobile/apps/photos/lib/services/sync/sync_service.dart b/mobile/apps/photos/lib/services/sync/sync_service.dart
index a57e188283..61de98cb2a 100644
--- a/mobile/apps/photos/lib/services/sync/sync_service.dart
+++ b/mobile/apps/photos/lib/services/sync/sync_service.dart
@@ -17,6 +17,7 @@ import 'package:photos/models/file/file_type.dart';
import "package:photos/service_locator.dart";
import "package:photos/services/language_service.dart";
import 'package:photos/services/notification_service.dart';
+import 'package:photos/services/social_sync_service.dart';
import 'package:photos/services/sync/local_sync_service.dart';
import 'package:photos/services/sync/remote_sync_service.dart';
import 'package:photos/utils/file_uploader.dart';
@@ -213,6 +214,14 @@ class SyncService {
if (!isProcessBg) {
await smartAlbumsService.syncSmartAlbums();
}
+
+ // Sync social data for shared collections
+ try {
+ _logger.info("[SYNC] Starting social sync");
+ await SocialSyncService.instance.syncAllSharedCollections();
+ } catch (e) {
+ _logger.warning("[SYNC] Social sync failed, continuing", e);
+ }
} else {
_logger.info("[SYNC] First import not completed, skipping remote");
}
diff --git a/mobile/apps/photos/lib/ui/social/comments_screen.dart b/mobile/apps/photos/lib/ui/social/comments_screen.dart
index 8447eeb6c1..91a93152be 100644
--- a/mobile/apps/photos/lib/ui/social/comments_screen.dart
+++ b/mobile/apps/photos/lib/ui/social/comments_screen.dart
@@ -17,7 +17,6 @@ import "package:photos/ui/components/buttons/icon_button_widget.dart";
import "package:photos/ui/social/widgets/collection_selector_widget.dart";
import "package:photos/ui/social/widgets/comment_bubble_widget.dart";
import "package:photos/ui/social/widgets/comment_input_widget.dart";
-import "package:uuid/uuid.dart";
class FileCommentsScreen extends StatefulWidget {
final int collectionID;
@@ -131,6 +130,7 @@ class _FileCommentsScreenState extends State<FileCommentsScreen> {
Future<void> _loadInitialComments() async {
setState(() => _isLoading = true);
+ // Load local data first for immediate display
final comments =
await SocialDataProvider.instance.getCommentsForFilePaginated(
widget.fileID,
@@ -145,6 +145,40 @@ class _FileCommentsScreenState extends State<FileCommentsScreen> {
_hasMoreComments = comments.length == _pageSize;
_isLoading = false;
});
+
+ // Sync in background and refresh if there are changes
+ unawaited(_syncAndRefresh());
+ }
+
+ Future<void> _syncAndRefresh() async {
+ try {
+ await SocialDataProvider.instance.syncFileSocialData(
+ _selectedCollectionID,
+ widget.fileID,
+ );
+
+ if (!mounted) return;
+
+ // Reload comments after sync
+ final freshComments =
+ await SocialDataProvider.instance.getCommentsForFilePaginated(
+ widget.fileID,
+ collectionID: _selectedCollectionID,
+ limit: _pageSize,
+ offset: 0,
+ );
+
+ if (mounted) {
+ setState(() {
+ _comments.clear();
+ _comments.addAll(freshComments);
+ _offset = freshComments.length;
+ _hasMoreComments = freshComments.length == _pageSize;
+ });
+ }
+ } catch (_) {
+ // Ignore sync errors, local data is already displayed
+ }
}
Future<void> _loadMoreComments() async {
@@ -228,20 +262,13 @@ class _FileCommentsScreenState extends State<FileCommentsScreen> {
final text = _textController.text.trim();
if (text.isEmpty) return;
- final now = DateTime.now().millisecondsSinceEpoch;
- final newComment = Comment(
- id: const Uuid().v4(),
+ // Call API to create comment
+ final result = await SocialDataProvider.instance.addComment(
collectionID: _selectedCollectionID,
+ text: text,
fileID: widget.fileID,
- data: text,
parentCommentID: _replyingTo?.id,
- userID: _currentUserID,
- createdAt: now,
- updatedAt: now,
);
-
- // Persist first
- final result = await SocialDataProvider.instance.addComment(newComment);
if (result == null) {
_logger.warning('Failed to save comment');
return;
@@ -250,7 +277,7 @@ class _FileCommentsScreenState extends State<FileCommentsScreen> {
// Update UI only after successful persistence
if (mounted) {
setState(() {
- _comments.insert(0, newComment);
+ _comments.insert(0, result);
_replyingTo = null;
// Update comment count in shared collections list
diff --git a/mobile/apps/photos/lib/ui/social/likes_bottom_sheet.dart b/mobile/apps/photos/lib/ui/social/likes_bottom_sheet.dart
index 2ee8474477..145d4cdd13 100644
--- a/mobile/apps/photos/lib/ui/social/likes_bottom_sheet.dart
+++ b/mobile/apps/photos/lib/ui/social/likes_bottom_sheet.dart
@@ -132,6 +132,12 @@ class _LikesBottomSheetState extends State<LikesBottomSheet> {
setState(() => _isLoading = true);
try {
+ // Sync reactions from server before loading locally
+ await SocialDataProvider.instance.syncFileReactions(
+ _selectedCollectionID,
+ widget.fileID,
+ );
+
final likes =
await SocialDataProvider.instance.getReactionsForFileInCollection(
widget.fileID,
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.dart
index b205ef4ee7..5918ba6b89 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
@@ -90,7 +90,7 @@ class FileBottomBarState extends State<FileBottomBar> {
}
}
- Future<void> _updateSocialState() async {
+ Future<void> _updateSocialState({bool sync = false}) async {
if (widget.file.uploadedFileID == null) {
_hasLiked = false;
_commentCount = 0;
@@ -98,8 +98,18 @@ class FileBottomBarState extends State<FileBottomBar> {
}
final fileID = widget.file.uploadedFileID!;
+ final collectionID = widget.file.collectionID;
final provider = SocialDataProvider.instance;
+ // Sync from server if requested and we have a collection ID
+ if (sync && collectionID != null) {
+ try {
+ await provider.syncFileReactions(collectionID, fileID);
+ } catch (_) {
+ // Ignore sync errors, continue with local data
+ }
+ }
+
// Check if user has liked
final reactions = await provider.getReactionsForFile(fileID);
_hasLiked = reactions.any(
diff --git a/mobile/apps/photos/lib/utils/social/relative_time_formatter.dart b/mobile/apps/photos/lib/utils/social/relative_time_formatter.dart
index 1aa9b06d05..393656a72e 100644
--- a/mobile/apps/photos/lib/utils/social/relative_time_formatter.dart
+++ b/mobile/apps/photos/lib/utils/social/relative_time_formatter.dart
@@ -1,8 +1,12 @@
import "package:intl/intl.dart";
-String formatRelativeTime(int timestampMillis) {
+/// Formats a timestamp (in microseconds) to a relative time string.
+///
+/// Server timestamps are in microseconds since epoch.
+String formatRelativeTime(int timestampMicros) {
final now = DateTime.now();
- final dateTime = DateTime.fromMillisecondsSinceEpoch(timestampMillis);
+ final dateTime =
+ DateTime.fromMicrosecondsSinceEpoch(timestampMicros);
final difference = now.difference(dateTime);
if (difference.inMinutes < 1) {