π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Revamp social notifications
Anand Baburajand59c878b2367
diff --git a/rust/wall/src/lib.rs b/rust/wall/src/lib.rsindex 5ca852727c..86f10fc89e 100644--- a/rust/wall/src/lib.rs+++ b/rust/wall/src/lib.rs@@ -13,11 +13,11 @@ pub use models::{};pub use transport::{EntityKeyPayload, FriendRelationshipResponse, FriendShareResponse, FriendStatusResponse,- LikeMessageResponse, LikePostResponse, ListPostLikersResponse, MessageConversationPage,- MessageConversationResponse, MessagePage, MessageResponse, PostLikerResponse,- PostObjectPayload, PostPage, PostResponse, PresignUploadResponse, ProfileAvatarPayload,- ProfileAvatarResponse, WallActorResponse, WallFriendResponse, WallKeyResponse,- WallKeyVersionResponse, WallLinkLoginResponse, WallLinkStatusResponse, WallLookupResponse,- WallNotification, WallNotificationPage, WallNotificationPost, WallNotificationType,- WallProfileResponse,+ LikeMessageResponse, LikePostResponse, ListPostLikersResponse, MessageConversationActivity,+ MessageConversationPage, MessageConversationPost, MessageConversationResponse, MessagePage,+ MessageResponse, PostLikerResponse, PostObjectPayload, PostPage, PostResponse,+ PresignUploadResponse, ProfileAvatarPayload, ProfileAvatarResponse, WallActorResponse,+ WallFriendResponse, WallKeyResponse, WallKeyVersionResponse, WallLinkLoginResponse,+ WallLinkStatusResponse, WallLookupResponse, WallNotification, WallNotificationPage,+ WallNotificationPost, WallNotificationType, WallProfileResponse,};diff --git a/rust/wall/src/transport.rs b/rust/wall/src/transport.rsindex 2b1acfe82e..86a5f425ab 100644--- a/rust/wall/src/transport.rs+++ b/rust/wall/src/transport.rs@@ -188,7 +188,32 @@ pub struct MessagePage {#[serde(rename_all = "camelCase")]pub struct MessageConversationResponse {pub friend: WallActorResponse,- pub last_message: MessageResponse,+ pub latest_activity: MessageConversationActivity,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct MessageConversationActivity {+ pub id: String,+ #[serde(rename = "type")]+ pub activity_type: String,+ pub created_at: String,+ #[serde(default)]+ pub message: Option<MessageResponse>,+ #[serde(default)]+ pub post: Option<MessageConversationPost>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct MessageConversationPost {+ pub post_id: i64,+ pub wall_id: String,+ pub wall_slug: String,+ #[serde(default)]+ pub owner_user_id: i64,+ #[serde(default)]+ pub objects: Vec<PostObjectPayload>,}#[derive(Debug, Clone, Serialize, Deserialize)]diff --git a/server/wall/controller/messages.go b/server/wall/controller/messages.goindex 844f351bc8..7da39e9047 100644--- a/server/wall/controller/messages.go+++ b/server/wall/controller/messages.go@@ -123,8 +123,8 @@ func (c *MessagesController) List(ctx *gin.Context, req models.ListMessagesRequeitems := make([]models.MessageConversationResponse, 0, len(conversations))for _, conversation := range conversations {items = append(items, models.MessageConversationResponse{- Friend: toActorResponse(conversation.Friend, true),- LastMessage: *toMessageResponse(conversation.LastMessage),+ Friend: toActorResponse(conversation.Friend, true),+ LatestActivity: toMessageConversationActivityResponse(conversation.LatestActivity),})}return &models.MessageConversationPage{Items: items, NextCursor: nextCursor}, nil@@ -281,3 +281,38 @@ func toMessageResponse(message repo.WallMessageRecord) *models.MessageResponse {}return resp}++func toMessageConversationActivityResponse(activity repo.WallMessageConversationActivityRecord) models.MessageConversationActivityResponse {+ resp := models.MessageConversationActivityResponse{+ ID: activity.ID,+ Type: activity.Type,+ CreatedAt: formatMicros(activity.CreatedAt),+ }+ if activity.Message != nil {+ resp.Message = toMessageResponse(*activity.Message)+ }+ if activity.Post != nil {+ resp.Post = &models.MessageConversationPostResponse{+ PostID: activity.Post.PostID,+ WallID: activity.Post.WallID,+ WallSlug: activity.Post.WallSlug,+ OwnerUserID: activity.Post.OwnerID,+ }+ if activity.Post.ObjectKey.Valid {+ resp.Post.Objects = []models.PostObjectPayload{+ toPostObjectPayload(repo.WallPostAssetRecord{+ PostID: activity.Post.PostID,+ ObjectKey: activity.Post.ObjectKey.String,+ Size: activity.Post.ObjectSize,+ Position: int(activity.Post.ObjectPosition.Int64),+ Variant: activity.Post.ObjectVariant,+ BlurHashCipher: activity.Post.ObjectBlurHashCipher,+ Width: activity.Post.ObjectWidth,+ Height: activity.Post.ObjectHeight,+ MediaType: activity.Post.ObjectMediaType,+ }),+ }+ }+ }+ return resp+}diff --git a/server/wall/models/models.go b/server/wall/models/models.goindex 50285fd692..310be92026 100644--- a/server/wall/models/models.go+++ b/server/wall/models/models.go@@ -306,8 +306,24 @@ type MessagePage struct {}type MessageConversationResponse struct {- Friend WallActorResponse `json:"friend"`- LastMessage MessageResponse `json:"lastMessage"`+ Friend WallActorResponse `json:"friend"`+ LatestActivity MessageConversationActivityResponse `json:"latestActivity"`+}++type MessageConversationActivityResponse struct {+ ID string `json:"id"`+ Type string `json:"type"`+ CreatedAt string `json:"createdAt"`+ Message *MessageResponse `json:"message,omitempty"`+ Post *MessageConversationPostResponse `json:"post,omitempty"`+}++type MessageConversationPostResponse struct {+ PostID int64 `json:"postId"`+ WallID string `json:"wallId"`+ WallSlug string `json:"wallSlug"`+ OwnerUserID int64 `json:"ownerUserId"`+ Objects []PostObjectPayload `json:"objects,omitempty"`}type MessageConversationPage struct {diff --git a/server/wall/repo/messages.go b/server/wall/repo/messages.goindex 6307ae8cb3..31e52ba0cb 100644--- a/server/wall/repo/messages.go+++ b/server/wall/repo/messages.go@@ -198,23 +198,202 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID intcursorID = id}rows, err := r.DB.QueryContext(ctx, `- WITH ranked AS (+ WITH message_candidates AS (SELECT- m.*,- ROW_NUMBER() OVER (- PARTITION BY CASE WHEN m.sender_id = $1 THEN m.recipient_wall_id ELSE m.sender_wall_id END- ORDER BY m.created_at DESC, m.message_id DESC- ) AS rn+ 'message' AS activity_type,+ 'message:' || m.message_id AS activity_id,+ m.created_at AS activity_created_at,+ CASE WHEN m.sender_id = $1 THEN m.recipient_wall_id ELSE m.sender_wall_id END AS friend_wall_id,+ m.message_id,+ NULL::bigint AS post_idFROM wall_messages mWHERE (m.sender_id = $1 OR m.recipient_id = $1)AND m.is_deleted = FALSE+ AND NOT (m.kind = 'post_reply' AND m.recipient_id = $1)++ UNION ALL++ SELECT+ 'message_like' AS activity_type,+ 'message_like:' || ml.message_id || ':' || ml.user_id::text AS activity_id,+ ml.created_at AS activity_created_at,+ liker_wall.wall_id AS friend_wall_id,+ m.message_id,+ NULL::bigint AS post_id+ FROM wall_message_likes ml+ JOIN wall_messages m ON m.message_id = ml.message_id+ JOIN walls liker_wall ON liker_wall.owner_id = ml.user_id+ WHERE m.sender_id = $1+ AND m.recipient_id = ml.user_id+ AND ml.user_id <> $1+ AND m.is_deleted = FALSE+ ),+ post_like_events AS (+ SELECT+ actor_wall.wall_id AS friend_wall_id,+ p.post_id,+ MAX(pl.created_at) AS liked_at+ FROM wall_post_likes pl+ JOIN wall_posts p ON p.post_id = pl.post_id+ JOIN walls actor_wall ON actor_wall.owner_id = pl.user_id+ WHERE p.owner_id = $1+ AND pl.user_id <> $1+ AND p.is_deleted = FALSE+ GROUP BY actor_wall.wall_id, p.post_id+ ),+ post_reply_events AS (+ SELECT DISTINCT ON (m.sender_wall_id, m.reply_post_id)+ m.sender_wall_id AS friend_wall_id,+ m.reply_post_id AS post_id,+ m.message_id,+ m.created_at AS replied_at+ FROM wall_messages m+ JOIN wall_posts p ON p.post_id = m.reply_post_id+ WHERE m.recipient_id = $1+ AND m.sender_id <> $1+ AND m.kind = 'post_reply'+ AND m.is_deleted = FALSE+ AND m.reply_post_id IS NOT NULL+ AND p.owner_id = $1+ AND p.is_deleted = FALSE+ ORDER BY m.sender_wall_id, m.reply_post_id, m.created_at DESC, m.message_id DESC+ ),+ post_candidates AS (+ SELECT+ CASE+ WHEN l.liked_at IS NOT NULL AND r.replied_at IS NOT NULL THEN 'post_like_and_reply'+ WHEN r.replied_at IS NOT NULL THEN 'post_reply'+ ELSE 'post_like'+ END AS activity_type,+ 'post_activity:' || COALESCE(l.post_id, r.post_id)::text || ':' || COALESCE(l.friend_wall_id, r.friend_wall_id) AS activity_id,+ GREATEST(COALESCE(l.liked_at, 0), COALESCE(r.replied_at, 0)) AS activity_created_at,+ COALESCE(l.friend_wall_id, r.friend_wall_id) AS friend_wall_id,+ r.message_id,+ COALESCE(l.post_id, r.post_id) AS post_id+ FROM post_like_events l+ FULL OUTER JOIN post_reply_events r+ ON r.friend_wall_id = l.friend_wall_id+ AND r.post_id = l.post_id+ ),+ friend_candidates AS (+ SELECT+ CASE fe.event_type+ WHEN 'friend_remove' THEN 'friend_remove'+ ELSE 'friend_add'+ END AS activity_type,+ 'friend_event:' || fe.event_id::text AS activity_id,+ fe.created_at AS activity_created_at,+ fe.actor_wall_id AS friend_wall_id,+ NULL::text AS message_id,+ NULL::bigint AS post_id+ FROM wall_friend_events fe+ WHERE fe.target_id = $1+ AND fe.actor_id <> $1+ ),+ candidates AS (+ SELECT * FROM message_candidates+ UNION ALL+ SELECT * FROM post_candidates+ UNION ALL+ SELECT * FROM friend_candidates+ ),+ ranked AS (+ SELECT+ c.*,+ ROW_NUMBER() OVER (+ PARTITION BY c.friend_wall_id+ ORDER BY c.activity_created_at DESC, c.activity_id DESC+ ) AS rn+ FROM candidates c)- SELECT `+sprintfWallMessageColumns("$1")+`- FROM ranked m- `+wallMessageJoins+`- WHERE m.rn = 1- AND ($2::bigint IS NULL OR (m.created_at, m.message_id) < ($2::bigint, $3::text))- ORDER BY m.created_at DESC, m.message_id DESC+ SELECT+ c.activity_type,+ c.activity_id,+ c.activity_created_at,+ friend_wall.owner_id,+ friend_wall.wall_id,+ friend_wall.wall_slug,+ friend_ka.public_key,+ friend_wall.current_version,+ friend_wall.encrypted_profile,+ friend_wall.avatar_object_key,+ friend_wall.avatar_size,+ friend_wall.updated_at,+ (SELECT COUNT(*) FROM wall_friend_shares fs WHERE fs.wall_id = friend_wall.wall_id) AS friend_friends,+ (SELECT COUNT(*) FROM wall_posts fp WHERE fp.wall_id = friend_wall.wall_id AND fp.is_deleted = FALSE) AS friend_posts,+ COALESCE(m.message_id, '') AS message_id,+ COALESCE(m.kind, '') AS kind,+ COALESCE(m.sender_id, 0) AS sender_id,+ COALESCE(m.sender_wall_id, '') AS sender_wall_id,+ COALESCE(m.recipient_id, 0) AS recipient_id,+ COALESCE(m.recipient_wall_id, '') AS recipient_wall_id,+ COALESCE(m.message_cipher, '') AS message_cipher,+ CASE+ WHEN m.message_id IS NULL THEN ''+ WHEN m.sender_id = $1 THEN COALESCE(m.sender_encrypted_message_key, '')+ ELSE COALESCE(m.recipient_encrypted_message_key, '')+ END AS encrypted_message_key,+ m.reply_post_id,+ m.reply_message_id,+ COALESCE((SELECT COUNT(*) FROM wall_message_likes ml WHERE ml.message_id = m.message_id), 0) AS likes,+ COALESCE(EXISTS (SELECT 1 FROM wall_message_likes ml WHERE ml.message_id = m.message_id AND ml.user_id = $1), FALSE) AS viewer_liked,+ COALESCE(m.is_deleted, FALSE) AS is_deleted,+ COALESCE(m.created_at, 0) AS message_created_at,+ COALESCE(m.updated_at, 0) AS message_updated_at,+ COALESCE(sender_wall.owner_id, 0) AS sender_owner_id,+ COALESCE(sender_wall.wall_id, '') AS sender_wall_id,+ COALESCE(sender_wall.wall_slug, '') AS sender_wall_slug,+ COALESCE(sender_ka.public_key, '') AS sender_public_key,+ COALESCE(sender_wall.current_version, 0) AS sender_current_version,+ COALESCE(sender_wall.encrypted_profile, '') AS sender_profile,+ sender_wall.avatar_object_key,+ sender_wall.avatar_size,+ COALESCE(sender_wall.updated_at, 0) AS sender_updated_at,+ CASE WHEN sender_wall.wall_id IS NULL THEN NULL::bigint ELSE (SELECT COUNT(*) FROM wall_friend_shares fs WHERE fs.wall_id = sender_wall.wall_id) END AS sender_friends,+ CASE WHEN sender_wall.wall_id IS NULL THEN NULL::bigint ELSE (SELECT COUNT(*) FROM wall_posts sp WHERE sp.wall_id = sender_wall.wall_id AND sp.is_deleted = FALSE) END AS sender_posts,+ COALESCE(recipient_wall.owner_id, 0) AS recipient_owner_id,+ COALESCE(recipient_wall.wall_id, '') AS recipient_wall_id,+ COALESCE(recipient_wall.wall_slug, '') AS recipient_wall_slug,+ COALESCE(recipient_ka.public_key, '') AS recipient_public_key,+ COALESCE(recipient_wall.current_version, 0) AS recipient_current_version,+ COALESCE(recipient_wall.encrypted_profile, '') AS recipient_profile,+ recipient_wall.avatar_object_key,+ recipient_wall.avatar_size,+ COALESCE(recipient_wall.updated_at, 0) AS recipient_updated_at,+ CASE WHEN recipient_wall.wall_id IS NULL THEN NULL::bigint ELSE (SELECT COUNT(*) FROM wall_friend_shares fs WHERE fs.wall_id = recipient_wall.wall_id) END AS recipient_friends,+ CASE WHEN recipient_wall.wall_id IS NULL THEN NULL::bigint ELSE (SELECT COUNT(*) FROM wall_posts rp WHERE rp.wall_id = recipient_wall.wall_id AND rp.is_deleted = FALSE) END AS recipient_posts,+ p.post_id,+ COALESCE(p.wall_id, '') AS post_wall_id,+ COALESCE(post_wall.wall_slug, '') AS post_wall_slug,+ COALESCE(p.owner_id, 0) AS post_owner_id,+ asset.object_key AS post_object_key,+ asset.size AS post_object_size,+ asset.position AS post_object_position,+ asset.variant AS post_object_variant,+ asset.blur_hash_cipher AS post_object_blur_hash_cipher,+ asset.width AS post_object_width,+ asset.height AS post_object_height,+ asset.media_type AS post_object_media_type+ FROM ranked c+ JOIN walls friend_wall ON friend_wall.wall_id = c.friend_wall_id+ JOIN key_attributes friend_ka ON friend_ka.user_id = friend_wall.owner_id+ LEFT JOIN wall_messages m ON m.message_id = c.message_id+ LEFT JOIN walls sender_wall ON sender_wall.wall_id = m.sender_wall_id+ LEFT JOIN key_attributes sender_ka ON sender_ka.user_id = sender_wall.owner_id+ LEFT JOIN walls recipient_wall ON recipient_wall.wall_id = m.recipient_wall_id+ LEFT JOIN key_attributes recipient_ka ON recipient_ka.user_id = recipient_wall.owner_id+ LEFT JOIN wall_posts p ON p.post_id = c.post_id AND p.is_deleted = FALSE+ LEFT JOIN walls post_wall ON post_wall.wall_id = p.wall_id+ LEFT JOIN LATERAL (+ SELECT object_key, size, position, variant, blur_hash_cipher, width, height, media_type+ FROM wall_post_assets+ WHERE post_id = p.post_id+ ORDER BY position ASC, asset_id ASC+ LIMIT 1+ ) asset ON TRUE+ WHERE c.rn = 1+ AND ($2::bigint IS NULL OR (c.activity_created_at, c.activity_id) < ($2::bigint, $3::text))+ ORDER BY c.activity_created_at DESC, c.activity_id DESCLIMIT $4`, viewerID, cursorCreatedAt, cursorID, limit+1)if err != nil {@@ -223,25 +402,18 @@ func (r *MessagesRepository) ListConversations(ctx context.Context, viewerID intdefer rows.Close()out := make([]WallMessageConversationRecord, 0, limit+1)for rows.Next() {- message, err := scanMessageRecord(rows)+ conversation, err := scanMessageConversationRecord(rows)if err != nil {return nil, "", err}- friend := message.Sender- if message.SenderID == viewerID {- friend = message.Recipient- }- out = append(out, WallMessageConversationRecord{- Friend: friend,- LastMessage: *message,- })+ out = append(out, *conversation)}if err := rows.Err(); err != nil {return nil, "", stacktrace.Propagate(err, "")}nextCursor := ""if len(out) > limit {- nextCursor = formatMessageCursor(out[limit-1].LastMessage)+ nextCursor = formatMessageConversationCursor(out[limit-1])out = out[:limit]}return out, nextCursor, nil@@ -278,6 +450,63 @@ func scanMessageRecord(scanner interface{ Scan(dest ...any) error }) (*WallMessareturn &rec, nil}+func scanMessageConversationRecord(scanner interface{ Scan(dest ...any) error }) (*WallMessageConversationRecord, error) {+ var rec WallMessageConversationRecord+ var message WallMessageRecord+ var postID sql.NullInt64+ var post WallMessageConversationPostRecord+ dest := []any{+ &rec.LatestActivity.Type,+ &rec.LatestActivity.ID,+ &rec.LatestActivity.CreatedAt,+ }+ dest = append(dest, wallActorScanDest(&rec.Friend)...)+ dest = append(dest,+ &message.MessageID,+ &message.Kind,+ &message.SenderID,+ &message.SenderWallID,+ &message.RecipientID,+ &message.RecipientWallID,+ &message.MessageCipher,+ &message.EncryptedMessageKey,+ &message.ReplyPostID,+ &message.ReplyMessageID,+ &message.Likes,+ &message.ViewerLiked,+ &message.IsDeleted,+ &message.CreatedAt,+ &message.UpdatedAt,+ )+ dest = append(dest, wallActorScanDest(&message.Sender)...)+ dest = append(dest, wallActorScanDest(&message.Recipient)...)+ dest = append(dest,+ &postID,+ &post.WallID,+ &post.WallSlug,+ &post.OwnerID,+ &post.ObjectKey,+ &post.ObjectSize,+ &post.ObjectPosition,+ &post.ObjectVariant,+ &post.ObjectBlurHashCipher,+ &post.ObjectWidth,+ &post.ObjectHeight,+ &post.ObjectMediaType,+ )+ if err := scanner.Scan(dest...); err != nil {+ return nil, stacktrace.Propagate(err, "")+ }+ if message.MessageID != "" {+ rec.LatestActivity.Message = &message+ }+ if postID.Valid {+ post.PostID = postID.Int64+ rec.LatestActivity.Post = &post+ }+ return &rec, nil+}+func parseMessageCursor(cursor string) (int64, string, bool) {createdAtText, id, ok := strings.Cut(strings.TrimSpace(cursor), ":")if !ok || strings.TrimSpace(id) == "" {@@ -293,3 +522,7 @@ func parseMessageCursor(cursor string) (int64, string, bool) {func formatMessageCursor(message WallMessageRecord) string {return strconv.FormatInt(message.CreatedAt, 10) + ":" + message.MessageID}++func formatMessageConversationCursor(conversation WallMessageConversationRecord) string {+ return strconv.FormatInt(conversation.LatestActivity.CreatedAt, 10) + ":" + conversation.LatestActivity.ID+}diff --git a/server/wall/repo/module.go b/server/wall/repo/module.goindex acd4807d24..f776bf3aca 100644--- a/server/wall/repo/module.go+++ b/server/wall/repo/module.go@@ -134,8 +134,31 @@ type WallMessageRecord struct {}type WallMessageConversationRecord struct {- Friend WallActorRecord- LastMessage WallMessageRecord+ Friend WallActorRecord+ LatestActivity WallMessageConversationActivityRecord+}++type WallMessageConversationActivityRecord struct {+ ID string+ Type string+ CreatedAt int64+ Message *WallMessageRecord+ Post *WallMessageConversationPostRecord+}++type WallMessageConversationPostRecord struct {+ PostID int64+ WallID string+ WallSlug string+ OwnerID int64+ ObjectKey sql.NullString+ ObjectSize sql.NullInt64+ ObjectPosition sql.NullInt64+ ObjectVariant sql.NullString+ ObjectBlurHashCipher sql.NullString+ ObjectWidth sql.NullInt64+ ObjectHeight sql.NullInt64+ ObjectMediaType sql.NullString}type CreateWallMessageRecord struct {diff --git a/server/wall/repo/module_test.go b/server/wall/repo/module_test.goindex 53a6cf3829..bb38d9bb9f 100644--- a/server/wall/repo/module_test.go+++ b/server/wall/repo/module_test.go@@ -137,7 +137,8 @@ func TestWallMessagesThreadAndConversations(t *testing.T) {require.Empty(t, nextCursor)require.Len(t, conversations, 1)require.Equal(t, bobWall.WallID, conversations[0].Friend.WallID)- require.Equal(t, reply.MessageID, conversations[0].LastMessage.MessageID)+ require.Equal(t, "message", conversations[0].LatestActivity.Type)+ require.Equal(t, reply.MessageID, conversations[0].LatestActivity.Message.MessageID)require.NoError(t, module.Messages.DeleteMessage(ctx, message.MessageID, bobID))deletedMessage, err := module.Messages.GetMessage(ctx, message.MessageID, bobID)@@ -167,6 +168,141 @@ func TestWallMessagesThreadAndConversations(t *testing.T) {require.Error(t, err)}+func TestWallMessageConversationsUseLatestActivity(t *testing.T) {+ ctx := context.Background()+ module := newWallTestModule(t)++ aliceID := insertWallUser(t, module, "[email protected]", "alice-activity-public")+ bobID := insertWallUser(t, module, "[email protected]", "bob-activity-public")++ aliceWall, err := module.Walls.CreateWall(ctx, aliceID, "alice-activity", "alice-wall-key", "alice-profile")+ require.NoError(t, err)+ bobWall, err := module.Walls.CreateWall(ctx, bobID, "bob-activity", "bob-wall-key", "bob-profile")+ require.NoError(t, err)++ require.NoError(t, module.Friends.AddFriend(ctx, bobID, bobWall.WallID, aliceWall.WallID, "alice-share-key", aliceWall.CurrentVersion, "bob-share-key", bobWall.CurrentVersion))+ setFriendEventCreatedAt(t, module, 1000, "friend_add", bobID, aliceID)++ conversations, nextCursor, err := module.Messages.ListConversations(ctx, aliceID, "", 10)+ require.NoError(t, err)+ require.Empty(t, nextCursor)+ require.Len(t, conversations, 1)+ require.Equal(t, bobWall.WallID, conversations[0].Friend.WallID)+ require.Equal(t, "friend_add", conversations[0].LatestActivity.Type)+ require.Nil(t, conversations[0].LatestActivity.Message)+ require.Nil(t, conversations[0].LatestActivity.Post)++ bobMessage, err := module.Messages.CreateMessage(ctx, CreateWallMessageRecord{+ Kind: "regular",+ SenderID: bobID,+ SenderWallID: bobWall.WallID,+ RecipientID: aliceID,+ RecipientWallID: aliceWall.WallID,+ MessageCipher: "bob-message-cipher",+ SenderEncryptedMessageKey: "bob-message-sender-key",+ RecipientEncryptedMessageKey: "bob-message-recipient-key",+ })+ require.NoError(t, err)+ setMessageCreatedAt(t, module, 2000, bobMessage.MessageID)++ conversations, _, err = module.Messages.ListConversations(ctx, aliceID, "", 10)+ require.NoError(t, err)+ require.Equal(t, "message", conversations[0].LatestActivity.Type)+ require.Equal(t, bobMessage.MessageID, conversations[0].LatestActivity.Message.MessageID)++ aliceMessage, err := module.Messages.CreateMessage(ctx, CreateWallMessageRecord{+ Kind: "regular",+ SenderID: aliceID,+ SenderWallID: aliceWall.WallID,+ RecipientID: bobID,+ RecipientWallID: bobWall.WallID,+ MessageCipher: "alice-message-cipher",+ SenderEncryptedMessageKey: "alice-message-sender-key",+ RecipientEncryptedMessageKey: "alice-message-recipient-key",+ })+ require.NoError(t, err)+ setMessageCreatedAt(t, module, 2500, aliceMessage.MessageID)+ require.NoError(t, module.Messages.SetLike(ctx, aliceMessage.MessageID, bobID, true))+ setMessageLikeCreatedAt(t, module, 3000, aliceMessage.MessageID, bobID)+ require.NoError(t, module.Messages.SetLike(ctx, bobMessage.MessageID, aliceID, true))+ setMessageLikeCreatedAt(t, module, 3500, bobMessage.MessageID, aliceID)++ conversations, _, err = module.Messages.ListConversations(ctx, aliceID, "", 10)+ require.NoError(t, err)+ require.Equal(t, "message_like", conversations[0].LatestActivity.Type)+ require.Equal(t, aliceMessage.MessageID, conversations[0].LatestActivity.Message.MessageID)++ postID, err := module.Posts.CreatePost(ctx, aliceID, aliceWall.WallID, "post-key", nil, aliceWall.CurrentVersion, nil)+ require.NoError(t, err)+ _, err = module.Posts.DB.Exec(`+ INSERT INTO wall_post_assets (post_id, object_key, bucket_id, width, height, media_type)+ VALUES ($1, $2, $3, $4, $5, $6)+ `, postID, "activity-post-object", "bucket", 320, 240, "image/jpeg")+ require.NoError(t, err)+ require.NoError(t, module.Posts.SetLike(ctx, postID, bobID, true))+ setPostLikeCreatedAt(t, module, 4000, postID, bobID)++ conversations, _, err = module.Messages.ListConversations(ctx, aliceID, "", 10)+ require.NoError(t, err)+ require.Equal(t, "post_like", conversations[0].LatestActivity.Type)+ require.NotNil(t, conversations[0].LatestActivity.Post)+ require.Equal(t, postID, conversations[0].LatestActivity.Post.PostID)+ require.Equal(t, "activity-post-object", conversations[0].LatestActivity.Post.ObjectKey.String)++ postReply, err := module.Messages.CreateMessage(ctx, CreateWallMessageRecord{+ Kind: "post_reply",+ SenderID: bobID,+ SenderWallID: bobWall.WallID,+ RecipientID: aliceID,+ RecipientWallID: aliceWall.WallID,+ MessageCipher: "post-reply-cipher",+ SenderEncryptedMessageKey: "post-reply-sender-key",+ RecipientEncryptedMessageKey: "post-reply-recipient-key",+ ReplyPostID: sql.NullInt64{Int64: postID, Valid: true},+ })+ require.NoError(t, err)+ setMessageCreatedAt(t, module, 5000, postReply.MessageID)++ conversations, _, err = module.Messages.ListConversations(ctx, aliceID, "", 10)+ require.NoError(t, err)+ require.Equal(t, "post_like_and_reply", conversations[0].LatestActivity.Type)+ require.NotNil(t, conversations[0].LatestActivity.Message)+ require.Equal(t, postReply.MessageID, conversations[0].LatestActivity.Message.MessageID)+ require.Equal(t, postID, conversations[0].LatestActivity.Post.PostID)++ replyOnlyPostID, err := module.Posts.CreatePost(ctx, aliceID, aliceWall.WallID, "reply-only-post-key", nil, aliceWall.CurrentVersion, nil)+ require.NoError(t, err)+ replyOnly, err := module.Messages.CreateMessage(ctx, CreateWallMessageRecord{+ Kind: "post_reply",+ SenderID: bobID,+ SenderWallID: bobWall.WallID,+ RecipientID: aliceID,+ RecipientWallID: aliceWall.WallID,+ MessageCipher: "reply-only-cipher",+ SenderEncryptedMessageKey: "reply-only-sender-key",+ RecipientEncryptedMessageKey: "reply-only-recipient-key",+ ReplyPostID: sql.NullInt64{Int64: replyOnlyPostID, Valid: true},+ })+ require.NoError(t, err)+ setMessageCreatedAt(t, module, 5500, replyOnly.MessageID)++ conversations, _, err = module.Messages.ListConversations(ctx, aliceID, "", 10)+ require.NoError(t, err)+ require.Equal(t, "post_reply", conversations[0].LatestActivity.Type)+ require.NotNil(t, conversations[0].LatestActivity.Message)+ require.Equal(t, replyOnly.MessageID, conversations[0].LatestActivity.Message.MessageID)+ require.Equal(t, replyOnlyPostID, conversations[0].LatestActivity.Post.PostID)++ require.NoError(t, module.Friends.DeleteFriendship(ctx, bobID, aliceWall.WallID))+ setFriendEventCreatedAt(t, module, 6000, "friend_remove", bobID, aliceID)++ conversations, _, err = module.Messages.ListConversations(ctx, aliceID, "", 10)+ require.NoError(t, err)+ require.Equal(t, "friend_remove", conversations[0].LatestActivity.Type)+ require.Nil(t, conversations[0].LatestActivity.Message)+ require.Nil(t, conversations[0].LatestActivity.Post)+}+func TestWallModuleLifecycle(t *testing.T) {ctx := context.Background()module := newWallTestModule(t)@@ -1049,3 +1185,9 @@ func setMessageCreatedAt(t *testing.T, module *Module, createdAt int64, messageI_, err := module.Messages.DB.Exec(`UPDATE wall_messages SET created_at = $1 WHERE message_id = $2`, createdAt, messageID)require.NoError(t, err)}++func setMessageLikeCreatedAt(t *testing.T, module *Module, createdAt int64, messageID string, userID int64) {+ t.Helper()+ _, err := module.Messages.DB.Exec(`UPDATE wall_message_likes SET created_at = $1 WHERE message_id = $2 AND user_id = $3`, createdAt, messageID, userID)+ require.NoError(t, err)+}diff --git a/web/apps/social/src/pages/app/friend.tsx b/web/apps/social/src/pages/app/friend.tsxindex 4a8f780571..bcf81278b5 100644--- a/web/apps/social/src/pages/app/friend.tsx+++ b/web/apps/social/src/pages/app/friend.tsx@@ -24,11 +24,9 @@ const backRouteForSource = () =>source == "home"? socialRoutes.home- : source == "notifications"- ? socialRoutes.notifications- : source == "profile"- ? socialRoutes.profile- : socialRoutes.friends;+ : source == "profile"+ ? socialRoutes.profile+ : socialRoutes.friends;const Page: React.FC = () => {const router = useRouter();@@ -39,7 +37,10 @@ const Page: React.FC = () => {const selectedFriend = friends.find((friend) => friend.id == friendID);const [friendsLoadAttempted, setFriendsLoadAttempted] = useState(false);const [posts, setPosts] = useState<SocialWallPost[]>([]);- const postGroups = useMemo(() => profilePostGroupsFromPosts(posts), [posts]);+ const postGroups = useMemo(+ () => profilePostGroupsFromPosts(posts),+ [posts],+ );useEffect(() => {if (!router.isReady) return;diff --git a/web/apps/social/src/pages/app/messages.tsx b/web/apps/social/src/pages/app/messages.tsxdeleted file mode 100644index 95cae96f35..0000000000--- a/web/apps/social/src/pages/app/messages.tsx+++ /dev/null@@ -1,149 +0,0 @@-import { SocialPageMeta } from "components/SocialPageMeta";-import { SocialRouteFallback } from "components/SocialRouteFallback";-import { useRouter } from "next/router";-import React from "react";-import { MessagesScreen, messagesBackground } from "screens/MessagesScreen";-import {- deleteCurrentMessage,- loadCurrentMessageConversations,- loadCurrentMessageThread,- replyToCurrentMessage,- sendCurrentMessage,- setCurrentMessageLiked,- type SocialWallMessage,- type SocialWallMessageConversation,-} from "services/socialWall";-import { useSocialAppState } from "state/socialAppState";-import { socialRoutes } from "utils/socialRoutes";--const Page: React.FC = () => {- const router = useRouter();- const { profile, profileLoadStatus } = useSocialAppState();- const [conversations, setConversations] = React.useState<- SocialWallMessageConversation[]- >([]);- const [isConversationsLoading, setIsConversationsLoading] =- React.useState(true);- const [isThreadLoading, setIsThreadLoading] = React.useState(false);- const [messages, setMessages] = React.useState<SocialWallMessage[]>([]);- const [selectedFriend, setSelectedFriend] = React.useState<- SocialWallMessageConversation["friend"] | undefined- >();-- const refreshConversations = React.useCallback(() => {- setIsConversationsLoading(true);- void loadCurrentMessageConversations()- .then((page) => setConversations(page.items))- .catch((error: unknown) =>- console.error("Failed to load message conversations", error),- )- .finally(() => setIsConversationsLoading(false));- }, []);-- React.useEffect(() => {- if (profileLoadStatus == "ready" && !profile) {- void router.replace(socialRoutes.onboarding);- }- }, [profile, profileLoadStatus, router]);-- React.useEffect(() => {- if (!profile) return;- refreshConversations();- }, [profile, refreshConversations]);-- React.useEffect(() => {- if (!selectedFriend) {- setMessages([]);- return;- }-- let cancelled = false;- setIsThreadLoading(true);- void loadCurrentMessageThread(- selectedFriend.wallId ?? selectedFriend.id,- )- .then((page) => {- if (!cancelled) setMessages(page.items);- })- .catch((error: unknown) =>- console.error("Failed to load message thread", error),- )- .finally(() => {- if (!cancelled) setIsThreadLoading(false);- });-- return () => {- cancelled = true;- };- }, [selectedFriend]);-- if (profileLoadStatus == "loading" || !profile) {- return <SocialRouteFallback background={messagesBackground} />;- }-- return (- <>- <SocialPageMeta themeColor={messagesBackground} />- <MessagesScreen- conversations={conversations}- isConversationsLoading={isConversationsLoading}- isThreadLoading={isThreadLoading}- messages={messages}- onBack={() => void router.push(socialRoutes.notifications)}- onCloseThread={() => setSelectedFriend(undefined)}- onOpenThread={setSelectedFriend}- onSendMessage={async (wallId, text) => {- const message = await sendCurrentMessage(wallId, text);- setMessages((currentMessages) => [- ...currentMessages,- message,- ]);- refreshConversations();- }}- onReplyToMessage={async (wallId, messageId, text) => {- const message = await replyToCurrentMessage(- wallId,- messageId,- text,- );- setMessages((currentMessages) => [- ...currentMessages,- message,- ]);- refreshConversations();- }}- onSetMessageLiked={async (messageId, liked) => {- await setCurrentMessageLiked(messageId, liked);- setMessages((currentMessages) =>- currentMessages.map((message) =>- message.id == messageId- ? {- ...message,- likeCount: Math.max(- 0,- message.likeCount + (liked ? 1 : -1),- ),- viewerLiked: liked,- }- : message,- ),- );- refreshConversations();- }}- onDeleteMessage={async (messageId) => {- await deleteCurrentMessage(messageId);- setMessages((currentMessages) =>- currentMessages.filter(- (message) => message.id != messageId,- ),- );- refreshConversations();- }}- profile={profile}- selectedFriend={selectedFriend}- />- </>- );-};--export default Page;diff --git a/web/apps/social/src/pages/app/notifications.tsx b/web/apps/social/src/pages/app/notifications.tsxindex aa5c061a58..3759f386ab 100644--- a/web/apps/social/src/pages/app/notifications.tsx+++ b/web/apps/social/src/pages/app/notifications.tsx@@ -1,81 +1,146 @@import { SocialPageMeta } from "components/SocialPageMeta";import { SocialRouteFallback } from "components/SocialRouteFallback";import { useRouter } from "next/router";-import React, { useEffect, useMemo, useState } from "react";+import React from "react";+import { MessagesScreen, messagesBackground } from "screens/MessagesScreen";import {- NotificationsScreen,- notificationsBackground,-} from "screens/NotificationsScreen";-import {- loadCurrentNotificationsPage,- loadCurrentPostLikers,- setCurrentPostLiked,- type SocialWallNotification,+ deleteCurrentMessage,+ loadCurrentMessageConversations,+ loadCurrentMessageThread,+ replyToCurrentMessage,+ sendCurrentMessage,+ setCurrentMessageLiked,+ type SocialWallMessage,+ type SocialWallMessageConversation,} from "services/socialWall";import { useSocialAppState } from "state/socialAppState";import { socialRoutes } from "utils/socialRoutes";-import { notificationForScreen } from "utils/socialWallDisplay";const Page: React.FC = () => {const router = useRouter();const { profile, profileLoadStatus } = useSocialAppState();- const [notifications, setNotifications] = useState<- SocialWallNotification[]+ const [conversations, setConversations] = React.useState<+ SocialWallMessageConversation[]>([]);- const [isNotificationsLoading, setIsNotificationsLoading] = useState(true);- const screenNotifications = useMemo(- () => notifications.map(notificationForScreen),- [notifications],- );+ const [isConversationsLoading, setIsConversationsLoading] =+ React.useState(true);+ const [isThreadLoading, setIsThreadLoading] = React.useState(false);+ const [messages, setMessages] = React.useState<SocialWallMessage[]>([]);+ const [selectedFriend, setSelectedFriend] = React.useState<+ SocialWallMessageConversation["friend"] | undefined+ >();- useEffect(() => {+ const refreshConversations = React.useCallback(() => {+ setIsConversationsLoading(true);+ void loadCurrentMessageConversations()+ .then((page) => setConversations(page.items))+ .catch((error: unknown) =>+ console.error("Failed to load message conversations", error),+ )+ .finally(() => setIsConversationsLoading(false));+ }, []);++ React.useEffect(() => {if (profileLoadStatus == "ready" && !profile) {void router.replace(socialRoutes.onboarding);}}, [profile, profileLoadStatus, router]);- useEffect(() => {+ React.useEffect(() => {if (!profile) return;+ refreshConversations();+ }, [profile, refreshConversations]);++ React.useEffect(() => {+ if (!selectedFriend) {+ setMessages([]);+ return;+ }let cancelled = false;- setIsNotificationsLoading(true);- void loadCurrentNotificationsPage()+ setIsThreadLoading(true);+ void loadCurrentMessageThread(+ selectedFriend.wallId ?? selectedFriend.id,+ ).then((page) => {- if (cancelled) return;- setNotifications(page.items);+ if (!cancelled) setMessages(page.items);}).catch((error: unknown) =>- console.error("Failed to load notifications", error),+ console.error("Failed to load message thread", error),).finally(() => {- if (!cancelled) setIsNotificationsLoading(false);+ if (!cancelled) setIsThreadLoading(false);});return () => {cancelled = true;};- }, [profile]);+ }, [selectedFriend]);if (profileLoadStatus == "loading" || !profile) {- return <SocialRouteFallback background={notificationsBackground} />;+ return <SocialRouteFallback background={messagesBackground} />;}return (<>- <SocialPageMeta themeColor={notificationsBackground} />- <NotificationsScreen- isNotificationsLoading={isNotificationsLoading}- notifications={screenNotifications}+ <SocialPageMeta themeColor={messagesBackground} />+ <MessagesScreen+ conversations={conversations}+ isConversationsLoading={isConversationsLoading}+ isThreadLoading={isThreadLoading}+ messages={messages}onBack={() => void router.push(socialRoutes.home)}- onOpenFriend={(friendID) =>- void router.push(- socialRoutes.friend(friendID, "notifications"),- )- }- onOpenMessages={() => void router.push(socialRoutes.messages)}- onLoadPostLikers={loadCurrentPostLikers}- onSetPostLiked={setCurrentPostLiked}+ onCloseThread={() => setSelectedFriend(undefined)}+ onOpenThread={setSelectedFriend}+ onSendMessage={async (wallId, text) => {+ const message = await sendCurrentMessage(wallId, text);+ setMessages((currentMessages) => [+ ...currentMessages,+ message,+ ]);+ refreshConversations();+ }}+ onReplyToMessage={async (wallId, messageId, text) => {+ const message = await replyToCurrentMessage(+ wallId,+ messageId,+ text,+ );+ setMessages((currentMessages) => [+ ...currentMessages,+ message,+ ]);+ refreshConversations();+ }}+ onSetMessageLiked={async (messageId, liked) => {+ await setCurrentMessageLiked(messageId, liked);+ setMessages((currentMessages) =>+ currentMessages.map((message) =>+ message.id == messageId+ ? {+ ...message,+ likeCount: Math.max(+ 0,+ message.likeCount + (liked ? 1 : -1),+ ),+ viewerLiked: liked,+ }+ : message,+ ),+ );+ refreshConversations();+ }}+ onDeleteMessage={async (messageId) => {+ await deleteCurrentMessage(messageId);+ setMessages((currentMessages) =>+ currentMessages.filter(+ (message) => message.id != messageId,+ ),+ );+ refreshConversations();+ }}profile={profile}+ selectedFriend={selectedFriend}/></>);diff --git a/web/apps/social/src/screens/HomeScreen.tsx b/web/apps/social/src/screens/HomeScreen.tsxindex b6c5c71303..68168da472 100644--- a/web/apps/social/src/screens/HomeScreen.tsx+++ b/web/apps/social/src/screens/HomeScreen.tsx@@ -2,7 +2,7 @@ import {AddSquareIcon,FavouriteIcon,MultiplicationSignIcon,- NotificationIcon,+ Notification01Icon,UserCheck01Icon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";@@ -824,7 +824,7 @@ export const HomeScreen: React.FC<HomeScreenProps> = ({}}><HugeiconsIcon- icon={NotificationIcon}+ icon={Notification01Icon}size={headerIconSize}strokeWidth={1.8}/>diff --git a/web/apps/social/src/screens/MessagesScreen.tsx b/web/apps/social/src/screens/MessagesScreen.tsxindex 571b31c0b3..ba96450268 100644--- a/web/apps/social/src/screens/MessagesScreen.tsx+++ b/web/apps/social/src/screens/MessagesScreen.tsx@@ -6,7 +6,7 @@ import {Tick02Icon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";-import { Box, Menu, MenuItem } from "@mui/material";+import { Box, Menu, MenuItem, Tooltip } from "@mui/material";import { keyframes } from "@mui/material/styles";import { SocialLoadingSpinner } from "components/SocialRouteFallback";import { formatTimeAgo } from "ente-base/date";@@ -87,24 +87,7 @@ const resizeComposer = (input: HTMLTextAreaElement | null) => {};const copyTextToClipboard = async (text: string) => {- if (navigator.clipboard?.writeText) {- await navigator.clipboard.writeText(text);- return;- }-- const input = document.createElement("textarea");- input.value = text;- input.setAttribute("readonly", "");- input.style.left = "-9999px";- input.style.opacity = "0";- input.style.position = "fixed";- input.style.top = "0";- document.body.appendChild(input);- input.focus();- input.select();- const copied = document.execCommand("copy");- input.remove();- if (!copied) throw new Error("Copy failed");+ await navigator.clipboard.writeText(text);};const Avatar: React.FC<{@@ -164,41 +147,154 @@ const messagePreview = (message: SocialWallMessage) => {return message.text;};+const truncateMessageText = (text: string): string => {+ const lines = text.split("\n");+ const firstLine = lines[0] ?? text;+ if (firstLine.length > 100) return `${firstLine.slice(0, 100)}...`;+ return lines.length > 1 ? `${firstLine}...` : firstLine;+};+const isCurrentProfileMessage = (message: SocialWallMessage,profile: SetupProfile,+) => isCurrentProfileActor(message.sender, profile);++const isCurrentProfileActor = (+ actor: SocialWallMessage["sender"],+ profile: SetupProfile,) => {- if (message.sender.wallId && profile.wallId) {- return message.sender.wallId == profile.wallId;+ if (actor.wallId && profile.wallId) {+ return actor.wallId == profile.wallId;}- if (message.sender.wallSlug && profile.wallSlug) {- return message.sender.wallSlug == profile.wallSlug;+ if (actor.wallSlug && profile.wallSlug) {+ return actor.wallSlug == profile.wallSlug;}- return message.sender.username == profile.username;+ return actor.username == profile.username;};-const conversationPreview = (+const actorName = (actor: SocialWallMessage["sender"]) =>+ firstNameFrom(actor.fullName.trim() || actor.username);++const messageLikeTooltipLabel = (message: SocialWallMessage,profile: SetupProfile,) => {+ const otherParticipant = isCurrentProfileActor(message.sender, profile)+ ? message.recipient+ : message.sender;+ const likerNames: string[] = [];+ if (message.viewerLiked) likerNames.push("You");+ if (message.likeCount > likerNames.length) {+ likerNames.push(actorName(otherParticipant));+ }+ if (message.likeCount > likerNames.length) {+ likerNames.push(`${message.likeCount - likerNames.length} others`);+ }+ return likerNames.filter(Boolean).join(" and ") || "Liked";+};++const conversationPreview = (+ conversation: SocialWallMessageConversation,+ profile: SetupProfile,+) => {+ const activity = conversation.latestActivity;+ if (activity.type == "friend_add") return "Added you as a friend";+ if (activity.type == "friend_remove") return "Removed you as a friend";+ if (activity.type == "post_like") return "Liked your post";+ if (activity.type == "post_reply") {+ return "Replied";+ }+ if (activity.type == "post_like_and_reply") {+ return "Liked and replied";+ }+ if (activity.type == "message_like") {+ const text = activity.message?.text.trim();+ return text+ ? `Liked "${truncateMessageText(text)}"`+ : "Liked a message";+ }++ const message = activity.message;+ if (!message) return "";const preview = messagePreview(message);return isCurrentProfileMessage(message, profile)? `You: ${preview}`: preview;};+const quotedConversationActivityPreview = (+ activity: SocialWallMessageConversation["latestActivity"],+) => {+ const text = activity.message?.text.trim();+ if (!text) return undefined;+ const previewText = truncateMessageText(text);++ if (activity.type == "message_like") {+ return { prefix: 'Liked "', previewText, suffix: '"' };+ }+ if (activity.type == "post_reply") {+ return { prefix: 'Replied "', previewText, suffix: '"' };+ }+ if (activity.type == "post_like_and_reply") {+ return { prefix: 'Liked and replied "', previewText, suffix: '"' };+ }+ return undefined;+};++const ConversationPreviewLine: React.FC<{+ conversation: SocialWallMessageConversation;+ profile: SetupProfile;+}> = ({ conversation, profile }) => {+ const activity = conversation.latestActivity;+ const quotedPreview = quotedConversationActivityPreview(activity);+ const previewLineSx = {+ color: textSecondary,+ fontFamily: '"Inter Variable", Inter, sans-serif',+ fontSize: 13,+ fontWeight: 500,+ lineHeight: "18px",+ minWidth: 0,+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ };++ if (!quotedPreview) {+ return (+ <Box sx={previewLineSx}>+ {conversationPreview(conversation, profile)}+ </Box>+ );+ }++ return (+ <Box sx={{ ...previewLineSx, alignItems: "baseline", display: "flex" }}>+ <Box component="span" sx={{ flexShrink: 0 }}>+ {quotedPreview.prefix}+ </Box>+ <Box+ component="span"+ sx={{+ minWidth: 0,+ overflow: "hidden",+ textOverflow: "ellipsis",+ whiteSpace: "nowrap",+ }}+ >+ {quotedPreview.previewText}+ </Box>+ <Box component="span" sx={{ flexShrink: 0 }}>+ {quotedPreview.suffix}+ </Box>+ </Box>+ );+};+const sameMessageSender = (first: SocialWallMessage | undefined,second: SocialWallMessage | undefined,) => Boolean(first && second && first.sender.wallId == second.sender.wallId);-const truncateMessageText = (text: string): string => {- const lines = text.split("\n");- const firstLine = lines[0] ?? text;- if (firstLine.length > 100) return `${firstLine.slice(0, 100)}...`;- return lines.length > 1 ? `${firstLine}...` : firstLine;-};-const ReplyIcon: React.FC = () => (<svgwidth="12"@@ -482,6 +578,26 @@ const MessageBubble: React.FC<{: "6px 20px 20px 6px";const hasMessageReply = Boolean(message.replyMessageId);const hasInlinePreview = message.kind == "post_reply" || hasMessageReply;+ const [isLikeTooltipOpen, setIsLikeTooltipOpen] = React.useState(false);+ const likeTooltipTimerRef = React.useRef<number | undefined>(undefined);+ const likeTooltipLabel = messageLikeTooltipLabel(message, profile);++ const clearLikeTooltipTimer = React.useCallback(() => {+ if (likeTooltipTimerRef.current == undefined) return;+ window.clearTimeout(likeTooltipTimerRef.current);+ likeTooltipTimerRef.current = undefined;+ }, []);++ const showLikeTooltip = (event: React.MouseEvent) => {+ event.preventDefault();+ event.stopPropagation();+ clearLikeTooltipTimer();+ setIsLikeTooltipOpen(true);+ likeTooltipTimerRef.current = window.setTimeout(() => {+ setIsLikeTooltipOpen(false);+ likeTooltipTimerRef.current = undefined;+ }, 1800);+ };const handleContextMenu = (event: React.MouseEvent,@@ -493,6 +609,18 @@ const MessageBubble: React.FC<{onOpenActions(message, bubbleElement);};+ React.useEffect(() => clearLikeTooltipTimer, [clearLikeTooltipTimer]);++ React.useEffect(() => {+ clearLikeTooltipTimer();+ setIsLikeTooltipOpen(false);+ }, [+ clearLikeTooltipTimer,+ message.id,+ message.likeCount,+ message.viewerLiked,+ ]);+return (<Boxcomponent="li"@@ -580,38 +708,77 @@ const MessageBubble: React.FC<{{message.text}</Box>{message.likeCount > 0 && (- <Box- aria-label="Liked"- role="img"- sx={{- alignItems: "center",- bgcolor: "#2B2B2B",- border: `2px solid ${threadBackground}`,- borderRadius: "999px",- bottom: -11,- boxShadow: "0 4px 10px rgba(0, 0, 0, 0.2)",- boxSizing: "border-box",- color: green,- display: "inline-flex",- fontFamily:- '"Inter Variable", Inter, sans-serif',- fontSize: 10,- fontWeight: 800,- gap: "4px",- height: 22,- justifyContent: "center",- lineHeight: 1,- minWidth: message.likeCount > 1 ? 34 : 28,- pb: "1px",- px: "7px",- position: "absolute",- zIndex: 2,- ...(isOwn ? { left: 8 } : { right: 8 }),+ <Tooltip+ arrow+ disableFocusListener+ disableHoverListener+ disableTouchListener+ open={isLikeTooltipOpen}+ placement={isOwn ? "left" : "right"}+ title={likeTooltipLabel}+ slotProps={{+ tooltip: {+ sx: {+ bgcolor: "#111111",+ borderRadius: "6px",+ color: threadText,+ fontFamily:+ '"Inter Variable", Inter, sans-serif',+ fontSize: 12,+ fontWeight: 700,+ lineHeight: "16px",+ px: "8px",+ py: "5px",+ },+ },+ arrow: { sx: { color: "#111111" } },}}>- <HeartIcon filled small />- {message.likeCount > 1 ? message.likeCount : null}- </Box>+ <Box+ component="button"+ type="button"+ aria-label={`Liked by ${likeTooltipLabel}`}+ onClick={showLikeTooltip}+ onContextMenu={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ sx={{+ alignItems: "center",+ appearance: "none",+ bgcolor: "#2B2B2B",+ border: `2px solid ${threadBackground}`,+ borderRadius: "999px",+ bottom: -11,+ boxShadow: "0 4px 10px rgba(0, 0, 0, 0.2)",+ boxSizing: "border-box",+ color: green,+ cursor: "pointer",+ display: "inline-flex",+ fontFamily:+ '"Inter Variable", Inter, sans-serif',+ fontSize: 10,+ fontWeight: 800,+ gap: "4px",+ height: 22,+ justifyContent: "center",+ lineHeight: 1,+ minWidth: 34,+ pb: "1px",+ px: "7px",+ position: "absolute",+ zIndex: 2,+ ...(isOwn ? { left: 8 } : { right: 8 }),+ "&:focus-visible": {+ outline: `2px solid ${green}`,+ outlineOffset: 2,+ },+ }}+ >+ <HeartIcon filled small />+ {message.likeCount}+ </Box>+ </Tooltip>)}</Box></Box>@@ -807,7 +974,9 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({<Boxcomponent="button"type="button"- aria-label={isThreadOpen ? "Back to messages" : "Back"}+ aria-label={+ isThreadOpen ? "Back to notifications" : "Back"+ }onClick={isThreadOpen ? onCloseThread : onBack}sx={{alignItems: "center",@@ -853,7 +1022,7 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({>{isThreadOpen? firstNameFrom(selectedName)- : "Messages"}+ : "Notifications"}</Box><Box aria-hidden /></Box>@@ -883,6 +1052,32 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({><SocialLoadingSpinner ariaLabel="Loading messages" /></Box>+ ) : messages.length == 0 ? (+ <Box+ sx={{+ alignItems: "center",+ display: "flex",+ height: "100%",+ justifyContent: "center",+ pointerEvents: "none",+ textAlign: "center",+ }}+ >+ <Box+ component="p"+ sx={{+ color: threadTimestamp,+ fontFamily:+ '"Inter Variable", Inter, sans-serif',+ fontSize: 14,+ fontWeight: 650,+ lineHeight: "20px",+ m: 0,+ }}+ >+ No messages yet+ </Box>+ </Box>) : (<Boxcomponent="ol"@@ -1386,21 +1581,6 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({textAlign: "center",}}>- <Box- component="h2"- sx={{- color: textBase,- fontFamily:- '"Inter Variable", Inter, sans-serif',- fontSize: 16,- fontWeight: 700,- letterSpacing: 0,- lineHeight: "22px",- m: 0,- }}- >- No messages yet- </Box><Boxcomponent="p"sx={{@@ -1411,12 +1591,9 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({fontWeight: 500,lineHeight: "20px",m: 0,- mt: "8px",- maxWidth: 260,}}>- Replies to posts and messages from friends- will appear here.+ No messages yet</Box></Box>) : (@@ -1435,10 +1612,13 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({conversation.friend.username;const timestampLabel = formatTimeAgo(microsForTimestamp(- conversation.lastMessage+ conversation.latestActivity.createdAtMs,),);+ const postThumbnailUrl =+ conversation.latestActivity.post+ ?.imageUrl;return (<Boxcomponent="li"@@ -1464,7 +1644,9 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({display: "grid",gap: "10px",gridTemplateColumns:- "44px minmax(0, 1fr)",+ postThumbnailUrl+ ? "44px minmax(0, 1fr) 44px"+ : "44px minmax(0, 1fr)",minHeight: 64,p: "8px 0",textAlign: "left",@@ -1489,13 +1671,13 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({alignItems:"center",display: "flex",- gap: "8px",+ gap: "4px",minWidth: 0,}}><Boxsx={{- flex: "1 1 auto",+ flex: "0 1 auto",fontFamily:'"Inter Variable", Inter, sans-serif',fontSize: 14,@@ -1515,10 +1697,26 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({name,)}</Box>+ <Box+ aria-hidden+ component="span"+ sx={{+ color: textSecondary,+ flexShrink: 0,+ fontFamily:+ '"Inter Variable", Inter, sans-serif',+ fontSize: 12,+ fontWeight: 600,+ lineHeight:+ "16px",+ }}+ >+ ·+ </Box><Boxcomponent="time"dateTime={new Date(- conversation.lastMessage.createdAtMs,+ conversation.latestActivity.createdAtMs,).toISOString()}sx={{color: textSecondary,@@ -1536,27 +1734,29 @@ export const MessagesScreen: React.FC<MessagesScreenProps> = ({{timestampLabel}</Box></Box>+ <ConversationPreviewLine+ conversation={+ conversation+ }+ profile={profile}+ />+ </Box>+ {postThumbnailUrl && (<Box+ component="img"+ alt=""+ src={postThumbnailUrl}sx={{- color: textSecondary,- fontFamily:- '"Inter Variable", Inter, sans-serif',- fontSize: 13,- fontWeight: 500,- lineHeight: "18px",- overflow: "hidden",- textOverflow:- "ellipsis",- whiteSpace:- "nowrap",+ borderRadius: "6px",+ display: "block",+ height: 44,+ objectFit: "cover",+ objectPosition:+ "center",+ width: 44,}}- >- {conversationPreview(- conversation.lastMessage,- profile,- )}- </Box>- </Box>+ />+ )}</Box></Box>);diff --git a/web/apps/social/src/screens/NotificationsScreen.tsx b/web/apps/social/src/screens/NotificationsScreen.tsxdeleted file mode 100644index 69d06cf61c..0000000000--- a/web/apps/social/src/screens/NotificationsScreen.tsx+++ /dev/null@@ -1,628 +0,0 @@-import {- ArrowLeft02Icon,- Message01Icon,- UserAdd01Icon,- UserRemove01Icon,-} from "@hugeicons/core-free-icons";-import { HugeiconsIcon } from "@hugeicons/react";-import { Box } from "@mui/material";-import {- SocialFileViewer,- type SocialLiker,- type SocialViewerPhoto,-} from "components/SocialFileViewer";-import { SocialLoadingSpinner } from "components/SocialRouteFallback";-import type { FriendProfile } from "data/friends";-import { formatTimeAgo } from "ente-base/date";-import React from "react";-import type { SetupProfile } from "screens/SetupProfileScreen";-import { firstNameFrom, initialsFor } from "utils/socialDisplay";--export const notificationsBackground = "#FFFFFF";--const green = "#08C225";-const paleGreen = "#E7F6E9";-const textBase = "#000";-const textSoft = "#777777";-const timelineLine = "#E6E6E6";-const iconCircleBackground = "#F5F5F7";-const iconCircleSize = 28;-const iconCircleTopOffset = 2;-const timelineLineLeft = iconCircleSize / 2 - 1;-const timelineLineTop = iconCircleTopOffset + iconCircleSize;-const timelineListInset = "12px";-const thumbnailRightInset = "16px";--type NotificationType =- | "liked-post"- | "replied-post"- | "added-friend"- | "removed-friend";--interface SocialNotification {- actor: Pick<FriendProfile, "avatarUrl" | "fullName" | "id" | "username">;- id: string;- post?: SocialViewerPhoto;- postThumbnailUrl?: string;- timestampMs: number;- type: NotificationType;-}--interface NotificationsScreenProps {- isNotificationsLoading?: boolean;- onBack?: () => void;- onOpenFriend?: (friendID: string) => void;- profile: SetupProfile;- notifications: SocialNotification[];- onLoadPostLikers?: (postId: number) => Promise<SocialLiker[]>;- onOpenMessages?: () => void;- onSetPostLiked?: (postId: number, liked: boolean) => Promise<void>;-}--interface NotificationRowProps {- notification: SocialNotification;- onOpenFriend?: (friendID: string) => void;- onOpenPost?: (notification: SocialNotification) => void;-}--const microsForTimestamp = (timestampMs: number) => timestampMs * 1000;--const LikedPhotoIcon: React.FC = () => (- <svg- width="15"- height="13"- viewBox="0 0 17 15"- fill="none"- xmlns="http://www.w3.org/2000/svg"- >- <path- d="M6.99906 13.1537C4.84391 11.5421 0.574219 7.85775 0.574219 4.54219C0.574219 2.35074 2.1824 0.574219 4.39366 0.574219C5.5395 0.574219 6.68533 0.956163 8.21311 2.48394C9.74089 0.956163 10.8867 0.574219 12.0326 0.574219C14.2438 0.574219 15.852 2.35074 15.852 4.54219C15.852 7.85775 11.5823 11.5421 9.42716 13.1537C8.70192 13.696 7.7243 13.696 6.99906 13.1537Z"- fill="#08C225"- stroke="#08C225"- strokeWidth="1.14583"- strokeLinecap="round"- strokeLinejoin="round"- />- </svg>-);--const RepliedPostNotificationIcon: React.FC = () => (- <svg- width="15"- height="12"- viewBox="0 0 12 9"- fill="none"- xmlns="http://www.w3.org/2000/svg"- >- <path- fillRule="evenodd"- clipRule="evenodd"- d="M4.5241 0.242677C4.62341 0.34442 4.67919 0.482337 4.67919 0.626134C4.67919 0.76993 4.62341 0.907847 4.5241 1.00959L1.89369 3.70102H7.68483C8.3587 3.70102 9.35854 3.9036 10.2042 4.52653C11.0775 5.17045 11.7507 6.23762 11.7507 7.86116C11.7507 8.00507 11.6948 8.14309 11.5953 8.24485C11.4959 8.34661 11.361 8.40378 11.2203 8.40378C11.0797 8.40378 10.9448 8.34661 10.8453 8.24485C10.7459 8.14309 10.69 8.00507 10.69 7.86116C10.69 6.59069 10.1844 5.84982 9.58481 5.40776C8.95761 4.94544 8.18899 4.78627 7.68483 4.78627H1.89369L4.5241 7.4777C4.5762 7.52738 4.61799 7.58728 4.64698 7.65384C4.67597 7.72041 4.69155 7.79226 4.69281 7.86512C4.69406 7.93798 4.68096 8.01035 4.65429 8.07791C4.62762 8.14548 4.58792 8.20686 4.53756 8.25839C4.4872 8.30991 4.42722 8.35053 4.36118 8.37782C4.29515 8.40512 4.22442 8.41852 4.15321 8.41723C4.082 8.41595 4.01178 8.4 3.94673 8.37034C3.88167 8.34068 3.82313 8.29792 3.77457 8.24461L0.23908 4.6271C0.139767 4.52536 0.0839844 4.38744 0.0839844 4.24364C0.0839844 4.09985 0.139767 3.96193 0.23908 3.86019L3.77457 0.242677C3.87401 0.141061 4.0088 0.0839844 4.14934 0.0839844C4.28987 0.0839844 4.42466 0.141061 4.5241 0.242677Z"- fill="currentColor"- stroke="currentColor"- strokeWidth="0.166667"- />- </svg>-);--const UserAddNotificationIcon: React.FC = () => (- <HugeiconsIcon icon={UserAdd01Icon} size={17} strokeWidth={1.8} />-);--const UserRemoveNotificationIcon: React.FC = () => (- <HugeiconsIcon icon={UserRemove01Icon} size={17} strokeWidth={1.8} />-);--const actionForNotification = (- type: NotificationType,-): { icon: React.ReactNode; label: string } => {- switch (type) {- case "liked-post":- return { icon: <LikedPhotoIcon />, label: "liked your post" };- case "replied-post":- return {- icon: <RepliedPostNotificationIcon />,- label: "replied to your post",- };- case "added-friend":- return {- icon: <UserAddNotificationIcon />,- label: "added you as a friend",- };- case "removed-friend":- return {- icon: <UserRemoveNotificationIcon />,- label: "removed you as a friend",- };- }-};--const NotificationRow: React.FC<NotificationRowProps> = ({- notification,- onOpenFriend,- onOpenPost,-}) => {- const { icon, label } = actionForNotification(notification.type);- const actorName =- notification.actor.fullName.trim() || notification.actor.username;- const actorFirstName = firstNameFrom(actorName);- const actorInitials = initialsFor(- actorFirstName || notification.actor.username,- );- const timestampMicros = microsForTimestamp(notification.timestampMs);- const timestampDateTime = new Date(- Math.floor(timestampMicros / 1000),- ).toISOString();- const timestampLabel = formatTimeAgo(timestampMicros);-- return (- <Box- component="li"- sx={{- alignItems: "flex-start",- display: "flex",- gap: "12px",- listStyle: "none",- mb: "40px",- position: "relative",- width: "100%",- "&:last-of-type": { mb: 0 },- "&:not(:last-of-type)::before": {- backgroundImage: `repeating-linear-gradient(to bottom, ${timelineLine} 0px, ${timelineLine} 8px, transparent 8px, transparent 16px)`,- borderRadius: "1px",- bottom: "-40px",- content: '""',- left: `${timelineLineLeft}px`,- position: "absolute",- top: `${timelineLineTop}px`,- width: "2px",- },- }}- >- <Box- sx={{- alignItems: "flex-start",- display: "flex",- flex: 1,- gap: "8px",- minWidth: 0,- width: "100%",- }}- >- <Box- sx={{- alignItems: "center",- bgcolor: iconCircleBackground,- borderRadius: "50%",- color: green,- display: "flex",- flexShrink: 0,- height: iconCircleSize,- justifyContent: "center",- mt: `${iconCircleTopOffset}px`,- position: "relative",- zIndex: 1,- width: iconCircleSize,- }}- >- {icon}- </Box>- <Box- sx={{- display: "flex",- flex: 1,- flexDirection: "column",- gap: "4px",- minWidth: 0,- }}- >- <Box- sx={{- alignItems: "center",- display: "flex",- flexDirection: "row",- }}- >- <Box- component="button"- type="button"- aria-label={`Open ${actorFirstName}'s profile`}- onClick={() =>- onOpenFriend?.(notification.actor.id)- }- sx={{- appearance: "none",- alignItems: "center",- bgcolor: notification.actor.avatarUrl- ? "transparent"- : paleGreen,- border: `2px solid ${notificationsBackground}`,- borderRadius: "50%",- color: green,- boxSizing: "border-box",- cursor: onOpenFriend ? "pointer" : "default",- display: "flex",- flexShrink: 0,- height: 32,- justifyContent: "center",- overflow: "hidden",- p: 0,- width: 32,- "&:focus-visible": {- outline: `2px solid ${green}`,- outlineOffset: 2,- },- }}- >- {notification.actor.avatarUrl ? (- <Box- component="img"- alt=""- src={notification.actor.avatarUrl}- sx={{- display: "block",- height: "100%",- objectFit: "cover",- objectPosition: "center",- width: "100%",- }}- />- ) : (- <Box- sx={{- fontFamily:- '"Inter Variable", Inter, sans-serif',- fontSize: 11,- fontWeight: 800,- lineHeight: 1,- }}- >- {actorInitials}- </Box>- )}- </Box>- </Box>- <Box- sx={{- color: textBase,- fontFamily: '"Inter Variable", Inter, sans-serif',- fontSize: 14,- fontWeight: 500,- lineHeight: "19px",- minWidth: 0,- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",- }}- >- <Box- component="button"- type="button"- aria-label={`Open ${actorFirstName}'s profile`}- onClick={() =>- onOpenFriend?.(notification.actor.id)- }- sx={{- appearance: "none",- bgcolor: "transparent",- border: 0,- borderRadius: "4px",- color: "inherit",- cursor: onOpenFriend ? "pointer" : "default",- display: "inline",- font: "inherit",- fontWeight: 600,- lineHeight: "inherit",- p: 0,- textAlign: "left",- "&:focus-visible": {- outline: `2px solid ${green}`,- outlineOffset: 2,- },- }}- >- {actorFirstName}- </Box>{" "}- {label}- </Box>- <Box- component="time"- dateTime={timestampDateTime}- sx={{- color: textSoft,- fontFamily: '"Inter Variable", Inter, sans-serif',- fontSize: 13,- fontWeight: 500,- lineHeight: "18px",- minWidth: 0,- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",- }}- >- {timestampLabel}- </Box>- </Box>- {notification.postThumbnailUrl && (- <Box- component="button"- type="button"- aria-label="Open your post"- onClick={() => onOpenPost?.(notification)}- sx={{- appearance: "none",- bgcolor: "transparent",- border: 0,- borderRadius: "8px",- display: "block",- flexShrink: 0,- height: 74,- overflow: "hidden",- p: 0,- width: 74,- "&:focus-visible": {- outline: `2px solid ${green}`,- outlineOffset: 2,- },- }}- >- <Box- component="img"- alt=""- src={notification.postThumbnailUrl}- sx={{- display: "block",- height: "100%",- objectFit: "cover",- objectPosition: "center",- width: "100%",- }}- />- </Box>- )}- </Box>- </Box>- );-};--export const NotificationsScreen: React.FC<NotificationsScreenProps> = ({- isNotificationsLoading = false,- notifications,- onBack,- onLoadPostLikers,- onOpenMessages,- onOpenFriend,- onSetPostLiked,- profile,-}) => {- const [selectedPost, setSelectedPost] =- React.useState<SocialViewerPhoto | null>(null);- const profileName = profile.fullName.trim() || profile.username.trim();- const hasNotifications = notifications.length > 0;- const openPost = (notification: SocialNotification) => {- if (!notification.postThumbnailUrl) return;-- setSelectedPost(- notification.post ?? {- alt: `${profileName} post`,- avatarUrl: profile.avatarUrl,- imageUrl: notification.postThumbnailUrl,- name: profileName,- timestampMs: notification.timestampMs,- },- );- };-- return (- <Box- component="main"- sx={{- bgcolor: notificationsBackground,- boxSizing: "border-box",- color: textBase,- display: "grid",- minHeight: "100svh",- overflowX: "hidden",- placeItems: { xs: "stretch", sm: "start center" },- }}- >- <Box- sx={{- bgcolor: notificationsBackground,- boxSizing: "border-box",- minHeight: "100svh",- mx: "auto",- position: "relative",- width: "100%",- "@media (min-width: 600px)": { maxWidth: 390 },- }}- >- <Box- component="header"- sx={{- alignItems: "center",- display: "grid",- gridTemplateColumns: "24px 1fr 24px",- height: 56,- px: 2,- width: "100%",- }}- >- <Box- component="button"- type="button"- aria-label="Back to home"- onClick={onBack}- sx={{- alignItems: "center",- bgcolor: "transparent",- border: 0,- color: textBase,- cursor: onBack ? "pointer" : "default",- display: "flex",- height: 24,- justifyContent: "flex-start",- ml: "-2px",- p: 0,- width: 24,- "&:focus-visible": {- borderRadius: "50%",- outline: `2px solid ${green}`,- outlineOffset: 2,- },- }}- >- <HugeiconsIcon- icon={ArrowLeft02Icon}- size={24}- strokeWidth={1.8}- />- </Box>- <Box- component="h1"- sx={{- color: textBase,- fontFamily: '"Inter Variable", Inter, sans-serif',- fontSize: 18,- fontWeight: 700,- justifySelf: "center",- lineHeight: "24px",- m: 0,- }}- >- Notifications- </Box>- <Box- component="button"- type="button"- aria-label="Open messages"- onClick={onOpenMessages}- sx={{- alignItems: "center",- bgcolor: "transparent",- border: 0,- color: textBase,- cursor: onOpenMessages ? "pointer" : "default",- display: "flex",- height: 24,- justifyContent: "flex-end",- p: 0,- width: 24,- "&:focus-visible": {- borderRadius: "50%",- outline: `2px solid ${green}`,- outlineOffset: 2,- },- }}- >- <HugeiconsIcon- icon={Message01Icon}- size={24}- strokeWidth={1.8}- />- </Box>- </Box>-- {hasNotifications ? (- <Box- component="ul"- sx={{- boxSizing: "border-box",- display: "flex",- flexDirection: "column",- m: 0,- mt: "21px",- pb: "28px",- pl: timelineListInset,- pr: thumbnailRightInset,- pt: 0,- width: "100%",- }}- >- {notifications.map((notification) => (- <NotificationRow- key={notification.id}- notification={notification}- onOpenFriend={onOpenFriend}- onOpenPost={openPost}- />- ))}- </Box>- ) : isNotificationsLoading ? (- <Box- sx={{- alignItems: "center",- boxSizing: "border-box",- display: "flex",- inset: 0,- justifyContent: "center",- pointerEvents: "none",- position: "absolute",- px: 3,- textAlign: "center",- }}- >- <SocialLoadingSpinner ariaLabel="Loading notifications" />- </Box>- ) : (- <Box- sx={{- alignItems: "center",- boxSizing: "border-box",- display: "flex",- flexDirection: "column",- inset: 0,- justifyContent: "center",- pointerEvents: "none",- position: "absolute",- px: 3,- textAlign: "center",- }}- >- <Box- component="h2"- sx={{- color: textBase,- fontFamily:- '"Inter Variable", Inter, sans-serif',- fontSize: 16,- fontWeight: 700,- letterSpacing: 0,- lineHeight: "22px",- m: 0,- }}- >- No notifications yet- </Box>- <Box- component="p"- sx={{- color: textSoft,- fontFamily:- '"Inter Variable", Inter, sans-serif',- fontSize: 14,- fontWeight: 500,- lineHeight: "20px",- m: 0,- mt: "8px",- maxWidth: 240,- }}- >- Likes and replies to posts, and new friends will- appear here.- </Box>- </Box>- )}- </Box>- {selectedPost && (- <SocialFileViewer- onClose={() => setSelectedPost(null)}- onLoadPostLikers={onLoadPostLikers}- photo={selectedPost}- postActionMode="like-with-count"- onSetPostLiked={onSetPostLiked}- />- )}- </Box>- );-};diff --git a/web/apps/social/src/services/socialWall.ts b/web/apps/social/src/services/socialWall.tsindex e1f86812d6..96ac13f6b8 100644--- a/web/apps/social/src/services/socialWall.ts+++ b/web/apps/social/src/services/socialWall.ts@@ -64,33 +64,34 @@ interface WallPostPage {nextCursor?: string;}-interface WallFriend {- createdAt: string;- friend: WallActor;- shareKeyVersion: number;+type WallMessageConversationActivityType =+ | "friend_add"+ | "friend_remove"+ | "message"+ | "message_like"+ | "post_like"+ | "post_like_and_reply"+ | "post_reply";++interface WallMessageConversationPost {+ objects?: WallPostObject[];+ postId: number;+ wallId: string;+ wallSlug: string;}-interface WallNotification {- actor: WallActor;+interface WallMessageConversationActivity {createdAt: string;id: string;- post?: {- author: WallActor;- objects?: WallPostObject[];- postId: number;- wallId: string;- wallSlug: string;- };- type:- | "likedPost"- | "repliedToPost"- | "addedYouAsFriend"- | "removedYouAsFriend";+ message?: WallMessage;+ post?: WallMessageConversationPost;+ type: WallMessageConversationActivityType;}-interface WallNotificationPage {- items?: WallNotification[];- nextCursor?: string;+interface WallFriend {+ createdAt: string;+ friend: WallActor;+ shareKeyVersion: number;}interface WallPostLikerPage {@@ -134,7 +135,7 @@ interface WallMessagePage {interface WallMessageConversation {friend: WallActor;- lastMessage: WallMessage;+ latestActivity: WallMessageConversationActivity;}interface WallMessageConversationPage {@@ -162,19 +163,6 @@ export interface SocialWallPostPage {nextCursor?: string;}-export interface SocialWallNotification {- actor: FriendProfile;- id: string;- post?: SocialWallPost;- timestampMs: number;- type: "added-friend" | "liked-post" | "removed-friend" | "replied-post";-}--export interface SocialWallNotificationPage {- items: SocialWallNotification[];- nextCursor?: string;-}-export interface SocialWallLink {accessKey: string;url: string;@@ -220,6 +208,27 @@ export interface SocialWallMessage {viewerLiked: boolean;}+export type SocialWallMessageActivityType = WallMessageConversationActivityType;++export interface SocialWallMessageActivityPost {+ height?: number;+ imageUrl?: string;+ mediaType?: string;+ objectKey?: string;+ postId: number;+ wallId: string;+ wallSlug: string;+ width?: number;+}++export interface SocialWallMessageActivity {+ createdAtMs: number;+ id: string;+ message?: SocialWallMessage;+ post?: SocialWallMessageActivityPost;+ type: SocialWallMessageActivityType;+}+export interface SocialWallMessagePage {items: SocialWallMessage[];nextCursor?: string;@@ -227,7 +236,7 @@ export interface SocialWallMessagePage {export interface SocialWallMessageConversation {friend: FriendProfile;- lastMessage: SocialWallMessage;+ latestActivity: SocialWallMessageActivity;}export interface SocialWallMessageConversationPage {@@ -303,9 +312,14 @@ const accountAvatarURL = async (avatar: WallAvatar | undefined,) => {if (!wallId || !avatar?.objectKey) return null;- return blobURLForBytes(- await ctx.download_wall_avatar(wallId, avatar.objectKey),- );+ try {+ return blobURLForBytes(+ await ctx.download_wall_avatar(wallId, avatar.objectKey),+ );+ } catch (error) {+ console.warn("Failed to load wall avatar", error);+ return null;+ }};const linkAvatarURL = async (@@ -475,6 +489,57 @@ const messageFromWallMessage = async (};};+const messageActivityPostFromWallPost = async (+ ctx: WallAccountCtxHandle,+ post: WallMessageConversationPost | undefined,+): Promise<SocialWallMessageActivityPost | undefined> => {+ if (!post) return undefined;++ const object = firstObject(post);+ const socialPost: SocialWallMessageActivityPost = {+ height: object?.height,+ mediaType: object?.mediaType,+ objectKey: object?.objectKey,+ postId: post.postId,+ wallId: post.wallId,+ wallSlug: post.wallSlug,+ width: object?.width,+ };+ if (!object?.objectKey) return socialPost;++ try {+ socialPost.imageUrl = blobURLForBytes(+ await ctx.download_post_asset(+ BigInt(post.postId),+ object.objectKey,+ ),+ object.mediaType,+ );+ } catch (error) {+ console.warn("Failed to load message activity post image", error);+ }+ return socialPost;+};++const messageActivityFromWallActivity = async (+ ctx: WallAccountCtxHandle,+ activity: WallMessageConversationActivity,+): Promise<SocialWallMessageActivity> => {+ const [message, post] = await Promise.all([+ activity.message+ ? messageFromWallMessage(ctx, activity.message, false)+ : undefined,+ messageActivityPostFromWallPost(ctx, activity.post),+ ]);+ return {+ createdAtMs: timestampMsFromWallDate(activity.createdAt),+ id: activity.id,+ message,+ post,+ type: activity.type,+ };+};+export const createCurrentProfileLink = async (wallId: string,): Promise<SocialWallLink> => {@@ -730,10 +795,9 @@ export const loadCurrentMessageConversations =);return {friend,- lastMessage: await messageFromWallMessage(+ latestActivity: await messageActivityFromWallActivity(ctx,- conversation.lastMessage,- false,+ conversation.latestActivity,),};}),@@ -776,64 +840,6 @@ export const deleteCurrentPost = async (postId: number) => {}};-export const loadCurrentNotificationsPage =- async (): Promise<SocialWallNotificationPage> => {- const ctx = await ensureCurrentWallContext();- try {- const page = (await ctx.list_notifications(- null,- 50,- )) as WallNotificationPage;- const items = await Promise.all(- (page.items ?? []).map(async (notification) => {- const actor = actorProfile(notification.actor);- actor.avatarUrl = await accountAvatarURL(- ctx,- notification.actor.wallId,- notification.actor.avatar,- );- const postObject = notification.post- ? firstObject(notification.post)- : null;- const post =- notification.post && postObject- ? await postFromAccountPost(ctx, {- author: notification.post.author,- createdAt: notification.createdAt,- likes: 0,- objects: notification.post.objects,- postId: notification.post.postId,- viewerLiked: false,- wallId: notification.post.wallId,- wallSlug: notification.post.wallSlug,- })- : undefined;- let notificationType: SocialWallNotification["type"] =- "liked-post";- if (notification.type == "addedYouAsFriend") {- notificationType = "added-friend";- } else if (notification.type == "removedYouAsFriend") {- notificationType = "removed-friend";- } else if (notification.type == "repliedToPost") {- notificationType = "replied-post";- }- return {- actor,- id: notification.id,- post: post ?? undefined,- timestampMs: timestampMsFromWallDate(- notification.createdAt,- ),- type: notificationType,- };- }),- );- return { items, nextCursor: page.nextCursor || undefined };- } finally {- ctx.free();- }- };-export const loadPublicSocialInvite = async ({accessKey,wallUsername,diff --git a/web/apps/social/src/utils/socialRoutes.ts b/web/apps/social/src/utils/socialRoutes.tsindex f57dcf37b3..a10f513358 100644--- a/web/apps/social/src/utils/socialRoutes.ts+++ b/web/apps/social/src/utils/socialRoutes.ts@@ -1,9 +1,5 @@export type SetupProfileSource = "login" | "verify";-export type FriendProfileSource =- | "friends"- | "home"- | "notifications"- | "profile";+export type FriendProfileSource = "friends" | "home" | "profile";export type VerifyFlow = "login" | "signup";export const onboardingSourceSearchParam = "onboardingSource";@@ -19,7 +15,6 @@ export const socialRoutes = {home: "/app",invite: "/invite",login: "/login",- messages: "/app/messages",notifications: "/app/notifications",onboarding: "/",passkeysFinish: "/passkeys/finish",@@ -47,10 +42,7 @@ export const friendProfileSourceFromQuery = (value: string | string[] | undefined,): FriendProfileSource => {const from = valueFromQuery(value);- return from == "home" ||- from == "notifications" ||- from == "profile" ||- from == "friends"+ return from == "home" || from == "profile" || from == "friends"? from: "friends";};diff --git a/web/apps/social/src/utils/socialWallDisplay.ts b/web/apps/social/src/utils/socialWallDisplay.tsindex 224feaaa7d..90768f9c15 100644--- a/web/apps/social/src/utils/socialWallDisplay.ts+++ b/web/apps/social/src/utils/socialWallDisplay.ts@@ -1,6 +1,6 @@import type { SocialViewerPhoto } from "components/SocialFileViewer";import type { ProfilePostGroup } from "screens/ProfileScreen";-import type { SocialWallNotification, SocialWallPost } from "services/socialWall";+import type { SocialWallPost } from "services/socialWall";export const socialPostToViewerPhoto = (post: SocialWallPost,@@ -57,16 +57,3 @@ export const profilePostGroupsFromPosts = (});return [...groups.values()];};--export const notificationForScreen = (- notification: SocialWallNotification,-) => ({- actor: notification.actor,- id: notification.id,- post: notification.post- ? socialPostToViewerPhoto(notification.post)- : undefined,- postThumbnailUrl: notification.post?.imageUrl,- timestampMs: notification.timestampMs,- type: notification.type,-});diff --git a/web/packages/wasm/src/wall.rs b/web/packages/wasm/src/wall.rsindex 9647a28bcb..9905f6c62b 100644--- a/web/packages/wasm/src/wall.rs+++ b/web/packages/wasm/src/wall.rs@@ -3,9 +3,10 @@use ente_core::http::Error as HttpError;use ente_wall::{AccountWallCtx, AuthKeyAttributes, CreatedWall, CreatedWallLink, DecryptedMessage,- DecryptedPost, DecryptedWallProfile, MessageResponse, OpenAccountWallCtxInput,- OpenWallLinkCtxInput, PostResponse, PrivateKeySource, ProfileAvatarResponse, WallActorResponse,- WallError as CoreWallError, WallLinkCtx, WallNotification, WallNotificationPost,+ DecryptedPost, DecryptedWallProfile, MessageConversationActivity, MessageConversationPost,+ MessageResponse, OpenAccountWallCtxInput, OpenWallLinkCtxInput, PostResponse, PrivateKeySource,+ ProfileAvatarResponse, WallActorResponse, WallError as CoreWallError, WallLinkCtx,+ WallNotification, WallNotificationPost,crypto::{decode_b64, encode_b64},};use serde::{Deserialize, Serialize};@@ -255,7 +256,28 @@ struct MessagePageJs {#[serde(rename_all = "camelCase")]struct MessageConversationJs {friend: ActorJs,- last_message: MessageJs,+ latest_activity: MessageConversationActivityJs,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct MessageConversationActivityJs {+ id: String,+ #[serde(rename = "type")]+ activity_type: String,+ created_at: String,+ message: Option<MessageJs>,+ post: Option<MessageConversationPostJs>,+}++#[derive(Serialize)]+#[serde(rename_all = "camelCase")]+struct MessageConversationPostJs {+ post_id: i64,+ wall_id: String,+ wall_slug: String,+ owner_user_id: i64,+ objects: Vec<ente_wall::PostObjectPayload>,}#[derive(Serialize)]@@ -493,6 +515,36 @@ async fn account_message_to_js(})}+async fn message_conversation_activity_to_js(+ ctx: &AccountWallCtx,+ activity: MessageConversationActivity,+) -> Result<MessageConversationActivityJs, WasmWallError> {+ let message = match activity.message {+ Some(message) => {+ let decrypted = ctx.decrypt_message(&message)?;+ Some(account_message_to_js(ctx, message, decrypted).await?)+ }+ None => None,+ };+ Ok(MessageConversationActivityJs {+ id: activity.id,+ activity_type: activity.activity_type,+ created_at: activity.created_at,+ message,+ post: activity.post.map(message_conversation_post_to_js),+ })+}++fn message_conversation_post_to_js(post: MessageConversationPost) -> MessageConversationPostJs {+ MessageConversationPostJs {+ post_id: post.post_id,+ wall_id: post.wall_id,+ wall_slug: post.wall_slug,+ owner_user_id: post.owner_user_id,+ objects: post.objects,+ }+}+/// Open an authenticated wall context for web.#[wasm_bindgen]pub async fn wall_open_account_ctx(input: JsValue) -> Result<WallAccountCtxHandle, WasmWallError> {@@ -884,7 +936,7 @@ impl WallAccountCtxHandle {.map_err(Into::into)}- /// List 1:1 message conversations with decrypted last messages.+ /// List 1:1 message conversations with decrypted latest activity messages.pub async fn list_message_conversations(&self,cursor: Option<String>,@@ -894,13 +946,11 @@ impl WallAccountCtxHandle {let mut items = Vec::with_capacity(page.items.len());for conversation in page.items {let friend = account_actor_to_js(&self.inner, conversation.friend).await?;- let decrypted = self.inner.decrypt_message(&conversation.last_message)?;items.push(MessageConversationJs {friend,- last_message: account_message_to_js(+ latest_activity: message_conversation_activity_to_js(&self.inner,- conversation.last_message,- decrypted,+ conversation.latest_activity,).await?,});